changeset 2759:b53f226b1d91 jdk7-b112

Merge
author lana
date Fri, 24 Sep 2010 16:41:32 -0700
parents c2cdc8c94b65 (current diff) 61f1bbd49a5e (diff)
children 61d3b9fbb26b ad17cf689258 a601a6711ef8 b57ca6031a35 4b0fdb9f7cfe
files src/share/classes/com/sun/media/sound/MidiDeviceReceiver.java src/share/native/sun/java2d/cmm/lcms/cmscam97.c src/share/native/sun/java2d/cmm/lcms/cmsmatsh.c src/share/native/sun/java2d/cmm/lcms/icc34.h src/share/native/sun/java2d/cmm/lcms/lcms.h src/solaris/classes/sun/net/spi/SdpProvider.java src/solaris/native/sun/net/spi/SdpProvider.c test/java/util/Locale/data/deflocale.exe test/java/util/Locale/data/deflocale.jds3 test/java/util/Locale/data/deflocale.rhel4 test/java/util/Locale/data/deflocale.winvista test/java/util/Locale/data/deflocale.winxp test/tools/launcher/VerifyExceptions.java
diffstat 319 files changed, 60565 insertions(+), 33095 deletions(-) [+]
line wrap: on
line diff
--- a/make/com/Makefile	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/com/Makefile	Fri Sep 24 16:41:32 2010 -0700
@@ -31,7 +31,7 @@
 PRODUCT = com
 include $(BUILDDIR)/common/Defs.gmk
 
-SUBDIRS = sun
+SUBDIRS = sun oracle
 include $(BUILDDIR)/common/Subdirs.gmk
 
 all build clean clobber::
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/com/oracle/Makefile	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,34 @@
+#
+# Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+BUILDDIR = ../..
+PRODUCT = oracle
+include $(BUILDDIR)/common/Defs.gmk
+
+SUBDIRS = net
+include $(BUILDDIR)/common/Subdirs.gmk
+
+all build clean clobber::
+	$(SUBDIRS-loop)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/com/oracle/net/Makefile	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,39 @@
+#
+# Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+BUILDDIR = ../../..
+PRODUCT = oracle
+include $(BUILDDIR)/common/Defs.gmk
+
+#
+# Files to compile
+#
+AUTO_FILES_JAVA_DIRS = com/oracle/net
+
+#
+# Rules
+#
+include $(BUILDDIR)/common/Classes.gmk
+
--- a/make/common/Release.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/common/Release.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -573,13 +573,13 @@
 	$(ECHO) "sun/jvmstat/" >> $@
 	$(ECHO) "sun/nio/cs/ext/" >> $@
 	$(ECHO) "sun/awt/HKSCS.class" >> $@
-	$(ECHO) "sun/awt/motif/X11GB2312$Decoder.class" >> $@
-	$(ECHO) "sun/awt/motif/X11GB2312$Encoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11GB2312\$$Decoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11GB2312\$$Encoder.class" >> $@
 	$(ECHO) "sun/awt/motif/X11GB2312.class" >> $@
-	$(ECHO) "sun/awt/motif/X11GBK$Encoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11GBK\$$Encoder.class" >> $@
 	$(ECHO) "sun/awt/motif/X11GBK.class" >> $@
-	$(ECHO) "sun/awt/motif/X11KSC5601$Decoder.class" >> $@
-	$(ECHO) "sun/awt/motif/X11KSC5601$Encoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11KSC5601\$$Decoder.class" >> $@
+	$(ECHO) "sun/awt/motif/X11KSC5601\$$Encoder.class" >> $@
 	$(ECHO) "sun/awt/motif/X11KSC5601.class" >> $@
 	$(ECHO) "sun/rmi/rmic/" >> $@
 	$(ECHO) "sun/tools/asm/" >> $@
--- a/make/docs/NON_CORE_PKGS.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/docs/NON_CORE_PKGS.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -91,6 +91,8 @@
 TRACING_PKGS     = com.sun.tracing         \
                    com.sun.tracing.dtrace
 
+ORACLENET_PKGS   = com.oracle.net
+
 # non-core packages in rt.jar
 NON_CORE_PKGS    = $(DOMAPI_PKGS) \
                    $(MGMT_PKGS) \
@@ -101,5 +103,6 @@
                    $(HTTPSERVER_PKGS) \
                    $(SMARTCARDIO_PKGS) \
                    $(TRACING_PKGS) \
-                   $(SCTPAPI_PKGS)
+                   $(SCTPAPI_PKGS) \
+                   $(ORACLENET_PKGS)
 
--- a/make/java/java/FILES_java.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/java/java/FILES_java.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -183,10 +183,22 @@
         java/util/MissingFormatWidthException.java \
         java/util/UnknownFormatConversionException.java \
         java/util/UnknownFormatFlagsException.java \
+    java/util/IllformedLocaleException.java \
     java/util/FormatterClosedException.java \
     java/util/ListResourceBundle.java \
         sun/util/EmptyListResourceBundle.java \
     java/util/Locale.java \
+        sun/util/locale/AsciiUtil.java \
+        sun/util/locale/BaseLocale.java \
+        sun/util/locale/Extension.java \
+        sun/util/locale/InternalLocaleBuilder.java \
+        sun/util/locale/LanguageTag.java \
+        sun/util/locale/LocaleExtensions.java \
+        sun/util/locale/LocaleObjectCache.java \
+        sun/util/locale/LocaleSyntaxException.java \
+        sun/util/locale/ParseStatus.java \
+        sun/util/locale/StringTokenIterator.java \
+        sun/util/locale/UnicodeLocaleExtension.java \
     java/util/LocaleISOData.java \
         sun/util/LocaleServiceProviderPool.java \
 	sun/util/LocaleDataMetaInfo.java \
--- a/make/java/net/FILES_c.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/java/net/FILES_c.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -39,10 +39,6 @@
 	ResolverConfigurationImpl.c \
 	DefaultProxySelector.c
 
-ifeq ($(PLATFORM), solaris)
-    FILES_c += SdpProvider.c
-endif
-
 ifeq ($(PLATFORM), linux)
     FILES_c += linux_close.c
 endif
--- a/make/java/net/Makefile	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/java/net/Makefile	Fri Sep 24 16:41:32 2010 -0700
@@ -44,6 +44,8 @@
     endif
     FILES_c += NTLMAuthSequence.c
     FILES_c += NetworkInterface_winXP.c
+else
+    FILES_c += SdpSupport.c
 endif
 
 FILES_export = \
@@ -84,7 +86,8 @@
 #
 # Find platform specific native code
 #
-vpath %.c $(PLATFORM_SRC)/native/sun/net/dns $(PLATFORM_SRC)/native/sun/net/www/protocol/http/ntlm $(PLATFORM_SRC)/native/sun/net/spi
+vpath %.c $(PLATFORM_SRC)/native/sun/net/dns $(PLATFORM_SRC)/native/sun/net/www/protocol/http/ntlm \
+    $(PLATFORM_SRC)/native/sun/net/sdp $(PLATFORM_SRC)/native/sun/net/spi
 
 #
 # Include rules
--- a/make/java/net/mapfile-vers	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/java/net/mapfile-vers	Fri Sep 24 16:41:32 2010 -0700
@@ -88,9 +88,10 @@
 		Java_java_net_PlainDatagramSocketImpl_setTimeToLive;
 		Java_sun_net_dns_ResolverConfigurationImpl_localDomain0;
 		Java_sun_net_dns_ResolverConfigurationImpl_fallbackDomain0;
+		Java_sun_net_sdp_SdpSupport_convert0;
+		Java_sun_net_sdp_SdpSupport_create0;
 		Java_sun_net_spi_DefaultProxySelector_init;
 		Java_sun_net_spi_DefaultProxySelector_getSystemProxy;
-		Java_sun_net_spi_SdpProvider_convert;
 		NET_AllocSockaddr;
 		NET_SockaddrToInetAddress;
                 NET_SockaddrEqualsInetAddress;
--- a/make/java/nio/FILES_java.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/java/nio/FILES_java.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -83,6 +83,7 @@
 	java/nio/file/ClosedFileSystemException.java \
 	java/nio/file/ClosedWatchServiceException.java \
 	java/nio/file/CopyOption.java \
+	java/nio/file/DirectoryIteratorException.java \
 	java/nio/file/DirectoryNotEmptyException.java \
 	java/nio/file/DirectoryStream.java \
 	java/nio/file/FileAlreadyExistsException.java \
@@ -199,6 +200,7 @@
 	sun/nio/ch/PipeImpl.java \
 	sun/nio/ch/PollArrayWrapper.java \
 	sun/nio/ch/Reflect.java \
+	sun/nio/ch/Secrets.java \
 	sun/nio/ch/SelectionKeyImpl.java \
 	sun/nio/ch/SelectorImpl.java \
 	sun/nio/ch/SelectorProviderImpl.java \
--- a/make/java/nio/mapfile-linux	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/java/nio/mapfile-linux	Fri Sep 24 16:41:32 2010 -0700
@@ -89,7 +89,7 @@
                 Java_sun_nio_ch_IOUtil_drain;
                 Java_sun_nio_ch_IOUtil_fdVal;
                 Java_sun_nio_ch_IOUtil_initIDs;
-                Java_sun_nio_ch_IOUtil_initPipe;
+                Java_sun_nio_ch_IOUtil_makePipe;
                 Java_sun_nio_ch_IOUtil_randomBytes;
                 Java_sun_nio_ch_IOUtil_setfdVal;
 		Java_sun_nio_ch_NativeThread_current;
--- a/make/java/nio/mapfile-solaris	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/java/nio/mapfile-solaris	Fri Sep 24 16:41:32 2010 -0700
@@ -76,7 +76,7 @@
                 Java_sun_nio_ch_IOUtil_drain;
                 Java_sun_nio_ch_IOUtil_fdVal;
                 Java_sun_nio_ch_IOUtil_initIDs;
-                Java_sun_nio_ch_IOUtil_initPipe;
+                Java_sun_nio_ch_IOUtil_makePipe;
                 Java_sun_nio_ch_IOUtil_randomBytes;
                 Java_sun_nio_ch_IOUtil_setfdVal;
 		Java_sun_nio_ch_NativeThread_current;
--- a/make/java/text/base/FILES_java.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/java/text/base/FILES_java.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -29,6 +29,7 @@
     java/text/AttributedString.java \
     java/text/BreakDictionary.java \
     java/text/BreakIterator.java \
+    java/text/CalendarBuilder.java \
     java/text/CharacterIterator.java \
     java/text/CharacterIteratorFieldDelegate.java \
     java/text/ChoiceFormat.java \
--- a/make/sun/cmm/lcms/FILES_c_unix.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/sun/cmm/lcms/FILES_c_unix.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -25,7 +25,6 @@
 
 FILES_c = \
     cmscam02.c \
-    cmscam97.c \
     cmscgats.c \
     cmscnvrt.c \
     cmserr.c \
@@ -35,13 +34,17 @@
     cmsio0.c \
     cmsio1.c \
     cmslut.c \
-    cmsmatsh.c \
+    cmsmd5.c \
     cmsmtrx.c \
     cmsnamed.c \
+    cmsopt.c \
     cmspack.c \
     cmspcs.c \
+    cmsplugin.c \
     cmsps2.c \
     cmssamp.c \
+    cmssm.c \
+    cmstypes.c \
     cmsvirt.c \
     cmswtpnt.c \
     cmsxform.c \
--- a/make/sun/cmm/lcms/FILES_c_windows.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/sun/cmm/lcms/FILES_c_windows.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -25,7 +25,6 @@
 
 FILES_c = \
     cmscam02.c \
-    cmscam97.c \
     cmscgats.c \
     cmscnvrt.c \
     cmserr.c \
@@ -35,13 +34,17 @@
     cmsio0.c \
     cmsio1.c \
     cmslut.c \
-    cmsmatsh.c \
+    cmsmd5.c \
     cmsmtrx.c \
     cmsnamed.c \
+    cmsopt.c \
     cmspack.c \
     cmspcs.c \
+    cmsplugin.c \
     cmsps2.c \
     cmssamp.c \
+    cmssm.c \
+    cmstypes.c \
     cmsvirt.c \
     cmswtpnt.c \
     cmsxform.c \
--- a/make/sun/cmm/lcms/Makefile	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/sun/cmm/lcms/Makefile	Fri Sep 24 16:41:32 2010 -0700
@@ -80,8 +80,8 @@
 vpath %.c   $(SHARE_SRC)/native/sun/java2d
 
 ifeq ($(PLATFORM), windows)
-
-OTHER_LDLIBS = user32.lib version.lib $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib
+OTHER_CFLAGS += -DCMS_IS_WINDOWS_ -Dsqrtf=sqrt
+OTHER_LDLIBS = $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib
 OTHER_INCLUDES += -I$(SHARE_SRC)/native/sun/java2d \
                   -I$(SHARE_SRC)/native/sun/awt/debug
 
--- a/make/sun/net/FILES_java.gmk	Thu Sep 23 17:33:40 2010 -0700
+++ b/make/sun/net/FILES_java.gmk	Fri Sep 24 16:41:32 2010 -0700
@@ -53,6 +53,7 @@
 	sun/net/ftp/FtpProtocolException.java \
 	sun/net/ftp/impl/FtpClient.java \
 	sun/net/ftp/impl/DefaultFtpClientProvider.java \
+	sun/net/sdp/SdpSupport.java \
 	sun/net/spi/DefaultProxySelector.java \
 	sun/net/spi/nameservice/NameServiceDescriptor.java \
 	sun/net/spi/nameservice/NameService.java \
@@ -136,8 +137,6 @@
 
 ifeq ($(PLATFORM), windows)
     FILES_java += sun/net/www/protocol/http/ntlm/NTLMAuthSequence.java 
+else
+    FILES_java += sun/net/sdp/SdpProvider.java
 endif
-
-ifeq ($(PLATFORM), solaris)
-    FILES_java += sun/net/spi/SdpProvider.java
-endif
--- a/src/share/bin/java.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/bin/java.c	Fri Sep 24 16:41:32 2010 -0700
@@ -712,19 +712,19 @@
     struct stat statbuf;
 
     /* return if jre/lib/rt.jar exists */
-    sprintf(pathname, "%s%slib%srt.jar", jrepath, separator, separator);
+    JLI_Snprintf(pathname, sizeof(pathname), "%s%slib%srt.jar", jrepath, separator, separator);
     if (stat(pathname, &statbuf) == 0) {
         return;
     }
 
     /* return if jre/classes exists */
-    sprintf(pathname, "%s%sclasses", jrepath, separator);
+    JLI_Snprintf(pathname, sizeof(pathname), "%s%sclasses", jrepath, separator);
     if (stat(pathname, &statbuf) == 0) {
         return;
     }
 
     /* modularized jre */
-    sprintf(pathname, "%s%slib%s*", jrepath, separator, separator);
+    JLI_Snprintf(pathname, sizeof(pathname), "%s%slib%s*", jrepath, separator, separator);
     s = (char *) JLI_WildcardExpandClasspath(pathname);
     def = JLI_MemAlloc(sizeof(format)
                        - 2 /* strlen("%s") */
@@ -1624,11 +1624,8 @@
     if (JLI_IsTraceLauncher()) {
         start = CounterGet();
     }
-
-    JLI_StrCpy(jvmCfgName, jrepath);
-    JLI_StrCat(jvmCfgName, FILESEP "lib" FILESEP);
-    JLI_StrCat(jvmCfgName, arch);
-    JLI_StrCat(jvmCfgName, FILESEP "jvm.cfg");
+    JLI_Snprintf(jvmCfgName, sizeof(jvmCfgName), "%s%slib%s%s%sjvm.cfg",
+        jrepath, FILESEP, FILESEP, arch, FILESEP);
 
     jvmCfg = fopen(jvmCfgName, "r");
     if (jvmCfg == NULL) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/oracle/net/Sdp.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.net;
+
+import java.net.Socket;
+import java.net.ServerSocket;
+import java.net.SocketImpl;
+import java.net.SocketImplFactory;
+import java.net.SocketException;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.ServerSocketChannel;
+import java.io.IOException;
+import java.io.FileDescriptor;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.InvocationTargetException;
+
+import sun.net.sdp.SdpSupport;
+
+/**
+ * This class consists exclusively of static methods that Sockets or Channels to
+ * sockets that support the InfiniBand Sockets Direct Protocol (SDP).
+ */
+
+public final class Sdp {
+    private Sdp() { }
+
+    /**
+     * The package-privage ServerSocket(SocketImpl) constructor
+     */
+    private static final Constructor<ServerSocket> serverSocketCtor;
+    static {
+        try {
+            serverSocketCtor = (Constructor<ServerSocket>)
+                ServerSocket.class.getDeclaredConstructor(SocketImpl.class);
+            setAccessible(serverSocketCtor);
+        } catch (NoSuchMethodException e) {
+            throw new AssertionError(e);
+        }
+    }
+
+    /**
+     * The package-private SdpSocketImpl() constructor
+     */
+    private static final Constructor<SocketImpl> socketImplCtor;
+    static {
+        try {
+            Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null);
+            socketImplCtor = (Constructor<SocketImpl>)cl.getDeclaredConstructor();
+            setAccessible(socketImplCtor);
+        } catch (ClassNotFoundException e) {
+            throw new AssertionError(e);
+        } catch (NoSuchMethodException e) {
+            throw new AssertionError(e);
+        }
+    }
+
+    private static void setAccessible(final AccessibleObject o) {
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
+            public Void run() {
+                o.setAccessible(true);
+                return null;
+            }
+        });
+    }
+
+    /**
+     * SDP enabled Socket.
+     */
+    private static class SdpSocket extends Socket {
+        SdpSocket(SocketImpl impl) throws SocketException {
+            super(impl);
+        }
+    }
+
+    /**
+     * Creates a SDP enabled SocketImpl
+     */
+    private static SocketImpl createSocketImpl() {
+        try {
+            return socketImplCtor.newInstance();
+        } catch (InstantiationException x) {
+            throw new AssertionError(x);
+        } catch (IllegalAccessException x) {
+            throw new AssertionError(x);
+        } catch (InvocationTargetException x) {
+            throw new AssertionError(x);
+        }
+    }
+
+    /**
+     * Creates an unconnected and unbound SDP socket. The {@code Socket} is
+     * associated with a {@link java.net.SocketImpl} of the system-default type.
+     *
+     * @return  a new Socket
+     *
+     * @throws  UnsupportedOperationException
+     *          If SDP is not supported
+     * @throws  IOException
+     *          If an I/O error occurs
+     */
+    public static Socket openSocket() throws IOException {
+        SocketImpl impl = createSocketImpl();
+        return new SdpSocket(impl);
+    }
+
+    /**
+     * Creates an unbound SDP server socket. The {@code ServerSocket} is
+     * associated with a {@link java.net.SocketImpl} of the system-default type.
+     *
+     * @return  a new ServerSocket
+     *
+     * @throws  UnsupportedOperationException
+     *          If SDP is not supported
+     * @throws  IOException
+     *          If an I/O error occurs
+     */
+    public static ServerSocket openServerSocket() throws IOException {
+        // create ServerSocket via package-private constructor
+        SocketImpl impl = createSocketImpl();
+        try {
+            return serverSocketCtor.newInstance(impl);
+        } catch (IllegalAccessException x) {
+            throw new AssertionError(x);
+        } catch (InstantiationException x) {
+            throw new AssertionError(x);
+        } catch (InvocationTargetException x) {
+            Throwable cause = x.getCause();
+            if (cause instanceof IOException)
+                throw (IOException)cause;
+            if (cause instanceof RuntimeException)
+                throw (RuntimeException)cause;
+            throw new RuntimeException(x);
+        }
+    }
+
+    /**
+     * Opens a socket channel to a SDP socket.
+     *
+     * <p> The channel will be associated with the system-wide default
+     * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}.
+     *
+     * @return  a new SocketChannel
+     *
+     * @throws  UnsupportedOperationException
+     *          If SDP is not supported or not supported by the default selector
+     *          provider
+     * @throws  IOException
+     *          If an I/O error occurs.
+     */
+    public static SocketChannel openSocketChannel() throws IOException {
+        FileDescriptor fd = SdpSupport.createSocket();
+        return sun.nio.ch.Secrets.newSocketChannel(fd);
+    }
+
+    /**
+     * Opens a socket channel to a SDP socket.
+     *
+     * <p> The channel will be associated with the system-wide default
+     * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}.
+     *
+     * @return  a new ServerSocketChannel
+     *
+     * @throws  UnsupportedOperationException
+     *          If SDP is not supported or not supported by the default selector
+     *          provider
+     * @throws  IOException
+     *          If an I/O error occurs
+     */
+    public static ServerSocketChannel openServerSocketChannel()
+        throws IOException
+    {
+        FileDescriptor fd = SdpSupport.createSocket();
+        return sun.nio.ch.Secrets.newServerSocketChannel(fd);
+    }
+}
--- a/src/share/classes/com/sun/java/swing/SwingUtilities3.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/java/swing/SwingUtilities3.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, Oracle and/or its affiliates. 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
@@ -31,13 +31,14 @@
 import java.util.Map;
 import java.util.WeakHashMap;
 import java.util.concurrent.Callable;
+import java.applet.Applet;
 import java.awt.AWTEvent;
 import java.awt.EventQueue;
 import java.awt.Component;
 import java.awt.Container;
+import java.awt.Window;
 import javax.swing.JComponent;
 import javax.swing.RepaintManager;
-import javax.swing.SwingUtilities;
 
 /**
  * A collection of utility methods for Swing.
@@ -91,7 +92,7 @@
      */
     public static void setVsyncRequested(Container rootContainer,
                                          boolean isRequested) {
-        assert SwingUtilities.getRoot(rootContainer) == rootContainer;
+        assert (rootContainer instanceof Applet) || (rootContainer instanceof Window);
         if (isRequested) {
             vsyncedMap.put(rootContainer, Boolean.TRUE);
         } else {
@@ -106,7 +107,7 @@
      * @return {@code true} if vsync painting is requested for {@code rootContainer}
      */
     public static boolean isVsyncRequested(Container rootContainer) {
-        assert SwingUtilities.getRoot(rootContainer) == rootContainer;
+        assert (rootContainer instanceof Applet) || (rootContainer instanceof Window);
         return Boolean.TRUE == vsyncedMap.get(rootContainer);
     }
 
--- a/src/share/classes/com/sun/java/swing/plaf/gtk/GTKPainter.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/java/swing/plaf/gtk/GTKPainter.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, Oracle and/or its affiliates. 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
@@ -399,7 +399,7 @@
         }
 
         String detail = "arrow";
-        if (name == "ScrollBar.button") {
+        if ((name == "ScrollBar.button") || (name == "TabbedPane.button")) {
             if (arrowType == ArrowType.UP || arrowType == ArrowType.DOWN) {
                 detail = "vscrollbar";
             } else {
@@ -409,7 +409,7 @@
                    name == "Spinner.previousButton") {
             detail = "spinbutton";
         } else if (name != "ComboBox.arrowButton") {
-            assert false;
+            assert false : "unexpected name: " + name;
         }
 
         int gtkState = GTKLookAndFeel.synthStateToGTKState(
@@ -436,7 +436,7 @@
         String name = button.getName();
         String detail = "button";
         int direction = SwingConstants.CENTER;
-        if (name == "ScrollBar.button") {
+        if ((name == "ScrollBar.button") || (name == "TabbedPane.button")) {
             Integer prop = (Integer)
                 button.getClientProperty("__arrow_direction__");
             direction = (prop != null) ?
@@ -457,7 +457,7 @@
         } else if (name == "Spinner.nextButton") {
             detail = "spinbutton_up";
         } else if (name != "ComboBox.arrowButton") {
-            assert false;
+            assert false : "unexpected name: " + name;
         }
 
         int state = context.getComponentState();
--- a/src/share/classes/com/sun/java/swing/plaf/gtk/PangoFonts.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/java/swing/plaf/gtk/PangoFonts.java	Fri Sep 24 16:41:32 2010 -0700
@@ -150,11 +150,6 @@
          * case for it to be a problem the values would have to be different.
          * It also seems unlikely to arise except when a user explicitly
          * deletes the X resource database entry.
-         * 3) Because of rounding errors sizes may differ very slightly
-         * between JDK and GTK. To fix that would at the very least require
-         * Swing to specify floating pt font sizes.
-         * Eg "10 pts" for GTK at 96 dpi to get the same size at Java 2D's
-         * 72 dpi you'd need to specify exactly 13.33.
          * There also some other issues to be aware of for the future:
          * GTK specifies the Xft.dpi value as server-wide which when used
          * on systems with 2 distinct X screens with different physical DPI
@@ -197,11 +192,16 @@
         String fcFamilyLC = family.toLowerCase();
         if (FontUtilities.mapFcName(fcFamilyLC) != null) {
             /* family is a Fc/Pango logical font which we need to expand. */
-           return FontUtilities.getFontConfigFUIR(fcFamilyLC, style, size);
+            Font font =  FontUtilities.getFontConfigFUIR(fcFamilyLC, style, size);
+            font = font.deriveFont(style, (float)dsize);
+            return new FontUIResource(font);
         } else {
             /* It's a physical font which we will create with a fallback */
-            Font font = new FontUIResource(family, style, size);
-            return FontUtilities.getCompositeFontUIResource(font);
+            Font font = new Font(family, style, size);
+            /* a roundabout way to set the font size in floating points */
+            font = font.deriveFont(style, (float)dsize);
+            FontUIResource fuir = new FontUIResource(font);
+            return FontUtilities.getCompositeFontUIResource(fuir);
         }
     }
 
--- a/src/share/classes/com/sun/java/swing/plaf/motif/MotifBorders.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/java/swing/plaf/motif/MotifBorders.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. 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
@@ -40,8 +40,6 @@
 import java.awt.Point;
 import java.awt.Rectangle;
 
-import java.io.Serializable;
-
 /**
  * Factory object that can vend Icons appropriate for the basic L & F.
  * <p>
@@ -99,7 +97,7 @@
         }
 
         public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
-            if (((JComponent)c).hasFocus()) {
+            if (c.hasFocus()) {
                 g.setColor(focus);
                 g.drawRect(x, y, w-1, h-1);
             } else {
@@ -233,6 +231,9 @@
         }
 
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
+            if (!(c instanceof JMenuBar)) {
+                return;
+            }
             JMenuBar menuBar = (JMenuBar)c;
             if (menuBar.isBorderPainted() == true) {
                 // this draws the MenuBar border
@@ -658,6 +659,9 @@
          * @param height the height of the painted border
          */
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
+            if (!(c instanceof JPopupMenu)) {
+                return;
+            }
 
             Font origFont = g.getFont();
             Color origColor = g.getColor();
@@ -701,6 +705,9 @@
          * @param insets the object to be reinitialized
          */
         public Insets getBorderInsets(Component c, Insets insets) {
+            if (!(c instanceof JPopupMenu)) {
+                return insets;
+            }
             FontMetrics fm;
             int         descent = 0;
             int         ascent = 16;
--- a/src/share/classes/com/sun/java/swing/plaf/windows/WindowsBorders.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/java/swing/plaf/windows/WindowsBorders.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2010, Oracle and/or its affiliates. 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
@@ -32,12 +32,8 @@
 
 import java.awt.Component;
 import java.awt.Insets;
-import java.awt.Dimension;
-import java.awt.Image;
-import java.awt.Rectangle;
 import java.awt.Color;
 import java.awt.Graphics;
-import java.io.Serializable;
 
 import static com.sun.java.swing.plaf.windows.TMSchema.*;
 import static com.sun.java.swing.plaf.windows.XPStyle.Skin;
@@ -159,6 +155,9 @@
 
         public void paintBorder(Component c, Graphics g, int x, int y,
                                 int width, int height) {
+            if (!(c instanceof JToolBar)) {
+                return;
+            }
             g.translate(x, y);
 
             XPStyle xp = XPStyle.getXP();
@@ -190,33 +189,33 @@
 
                 } else {
 
-                if (!vertical) {
-                    if (c.getComponentOrientation().isLeftToRight()) {
+                    if (!vertical) {
+                        if (c.getComponentOrientation().isLeftToRight()) {
+                            g.setColor(shadow);
+                            g.drawLine(4, 3, 4, height - 4);
+                            g.drawLine(4, height - 4, 2, height - 4);
+
+                            g.setColor(highlight);
+                            g.drawLine(2, 3, 3, 3);
+                            g.drawLine(2, 3, 2, height - 5);
+                        } else {
+                            g.setColor(shadow);
+                            g.drawLine(width - 3, 3, width - 3, height - 4);
+                            g.drawLine(width - 4, height - 4, width - 4, height - 4);
+
+                            g.setColor(highlight);
+                            g.drawLine(width - 5, 3, width - 4, 3);
+                            g.drawLine(width - 5, 3, width - 5, height - 5);
+                        }
+                    } else { // Vertical
                         g.setColor(shadow);
-                        g.drawLine(4, 3, 4, height - 4);
-                        g.drawLine(4, height - 4, 2, height - 4);
+                        g.drawLine(3, 4, width - 4, 4);
+                        g.drawLine(width - 4, 2, width - 4, 4);
 
                         g.setColor(highlight);
-                        g.drawLine(2, 3, 3, 3);
-                        g.drawLine(2, 3, 2, height - 5);
-                    } else {
-                        g.setColor(shadow);
-                        g.drawLine(width - 3, 3, width - 3, height - 4);
-                        g.drawLine(width - 4, height - 4, width - 4, height - 4);
-
-                        g.setColor(highlight);
-                        g.drawLine(width - 5, 3, width - 4, 3);
-                        g.drawLine(width - 5, 3, width - 5, height - 5);
+                        g.drawLine(3, 2, width - 4, 2);
+                        g.drawLine(3, 2, 3, 3);
                     }
-                } else { // Vertical
-                    g.setColor(shadow);
-                    g.drawLine(3, 4, width - 4, 4);
-                    g.drawLine(width - 4, 2, width - 4, 4);
-
-                    g.setColor(highlight);
-                    g.drawLine(3, 2, width - 4, 2);
-                    g.drawLine(3, 2, 3, 3);
-                }
                 }
             }
 
@@ -225,6 +224,9 @@
 
         public Insets getBorderInsets(Component c, Insets insets) {
             insets.set(1,1,1,1);
+            if (!(c instanceof JToolBar)) {
+                return insets;
+            }
             if (((JToolBar)c).isFloatable()) {
                 int gripInset = (XPStyle.getXP() != null) ? 12 : 9;
                 if (((JToolBar)c).getOrientation() == HORIZONTAL) {
--- a/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java	Fri Sep 24 16:41:32 2010 -0700
@@ -474,7 +474,7 @@
         This is necessary for Receivers retrieved via MidiSystem.getReceiver()
         (which opens the device implicitely).
      */
-    protected abstract class AbstractReceiver implements Receiver {
+    protected abstract class AbstractReceiver implements MidiDeviceReceiver {
         private boolean open = true;
 
 
@@ -508,6 +508,10 @@
             AbstractMidiDevice.this.closeInternal(this);
         }
 
+        public MidiDevice getMidiDevice() {
+            return AbstractMidiDevice.this;
+        }
+
         protected boolean isOpen() {
             return open;
         }
@@ -529,7 +533,7 @@
      * Also, it has some optimizations regarding sending to the Receivers,
      * for known Receivers, and managing itself in the TransmitterList.
      */
-    protected class BasicTransmitter implements Transmitter {
+    protected class BasicTransmitter implements MidiDeviceTransmitter {
 
         private Receiver receiver = null;
         TransmitterList tlist = null;
@@ -568,6 +572,9 @@
             }
         }
 
+        public MidiDevice getMidiDevice() {
+            return AbstractMidiDevice.this;
+        }
 
     } // class BasicTransmitter
 
--- a/src/share/classes/com/sun/media/sound/AudioFloatConverter.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/AudioFloatConverter.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. 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
@@ -40,8 +40,6 @@
  */
 public abstract class AudioFloatConverter {
 
-    public static final Encoding PCM_FLOAT = new Encoding("PCM_FLOAT");
-
     /***************************************************************************
      *
      * LSB Filter, used filter least significant byte in samples arrays.
@@ -982,7 +980,7 @@
                             format.getSampleSizeInBits() + 7) / 8) - 4);
                 }
             }
-        } else if (format.getEncoding().equals(PCM_FLOAT)) {
+        } else if (format.getEncoding().equals(Encoding.PCM_FLOAT)) {
             if (format.getSampleSizeInBits() == 32) {
                 if (format.isBigEndian())
                     conv = new AudioFloatConversion32B();
--- a/src/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2010, Oracle and/or its affiliates. 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
@@ -175,7 +175,6 @@
                 for (int c = 0; c < targetChannels; c++) {
                     for (int i = 0, ix = off + c; i < len2; i++, ix += cs) {
                         b[ix] = conversion_buffer[i];
-                        ;
                     }
                 }
             } else if (targetChannels == 1) {
@@ -186,7 +185,6 @@
                 for (int c = 1; c < sourceChannels; c++) {
                     for (int i = c, ix = off; i < len2; i += cs, ix++) {
                         b[ix] += conversion_buffer[i];
-                        ;
                     }
                 }
                 float vol = 1f / ((float) sourceChannels);
@@ -390,6 +388,7 @@
                 return -1;
             if (len < 0)
                 return 0;
+            int offlen = off + len;
             int remain = len / nrofchannels;
             int destPos = 0;
             int in_end = ibuffer_len;
@@ -423,7 +422,7 @@
             for (int c = 0; c < nrofchannels; c++) {
                 int ix = 0;
                 float[] buff = cbuffer[c];
-                for (int i = c; i < b.length; i += nrofchannels) {
+                for (int i = c + off; i < offlen; i += nrofchannels) {
                     b[i] = buff[ix++];
                 }
             }
@@ -447,7 +446,7 @@
         }
 
         public long skip(long len) throws IOException {
-            if (len > 0)
+            if (len < 0)
                 return 0;
             if (skipbuffer == null)
                 skipbuffer = new float[1024 * targetFormat.getFrameSize()];
@@ -470,7 +469,7 @@
     }
 
     private Encoding[] formats = { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-            AudioFloatConverter.PCM_FLOAT };
+            Encoding.PCM_FLOAT };
 
     public AudioInputStream getAudioInputStream(Encoding targetEncoding,
             AudioInputStream sourceStream) {
@@ -482,7 +481,7 @@
         float samplerate = format.getSampleRate();
         int bits = format.getSampleSizeInBits();
         boolean bigendian = format.isBigEndian();
-        if (targetEncoding.equals(AudioFloatConverter.PCM_FLOAT))
+        if (targetEncoding.equals(Encoding.PCM_FLOAT))
             bits = 32;
         AudioFormat targetFormat = new AudioFormat(encoding, samplerate, bits,
                 channels, channels * bits / 8, samplerate, bigendian);
@@ -521,19 +520,19 @@
 
     public Encoding[] getSourceEncodings() {
         return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-                AudioFloatConverter.PCM_FLOAT };
+                Encoding.PCM_FLOAT };
     }
 
     public Encoding[] getTargetEncodings() {
         return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-                AudioFloatConverter.PCM_FLOAT };
+                Encoding.PCM_FLOAT };
     }
 
     public Encoding[] getTargetEncodings(AudioFormat sourceFormat) {
         if (AudioFloatConverter.getConverter(sourceFormat) == null)
             return new Encoding[0];
         return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-                AudioFloatConverter.PCM_FLOAT };
+                Encoding.PCM_FLOAT };
     }
 
     public AudioFormat[] getTargetFormats(Encoding targetEncoding,
@@ -572,17 +571,17 @@
             }
         }
 
-        if (targetEncoding.equals(AudioFloatConverter.PCM_FLOAT)) {
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+        if (targetEncoding.equals(Encoding.PCM_FLOAT)) {
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
                     AudioSystem.NOT_SPECIFIED, false));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
                     AudioSystem.NOT_SPECIFIED, true));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
                     AudioSystem.NOT_SPECIFIED, false));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
                     AudioSystem.NOT_SPECIFIED, true));
         }
--- a/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java	Fri Sep 24 16:41:32 2010 -0700
@@ -42,11 +42,14 @@
      */
     public AudioSynthesizerPropertyInfo(String name, Object value) {
         this.name = name;
-        this.value = value;
         if (value instanceof Class)
             valueClass = (Class)value;
-        else if (value != null)
-            valueClass = value.getClass();
+        else
+        {
+            this.value = value;
+            if (value != null)
+                valueClass = value.getClass();
+        }
     }
     /**
      * The name of the property.
--- a/src/share/classes/com/sun/media/sound/DLSSoundbank.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/DLSSoundbank.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. 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
@@ -781,7 +781,7 @@
                     }
                     if (sampleformat == 3) {
                         audioformat = new AudioFormat(
-                                AudioFloatConverter.PCM_FLOAT, samplerate, bits,
+                                Encoding.PCM_FLOAT, samplerate, bits,
                                 channels, framesize, samplerate, false);
                     }
 
@@ -965,7 +965,7 @@
             sampleformat = 1;
         else if (audioformat.getEncoding().equals(Encoding.PCM_SIGNED))
             sampleformat = 1;
-        else if (audioformat.getEncoding().equals(AudioFloatConverter.PCM_FLOAT))
+        else if (audioformat.getEncoding().equals(Encoding.PCM_FLOAT))
             sampleformat = 3;
 
         fmt_chunk.writeUnsignedShort(sampleformat);
--- a/src/share/classes/com/sun/media/sound/MidiDeviceReceiver.java	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2009, Oracle and/or its affiliates. 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package com.sun.media.sound;
-
-import javax.sound.midi.MidiDevice;
-import javax.sound.midi.Receiver;
-
-/**
- * A Receiver with reference to it's MidiDevice object.
- *
- * @author Karl Helgason
- */
-public interface MidiDeviceReceiver extends Receiver {
-
-    /** Obtains the MidiDevice object associated with this Receiver.
-     */
-    public MidiDevice getMidiDevice();
-
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/media/sound/MidiDeviceReceiverEnvelope.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.media.sound;
+
+import javax.sound.midi.*;
+
+
+/**
+ * Helper class which allows to convert {@code Receiver}
+ * to {@code MidiDeviceReceiver}.
+ *
+ * @author Alex Menkov
+ */
+public class MidiDeviceReceiverEnvelope implements MidiDeviceReceiver {
+
+    private final MidiDevice device;
+    private final Receiver receiver;
+
+    /**
+     * Creates a new {@code MidiDeviceReceiverEnvelope} object which
+     * envelops the specified {@code Receiver}
+     * and is owned by the specified {@code MidiDevice}.
+     *
+     * @param device the owner {@code MidiDevice}
+     * @param receiver the {@code Receiver} to be enveloped
+     */
+    public MidiDeviceReceiverEnvelope(MidiDevice device, Receiver receiver) {
+        if (device == null || receiver == null) {
+            throw new NullPointerException();
+        }
+        this.device = device;
+        this.receiver = receiver;
+    }
+
+    // Receiver implementation
+    public void close() {
+        receiver.close();
+    }
+
+    public void send(MidiMessage message, long timeStamp) {
+        receiver.send(message, timeStamp);
+    }
+
+    // MidiDeviceReceiver implementation
+    public MidiDevice getMidiDevice() {
+        return device;
+    }
+
+    /**
+     * Obtains the receiver enveloped
+     * by this {@code MidiDeviceReceiverEnvelope} object.
+     *
+     * @return the enveloped receiver
+     */
+    public Receiver getReceiver() {
+        return receiver;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/media/sound/MidiDeviceTransmitterEnvelope.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.media.sound;
+
+import javax.sound.midi.*;
+
+
+/**
+ * Helper class which allows to convert {@code Transmitter}
+ * to {@code MidiDeviceTransmitter}.
+ *
+ * @author Alex Menkov
+ */
+public class MidiDeviceTransmitterEnvelope implements MidiDeviceTransmitter {
+
+    private final MidiDevice device;
+    private final Transmitter transmitter;
+
+    /**
+     * Creates a new {@code MidiDeviceTransmitterEnvelope} object which
+     * envelops the specified {@code Transmitter}
+     * and is owned by the specified {@code MidiDevice}.
+     *
+     * @param device the owner {@code MidiDevice}
+     * @param transmitter the {@code Transmitter} to be enveloped
+     */
+    public MidiDeviceTransmitterEnvelope(MidiDevice device, Transmitter transmitter) {
+        if (device == null || transmitter == null) {
+            throw new NullPointerException();
+        }
+        this.device = device;
+        this.transmitter = transmitter;
+    }
+
+    // Transmitter implementation
+    public void setReceiver(Receiver receiver) {
+        transmitter.setReceiver(receiver);
+    }
+
+    public Receiver getReceiver() {
+        return transmitter.getReceiver();
+    }
+
+    public void close() {
+        transmitter.close();
+    }
+
+
+    // MidiDeviceReceiver implementation
+    public MidiDevice getMidiDevice() {
+        return device;
+    }
+
+    /**
+     * Obtains the transmitter enveloped
+     * by this {@code MidiDeviceTransmitterEnvelope} object.
+     *
+     * @return the enveloped transmitter
+     */
+    public Transmitter getTransmitter() {
+        return transmitter;
+    }
+}
--- a/src/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java	Fri Sep 24 16:41:32 2010 -0700
@@ -205,7 +205,8 @@
         }
         if (buffer.array() == null) {
             return AudioFloatInputStream.getInputStream(new AudioInputStream(
-                    buffer.getInputStream(), format, buffer.capacity()));
+                    buffer.getInputStream(), format,
+                    buffer.capacity() / format.getFrameSize()));
         }
         if (buffer8 != null) {
             if (format.getEncoding().equals(Encoding.PCM_SIGNED)
--- a/src/share/classes/com/sun/media/sound/ModelInstrument.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/ModelInstrument.java	Fri Sep 24 16:41:32 2010 -0700
@@ -56,7 +56,7 @@
 
     public ModelDirector getDirector(ModelPerformer[] performers,
             MidiChannel channel, ModelDirectedPlayer player) {
-        return new ModelStandardDirector(performers, player);
+        return new ModelStandardIndexedDirector(performers, player);
     }
 
     public ModelPerformer[] getPerformers() {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/media/sound/ModelStandardIndexedDirector.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.media.sound;
+
+/**
+ * A standard indexed director who chooses performers
+ * by there keyfrom,keyto,velfrom,velto properties.
+ *
+ * @author Karl Helgason
+ */
+public class ModelStandardIndexedDirector implements ModelDirector {
+
+    ModelPerformer[] performers;
+    ModelDirectedPlayer player;
+    boolean noteOnUsed = false;
+    boolean noteOffUsed = false;
+
+    // Variables needed for index
+    byte[][] trantables;
+    int[] counters;
+    int[][] mat;
+
+    public ModelStandardIndexedDirector(ModelPerformer[] performers,
+            ModelDirectedPlayer player) {
+        this.performers = performers;
+        this.player = player;
+        for (int i = 0; i < performers.length; i++) {
+            ModelPerformer p = performers[i];
+            if (p.isReleaseTriggered()) {
+                noteOffUsed = true;
+            } else {
+                noteOnUsed = true;
+            }
+        }
+        buildindex();
+    }
+
+    private int[] lookupIndex(int x, int y) {
+        if ((x >= 0) && (x < 128) && (y >= 0) && (y < 128)) {
+            int xt = trantables[0][x];
+            int yt = trantables[1][y];
+            if (xt != -1 && yt != -1) {
+                return mat[xt + yt * counters[0]];
+            }
+        }
+        return null;
+    }
+
+    private int restrict(int value) {
+        if(value < 0) return 0;
+        if(value > 127) return 127;
+        return value;
+    }
+
+    private void buildindex() {
+        trantables = new byte[2][129];
+        counters = new int[trantables.length];
+        for (ModelPerformer performer : performers) {
+            int keyFrom = performer.getKeyFrom();
+            int keyTo = performer.getKeyTo();
+            int velFrom = performer.getVelFrom();
+            int velTo = performer.getVelTo();
+            if (keyFrom > keyTo) continue;
+            if (velFrom > velTo) continue;
+            keyFrom = restrict(keyFrom);
+            keyTo = restrict(keyTo);
+            velFrom = restrict(velFrom);
+            velTo = restrict(velTo);
+            trantables[0][keyFrom] = 1;
+            trantables[0][keyTo + 1] = 1;
+            trantables[1][velFrom] = 1;
+            trantables[1][velTo + 1] = 1;
+        }
+        for (int d = 0; d < trantables.length; d++) {
+            byte[] trantable = trantables[d];
+            int transize = trantable.length;
+            for (int i = transize - 1; i >= 0; i--) {
+                if (trantable[i] == 1) {
+                    trantable[i] = -1;
+                    break;
+                }
+                trantable[i] = -1;
+            }
+            int counter = -1;
+            for (int i = 0; i < transize; i++) {
+                if (trantable[i] != 0) {
+                    counter++;
+                    if (trantable[i] == -1)
+                        break;
+                }
+                trantable[i] = (byte) counter;
+            }
+            counters[d] = counter;
+        }
+        mat = new int[counters[0] * counters[1]][];
+        int ix = 0;
+        for (ModelPerformer performer : performers) {
+            int keyFrom = performer.getKeyFrom();
+            int keyTo = performer.getKeyTo();
+            int velFrom = performer.getVelFrom();
+            int velTo = performer.getVelTo();
+            if (keyFrom > keyTo) continue;
+            if (velFrom > velTo) continue;
+            keyFrom = restrict(keyFrom);
+            keyTo = restrict(keyTo);
+            velFrom = restrict(velFrom);
+            velTo = restrict(velTo);
+            int x_from = trantables[0][keyFrom];
+            int x_to = trantables[0][keyTo + 1];
+            int y_from = trantables[1][velFrom];
+            int y_to = trantables[1][velTo + 1];
+            if (x_to == -1)
+                x_to = counters[0];
+            if (y_to == -1)
+                y_to = counters[1];
+            for (int y = y_from; y < y_to; y++) {
+                int i = x_from + y * counters[0];
+                for (int x = x_from; x < x_to; x++) {
+                    int[] mprev = mat[i];
+                    if (mprev == null) {
+                        mat[i] = new int[] { ix };
+                    } else {
+                        int[] mnew = new int[mprev.length + 1];
+                        mnew[mnew.length - 1] = ix;
+                        for (int k = 0; k < mprev.length; k++)
+                            mnew[k] = mprev[k];
+                        mat[i] = mnew;
+                    }
+                    i++;
+                }
+            }
+            ix++;
+        }
+    }
+
+    public void close() {
+    }
+
+    public void noteOff(int noteNumber, int velocity) {
+        if (!noteOffUsed)
+            return;
+        int[] plist = lookupIndex(noteNumber, velocity);
+        if(plist == null) return;
+        for (int i : plist) {
+            ModelPerformer p = performers[i];
+            if (p.isReleaseTriggered()) {
+                player.play(i, null);
+            }
+        }
+    }
+
+    public void noteOn(int noteNumber, int velocity) {
+        if (!noteOnUsed)
+            return;
+        int[] plist = lookupIndex(noteNumber, velocity);
+        if(plist == null) return;
+        for (int i : plist) {
+            ModelPerformer p = performers[i];
+            if (!p.isReleaseTriggered()) {
+                player.play(i, null);
+            }
+        }
+    }
+}
--- a/src/share/classes/com/sun/media/sound/SoftChannel.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/SoftChannel.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. 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
@@ -116,7 +116,7 @@
     protected int tuning_program = 0;
     protected SoftInstrument current_instrument = null;
     protected ModelChannelMixer current_mixer = null;
-    private ModelDirector current_director = null;
+    protected ModelDirector current_director = null;
 
     // Controller Destination Settings
     protected int cds_control_number = -1;
@@ -1264,13 +1264,16 @@
     }
 
     public void programChange(int bank, int program) {
-        bank = restrict7Bit(bank);
+        bank = restrict14Bit(bank);
         program = restrict7Bit(program);
         synchronized (control_mutex) {
             mainmixer.activity();
-            this.bank = bank;
-            this.program = program;
-            current_instrument = null;
+            if(this.bank != bank || this.program != program)
+            {
+                this.bank = bank;
+                this.program = program;
+                current_instrument = null;
+            }
         }
     }
 
--- a/src/share/classes/com/sun/media/sound/SoftMixingMixer.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/SoftMixingMixer.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2010, Oracle and/or its affiliates. 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
@@ -118,16 +118,16 @@
                         AudioSystem.NOT_SPECIFIED, bits, channels, channels
                                 * bits / 8, AudioSystem.NOT_SPECIFIED, true));
             }
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
                     AudioSystem.NOT_SPECIFIED, false));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
                     AudioSystem.NOT_SPECIFIED, true));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
                     AudioSystem.NOT_SPECIFIED, false));
-            formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            formats.add(new AudioFormat(Encoding.PCM_FLOAT,
                     AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
                     AudioSystem.NOT_SPECIFIED, true));
         }
--- a/src/share/classes/com/sun/media/sound/SoftReceiver.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/SoftReceiver.java	Fri Sep 24 16:41:32 2010 -0700
@@ -27,6 +27,7 @@
 import java.util.TreeMap;
 
 import javax.sound.midi.MidiDevice;
+import javax.sound.midi.MidiDeviceReceiver;
 import javax.sound.midi.MidiMessage;
 import javax.sound.midi.ShortMessage;
 
--- a/src/share/classes/com/sun/media/sound/SoftSynthesizer.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/SoftSynthesizer.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2010, Oracle and/or its affiliates. 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
@@ -25,16 +25,25 @@
 
 package com.sun.media.sound;
 
+import java.io.BufferedInputStream;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.OutputStream;
 import java.lang.ref.WeakReference;
-import java.security.AccessControlException;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.prefs.BackingStoreException;
+import java.util.prefs.Preferences;
 
 import javax.sound.midi.Instrument;
 import javax.sound.midi.MidiChannel;
@@ -182,6 +191,7 @@
     // 1: DLS Voice Allocation
     protected int voice_allocation_mode = 0;
 
+    protected boolean load_default_soundbank = false;
     protected boolean reverb_light = true;
     protected boolean reverb_on = true;
     protected boolean chorus_on = true;
@@ -226,8 +236,6 @@
             = new HashMap<String, SoftTuning>();
     private Map<String, SoftInstrument> inslist
             = new HashMap<String, SoftInstrument>();
-    private Map<String, ModelInstrument> availlist
-            = new HashMap<String, ModelInstrument>();
     private Map<String, ModelInstrument> loadedlist
             = new HashMap<String, ModelInstrument>();
 
@@ -275,10 +283,12 @@
         synchronized (control_mutex) {
             if (channels != null)
                 for (SoftChannel c : channels)
+                {
                     c.current_instrument = null;
+                    c.current_director = null;
+                }
             for (Instrument instrument : instruments) {
                 String pat = patchToString(instrument.getPatch());
-                availlist.remove(pat);
                 SoftInstrument softins
                         = new SoftInstrument((ModelInstrument) instrument);
                 inslist.put(pat, softins);
@@ -341,6 +351,7 @@
         number_of_midi_channels = (Integer)items[10].value;
         jitter_correction = (Boolean)items[11].value;
         reverb_light = (Boolean)items[12].value;
+        load_default_soundbank = (Boolean)items[13].value;
     }
 
     private String patchToString(Patch patch) {
@@ -578,7 +589,9 @@
                 c.current_instrument = null;
             inslist.remove(pat);
             loadedlist.remove(pat);
-            availlist.remove(pat);
+            for (int i = 0; i < channels.length; i++) {
+                channels[i].allSoundOff();
+            }
         }
     }
 
@@ -600,7 +613,7 @@
             return false;
 
         synchronized (control_mutex) {
-            if (!loadedlist.containsValue(to) && !availlist.containsValue(to))
+            if (!loadedlist.containsValue(to))
                 throw new IllegalArgumentException("Instrument to is not loaded.");
             unloadInstrument(from);
             ModelMappedInstrument mfrom = new ModelMappedInstrument(
@@ -609,118 +622,155 @@
         }
     }
 
-    public synchronized Soundbank getDefaultSoundbank() {
-        if (defaultSoundBank == null) {
-            try {
-                File javahome = new File(System.getProperties().getProperty(
-                        "java.home"));
-                File libaudio = new File(new File(javahome, "lib"), "audio");
+    public Soundbank getDefaultSoundbank() {
+        synchronized (SoftSynthesizer.class) {
+            if (defaultSoundBank != null)
+                return defaultSoundBank;
+
+            List<PrivilegedAction<InputStream>> actions =
+                new ArrayList<PrivilegedAction<InputStream>>();
 
-                if (libaudio.exists()) {
-                    File foundfile = null;
-                    File[] files = libaudio.listFiles();
-                    if (files != null) {
-                        for (int i = 0; i < files.length; i++) {
-                            File file = files[i];
-                            if (file.isFile()) {
-                                String lname = file.getName().toLowerCase();
-                                if (lname.endsWith(".sf2") ||
-                                        lname.endsWith(".dls")) {
-                                    if (foundfile == null || (file.length() >
-                                            foundfile.length())) {
-                                        foundfile = file;
+            actions.add(new PrivilegedAction<InputStream>() {
+                public InputStream run() {
+                    File javahome = new File(System.getProperties()
+                            .getProperty("java.home"));
+                    File libaudio = new File(new File(javahome, "lib"), "audio");
+                    if (libaudio.exists()) {
+                        File foundfile = null;
+                        File[] files = libaudio.listFiles();
+                        if (files != null) {
+                            for (int i = 0; i < files.length; i++) {
+                                File file = files[i];
+                                if (file.isFile()) {
+                                    String lname = file.getName().toLowerCase();
+                                    if (lname.endsWith(".sf2")
+                                            || lname.endsWith(".dls")) {
+                                        if (foundfile == null
+                                                || (file.length() > foundfile
+                                                        .length())) {
+                                            foundfile = file;
+                                        }
                                     }
                                 }
                             }
                         }
+                        if (foundfile != null) {
+                            try {
+                                return new FileInputStream(foundfile);
+                            } catch (IOException e) {
+                            }
+                        }
                     }
-                    if (foundfile != null) {
-                        try {
-                            Soundbank sbk = MidiSystem.getSoundbank(foundfile);
-                            defaultSoundBank = sbk;
-                            return defaultSoundBank;
-                        } catch (Exception e) {
-                            //e.printStackTrace();
+                    return null;
+                }
+            });
+
+            actions.add(new PrivilegedAction<InputStream>() {
+                public InputStream run() {
+                    if (System.getProperties().getProperty("os.name")
+                            .startsWith("Windows")) {
+                        File gm_dls = new File(System.getenv("SystemRoot")
+                                + "\\system32\\drivers\\gm.dls");
+                        if (gm_dls.exists()) {
+                            try {
+                                return new FileInputStream(gm_dls);
+                            } catch (IOException e) {
+                            }
                         }
                     }
+                    return null;
                 }
+            });
 
-                if (System.getProperties().getProperty("os.name")
-                        .startsWith("Windows")) {
-                    File gm_dls = new File(System.getenv("SystemRoot")
-                            + "\\system32\\drivers\\gm.dls");
-                    if (gm_dls.exists()) {
+            actions.add(new PrivilegedAction<InputStream>() {
+                public InputStream run() {
+                    /*
+                     * Try to load saved generated soundbank
+                     */
+                    File userhome = new File(System.getProperty("user.home"),
+                            ".gervill");
+                    File emg_soundbank_file = new File(userhome,
+                            "soundbank-emg.sf2");
+                    if (emg_soundbank_file.exists()) {
                         try {
-                            Soundbank sbk = MidiSystem.getSoundbank(gm_dls);
-                            defaultSoundBank = sbk;
-                            return defaultSoundBank;
-                        } catch (Exception e) {
-                            //e.printStackTrace();
+                            return new FileInputStream(emg_soundbank_file);
+                        } catch (IOException e) {
                         }
                     }
+                    return null;
                 }
-            } catch (AccessControlException e) {
-            } catch (Exception e) {
-                //e.printStackTrace();
-            }
-
-            File userhome = null;
-            File emg_soundbank_file = null;
+            });
 
-            /*
-             *  Try to load saved generated soundbank
-             */
-            try {
-                userhome = new File(System.getProperty("user.home"),
-                     ".gervill");
-                emg_soundbank_file = new File(userhome, "soundbank-emg.sf2");
-                Soundbank sbk = MidiSystem.getSoundbank(emg_soundbank_file);
-                defaultSoundBank = sbk;
-                return defaultSoundBank;
-            } catch (AccessControlException e) {
-            } catch (Exception e) {
-                //e.printStackTrace();
+            for (PrivilegedAction<InputStream> action : actions) {
+                try {
+                    InputStream is = AccessController.doPrivileged(action);
+                    if(is == null) continue;
+                    Soundbank sbk;
+                    try {
+                        sbk = MidiSystem.getSoundbank(new BufferedInputStream(is));
+                    } finally {
+                        is.close();
+                    }
+                    if (sbk != null) {
+                        defaultSoundBank = sbk;
+                        return defaultSoundBank;
+                    }
+                } catch (Exception e) {
+                }
             }
 
             try {
-
                 /*
-                 *  Generate emergency soundbank
+                 * Generate emergency soundbank
                  */
                 defaultSoundBank = EmergencySoundbank.createSoundbank();
-
-                /*
-                 *  Save generated soundbank to disk for faster future use.
-                 */
-                if(defaultSoundBank != null)
-                {
-                    if(!userhome.exists()) userhome.mkdirs();
-                    if(!emg_soundbank_file.exists())
-                        ((SF2Soundbank)defaultSoundBank).save(emg_soundbank_file);
-                }
             } catch (Exception e) {
-                //e.printStackTrace();
             }
 
+            if (defaultSoundBank != null) {
+                /*
+                 * Save generated soundbank to disk for faster future use.
+                 */
+                OutputStream out = AccessController
+                        .doPrivileged(new PrivilegedAction<OutputStream>() {
+                            public OutputStream run() {
+                                try {
+                                    File userhome = new File(System
+                                            .getProperty("user.home"),
+                                            ".gervill");
+                                    if (!userhome.exists())
+                                        userhome.mkdirs();
+                                    File emg_soundbank_file = new File(
+                                            userhome, "soundbank-emg.sf2");
+                                    if (emg_soundbank_file.exists())
+                                        return null;
+                                    return new FileOutputStream(
+                                            emg_soundbank_file);
+                                } catch (IOException e) {
+                                } catch (SecurityException e) {
+                                }
+                                return null;
+                            }
+                        });
+                if (out != null) {
+                    try {
+                        ((SF2Soundbank) defaultSoundBank).save(out);
+                        out.close();
+                    } catch (IOException e) {
+                    }
+                }
+            }
         }
         return defaultSoundBank;
     }
 
     public Instrument[] getAvailableInstruments() {
-        if (!isOpen()) {
-            Soundbank defsbk = getDefaultSoundbank();
-            if (defsbk == null)
-                return new Instrument[0];
-            return defsbk.getInstruments();
-        }
-
-        synchronized (control_mutex) {
-            ModelInstrument[] inslist_array =
-                    new ModelInstrument[availlist.values().size()];
-            availlist.values().toArray(inslist_array);
-            Arrays.sort(inslist_array, new ModelInstrumentComparator());
-            return inslist_array;
-        }
+        Soundbank defsbk = getDefaultSoundbank();
+        if (defsbk == null)
+            return new Instrument[0];
+        Instrument[] inslist_array = defsbk.getInstruments();
+        Arrays.sort(inslist_array, new ModelInstrumentComparator());
+        return inslist_array;
     }
 
     public Instrument[] getLoadedInstruments() {
@@ -794,6 +844,31 @@
         return info;
     }
 
+    private Properties getStoredProperties() {
+        return AccessController
+                .doPrivileged(new PrivilegedAction<Properties>() {
+                    public Properties run() {
+                        Properties p = new Properties();
+                        String notePath = "/com/sun/media/sound/softsynthesizer";
+                        try {
+                            Preferences prefroot = Preferences.userRoot();
+                            if (prefroot.nodeExists(notePath)) {
+                                Preferences prefs = prefroot.node(notePath);
+                                String[] prefs_keys = prefs.keys();
+                                for (String prefs_key : prefs_keys) {
+                                    String val = prefs.get(prefs_key, null);
+                                    if (val != null)
+                                        p.setProperty(prefs_key, val);
+                                }
+                            }
+                        } catch (BackingStoreException e) {
+                        } catch (SecurityException e) {
+                        }
+                        return p;
+                    }
+                });
+    }
+
     public AudioSynthesizerPropertyInfo[] getPropertyInfo(Map<String, Object> info) {
         List<AudioSynthesizerPropertyInfo> list =
                 new ArrayList<AudioSynthesizerPropertyInfo>();
@@ -861,17 +936,92 @@
         item.description = "Turn light reverb mode on or off";
         list.add(item);
 
+        item = new AudioSynthesizerPropertyInfo("load default soundbank", o?load_default_soundbank:true);
+        item.description = "Enabled/disable loading default soundbank";
+        list.add(item);
+
         AudioSynthesizerPropertyInfo[] items;
         items = list.toArray(new AudioSynthesizerPropertyInfo[list.size()]);
 
-        if (info != null)
-            for (AudioSynthesizerPropertyInfo item2: items) {
-                Object v = info.get(item2.name);
+        Properties storedProperties = getStoredProperties();
+
+        for (AudioSynthesizerPropertyInfo item2 : items) {
+            Object v = (info == null) ? null : info.get(item2.name);
+            v = (v != null) ? v : storedProperties.getProperty(item2.name);
+            if (v != null) {
                 Class c = (item2.valueClass);
-                if (v != null)
-                    if (c.isInstance(v))
-                        item2.value = v;
+                if (c.isInstance(v))
+                    item2.value = v;
+                else if (v instanceof String) {
+                    String s = (String) v;
+                    if (c == Boolean.class) {
+                        if (s.equalsIgnoreCase("true"))
+                            item2.value = Boolean.TRUE;
+                        if (s.equalsIgnoreCase("false"))
+                            item2.value = Boolean.FALSE;
+                    } else if (c == AudioFormat.class) {
+                        int channels = 2;
+                        boolean signed = true;
+                        boolean bigendian = false;
+                        int bits = 16;
+                        float sampleRate = 44100f;
+                        try {
+                            StringTokenizer st = new StringTokenizer(s, ", ");
+                            String prevToken = "";
+                            while (st.hasMoreTokens()) {
+                                String token = st.nextToken().toLowerCase();
+                                if (token.equals("mono"))
+                                    channels = 1;
+                                if (token.startsWith("channel"))
+                                    channels = Integer.parseInt(prevToken);
+                                if (token.contains("unsigned"))
+                                    signed = false;
+                                if (token.equals("big-endian"))
+                                    bigendian = true;
+                                if (token.equals("bit"))
+                                    bits = Integer.parseInt(prevToken);
+                                if (token.equals("hz"))
+                                    sampleRate = Float.parseFloat(prevToken);
+                                prevToken = token;
+                            }
+                            item2.value = new AudioFormat(sampleRate, bits,
+                                    channels, signed, bigendian);
+                        } catch (NumberFormatException e) {
+                        }
+
+                    } else
+                        try {
+                            if (c == Byte.class)
+                                item2.value = Byte.valueOf(s);
+                            else if (c == Short.class)
+                                item2.value = Short.valueOf(s);
+                            else if (c == Integer.class)
+                                item2.value = Integer.valueOf(s);
+                            else if (c == Long.class)
+                                item2.value = Long.valueOf(s);
+                            else if (c == Float.class)
+                                item2.value = Float.valueOf(s);
+                            else if (c == Double.class)
+                                item2.value = Double.valueOf(s);
+                        } catch (NumberFormatException e) {
+                        }
+                } else if (v instanceof Number) {
+                    Number n = (Number) v;
+                    if (c == Byte.class)
+                        item2.value = Byte.valueOf(n.byteValue());
+                    if (c == Short.class)
+                        item2.value = Short.valueOf(n.shortValue());
+                    if (c == Integer.class)
+                        item2.value = Integer.valueOf(n.intValue());
+                    if (c == Long.class)
+                        item2.value = Long.valueOf(n.longValue());
+                    if (c == Float.class)
+                        item2.value = Float.valueOf(n.floatValue());
+                    if (c == Double.class)
+                        item2.value = Double.valueOf(n.doubleValue());
+                }
             }
+        }
 
         return items;
     }
@@ -1007,11 +1157,12 @@
             if (targetFormat != null)
                 setFormat(targetFormat);
 
-            Soundbank defbank = getDefaultSoundbank();
-            if (defbank != null) {
-                loadAllInstruments(defbank);
-                availlist.putAll(loadedlist);
-                loadedlist.clear();
+            if (load_default_soundbank)
+            {
+                Soundbank defbank = getDefaultSoundbank();
+                if (defbank != null) {
+                    loadAllInstruments(defbank);
+                }
             }
 
             voices = new SoftVoice[maxpoly];
@@ -1117,7 +1268,6 @@
             }
 
             inslist.clear();
-            availlist.clear();
             loadedlist.clear();
             tunings.clear();
 
--- a/src/share/classes/com/sun/media/sound/SoftVoice.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/SoftVoice.java	Fri Sep 24 16:41:32 2010 -0700
@@ -279,9 +279,12 @@
     }
 
     protected void updateTuning(SoftTuning newtuning) {
+        tuning = newtuning;
         tunedKey = tuning.getTuning(note) / 100.0;
         if (!portamento) {
             co_noteon_keynumber[0] = tunedKey * (1.0 / 128.0);
+            if(performer == null)
+                return;
             int[] c = performer.midi_connections[4];
             if (c == null)
                 return;
@@ -433,6 +436,8 @@
     }
 
     protected void setPolyPressure(int pressure) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[2];
         if (c == null)
             return;
@@ -441,6 +446,8 @@
     }
 
     protected void setChannelPressure(int pressure) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[1];
         if (c == null)
             return;
@@ -449,6 +456,8 @@
     }
 
     protected void controlChange(int controller, int value) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_ctrl_connections[controller];
         if (c == null)
             return;
@@ -457,6 +466,8 @@
     }
 
     protected void nrpnChange(int controller, int value) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_nrpn_connections.get(controller);
         if (c == null)
             return;
@@ -465,6 +476,8 @@
     }
 
     protected void rpnChange(int controller, int value) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_rpn_connections.get(controller);
         if (c == null)
             return;
@@ -473,6 +486,8 @@
     }
 
     protected void setPitchBend(int bend) {
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[0];
         if (c == null)
             return;
@@ -499,6 +514,8 @@
 
         co_noteon_on[0] = -1;
 
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[3];
         if (c == null)
             return;
@@ -527,6 +544,8 @@
 
         co_noteon_on[0] = 0;
 
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[3];
         if (c == null)
             return;
@@ -543,6 +562,8 @@
         sustain = true;
         co_noteon_on[0] = 1;
 
+        if(performer == null)
+            return;
         int[] c = performer.midi_connections[3];
         if (c == null)
             return;
@@ -555,6 +576,11 @@
             active = false;
             stopping = false;
             audiostarted = false;
+            instrument = null;
+            performer = null;
+            connections = null;
+            extendedConnectionBlocks = null;
+            channelmixer = null;
             if (osc_stream != null)
                 try {
                     osc_stream.close();
--- a/src/share/classes/com/sun/media/sound/WaveExtensibleFileReader.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/WaveExtensibleFileReader.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. 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
@@ -271,7 +271,7 @@
                         bits, channels, framesize, samplerate, false, p);
             }
         } else if (subFormat.equals(SUBTYPE_IEEE_FLOAT)) {
-            audioformat = new AudioFormat(AudioFloatConverter.PCM_FLOAT,
+            audioformat = new AudioFormat(Encoding.PCM_FLOAT,
                     samplerate, bits, channels, framesize, samplerate, false, p);
         } else
             throw new UnsupportedAudioFileException();
--- a/src/share/classes/com/sun/media/sound/WaveFloatFileReader.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/WaveFloatFileReader.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. 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
@@ -33,6 +33,7 @@
 
 import javax.sound.sampled.AudioFileFormat;
 import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioFormat.Encoding;
 import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.UnsupportedAudioFileException;
@@ -102,7 +103,7 @@
             throw new UnsupportedAudioFileException();
 
         AudioFormat audioformat = new AudioFormat(
-                AudioFloatConverter.PCM_FLOAT, samplerate, bits, channels,
+                Encoding.PCM_FLOAT, samplerate, bits, channels,
                 framesize, samplerate, false);
         AudioFileFormat fileformat = new AudioFileFormat(
                 AudioFileFormat.Type.WAVE, audioformat,
--- a/src/share/classes/com/sun/media/sound/WaveFloatFileWriter.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/media/sound/WaveFloatFileWriter.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2010, Oracle and/or its affiliates. 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
@@ -30,6 +30,7 @@
 
 import javax.sound.sampled.AudioFileFormat;
 import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioFormat.Encoding;
 import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.AudioFileFormat.Type;
@@ -48,8 +49,7 @@
 
     public Type[] getAudioFileTypes(AudioInputStream stream) {
 
-        if (!stream.getFormat().getEncoding().equals(
-                AudioFloatConverter.PCM_FLOAT))
+        if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
             return new Type[0];
         return new Type[] { Type.WAVE };
     }
@@ -58,8 +58,7 @@
         if (!Type.WAVE.equals(type))
             throw new IllegalArgumentException("File type " + type
                     + " not supported.");
-        if (!stream.getFormat().getEncoding().equals(
-                AudioFloatConverter.PCM_FLOAT))
+        if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
             throw new IllegalArgumentException("File format "
                     + stream.getFormat() + " not supported.");
     }
--- a/src/share/classes/com/sun/rowset/CachedRowSetImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/CachedRowSetImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -518,7 +518,7 @@
             setReadOnly(true);
         setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
         setEscapeProcessing(true);
-        setTypeMap(null);
+        //setTypeMap(null);
         checkTransactionalWriter();
 
         //Instantiating the vector for MatchColumns
@@ -679,7 +679,10 @@
                 } else if (obj instanceof Clob) {
                     obj = new SerialClob((Clob)obj);
                 } else if (obj instanceof java.sql.Array) {
-                    obj = new SerialArray((java.sql.Array)obj, map);
+                    if(map != null)
+                        obj = new SerialArray((java.sql.Array)obj, map);
+                    else
+                        obj = new SerialArray((java.sql.Array)obj);
                 }
 
                 ((Row)currentRow).initColumnObject(i, obj);
@@ -762,7 +765,7 @@
         if( conn != null){
            // JDBC 4.0 mandates as does the Java EE spec that all DataBaseMetaData methods
            // must be implemented, therefore, the previous fix for 5055528 is being backed out
-           dbmslocatorsUpdateCopy = conn.getMetaData().locatorsUpdateCopy();
+            dbmslocatorsUpdateCopy = conn.getMetaData().locatorsUpdateCopy();
         }
     }
 
@@ -6322,6 +6325,7 @@
         crs.RowSetMD = RowSetMD;
         crs.numRows = 1;
         crs.cursorPos = 0;
+        crs.setTypeMap(this.getTypeMap());
 
         // make sure we don't get someone playing with these
         // %%% is this now necessary ???
@@ -10114,7 +10118,7 @@
      * during the deserialization process
      *
      */
-    protected void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
         // Default state initialization happens here
         ois.defaultReadObject();
         // Initialization of transient Res Bundle happens here .
@@ -10125,5 +10129,15 @@
         }
 
     }
-        static final long serialVersionUID =1884577171200622428L;
+
+    //------------------------- JDBC 4.1 -----------------------------------
+    public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
+        throw new SQLFeatureNotSupportedException("Not supported yet.");
+    }
+
+    public <T> T getObject(String columnLabel, Class<T> type) throws SQLException {
+        throw new SQLFeatureNotSupportedException("Not supported yet.");
+    }
+
+    static final long serialVersionUID =1884577171200622428L;
 }
--- a/src/share/classes/com/sun/rowset/FilteredRowSetImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/FilteredRowSetImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -1746,5 +1746,23 @@
       onInsertRow = false;
       super.insertRow();
    }
-  static final long serialVersionUID = 6178454588413509360L;
+
+   /**
+    * This method re populates the resBundle
+    * during the deserialization process
+    *
+    */
+   private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+       // Default state initialization happens here
+       ois.defaultReadObject();
+       // Initialization of transient Res Bundle happens here .
+       try {
+          resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+       } catch(IOException ioe) {
+           throw new RuntimeException(ioe);
+       }
+
+   }
+
+   static final long serialVersionUID = 6178454588413509360L;
 } // end FilteredRowSetImpl class
--- a/src/share/classes/com/sun/rowset/JdbcRowSetImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/JdbcRowSetImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -101,7 +101,7 @@
     private Vector strMatchColumns;
 
 
-    protected transient JdbcRowSetResourceBundle jdbcResBundle;
+    protected transient JdbcRowSetResourceBundle resBundle;
 
     /**
      * Constructs a default <code>JdbcRowSet</code> object.
@@ -140,7 +140,7 @@
         rs   = null;
 
         try {
-           jdbcResBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
         } catch(IOException ioe) {
             throw new RuntimeException(ioe);
         }
@@ -154,42 +154,42 @@
         try {
             setShowDeleted(false);
         } catch(SQLException sqle) {
-             System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setshowdeleted").toString() +
+             System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setshowdeleted").toString() +
                                 sqle.getLocalizedMessage());
         }
 
         try {
             setQueryTimeout(0);
         } catch(SQLException sqle) {
-            System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setquerytimeout").toString() +
+            System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setquerytimeout").toString() +
                                 sqle.getLocalizedMessage());
         }
 
         try {
             setMaxRows(0);
         } catch(SQLException sqle) {
-            System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setmaxrows").toString() +
+            System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setmaxrows").toString() +
                                 sqle.getLocalizedMessage());
         }
 
         try {
             setMaxFieldSize(0);
         } catch(SQLException sqle) {
-             System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setmaxfieldsize").toString() +
+             System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setmaxfieldsize").toString() +
                                 sqle.getLocalizedMessage());
         }
 
         try {
             setEscapeProcessing(true);
         } catch(SQLException sqle) {
-             System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setescapeprocessing").toString() +
+             System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setescapeprocessing").toString() +
                                 sqle.getLocalizedMessage());
         }
 
         try {
             setConcurrency(ResultSet.CONCUR_UPDATABLE);
         } catch (SQLException sqle) {
-            System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setconcurrency").toString() +
+            System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setconcurrency").toString() +
                                 sqle.getLocalizedMessage());
         }
 
@@ -198,7 +198,7 @@
         try {
             setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
         } catch(SQLException sqle){
-          System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.settype").toString() +
+          System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.settype").toString() +
                                 sqle.getLocalizedMessage());
         }
 
@@ -207,7 +207,7 @@
         try {
             setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
         } catch(SQLException sqle){
-            System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.settransactionisolation").toString() +
+            System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.settransactionisolation").toString() +
                                 sqle.getLocalizedMessage());
         }
 
@@ -263,7 +263,7 @@
         rs = null;
 
         try {
-           jdbcResBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
         } catch(IOException ioe) {
             throw new RuntimeException(ioe);
         }
@@ -338,7 +338,7 @@
         rs = null;
 
         try {
-           jdbcResBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
         } catch(IOException ioe) {
             throw new RuntimeException(ioe);
         }
@@ -430,7 +430,7 @@
         rs = res;
 
         try {
-           jdbcResBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
         } catch(IOException ioe) {
             throw new RuntimeException(ioe);
         }
@@ -517,7 +517,7 @@
         // to the db, implies undesirable state so throw exception
 
         if (conn == null && ps == null && rs == null ) {
-            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.invalstate").toString());
+            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.invalstate").toString());
         }
     }
 
@@ -593,28 +593,28 @@
         try {
             ps.setEscapeProcessing(getEscapeProcessing());
         } catch (SQLException ex) {
-            System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setescapeprocessing").toString() +
+            System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setescapeprocessing").toString() +
                                 ex.getLocalizedMessage());
         }
 
         try {
             ps.setMaxFieldSize(getMaxFieldSize());
         } catch (SQLException ex) {
-            System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setmaxfieldsize").toString() +
+            System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setmaxfieldsize").toString() +
                                 ex.getLocalizedMessage());
         }
 
         try {
             ps.setMaxRows(getMaxRows());
         } catch (SQLException ex) {
-           System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setmaxrows").toString() +
+           System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setmaxrows").toString() +
                                 ex.getLocalizedMessage());
         }
 
         try {
             ps.setQueryTimeout(getQueryTimeout());
         } catch (SQLException ex) {
-           System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setquerytimeout").toString() +
+           System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.setquerytimeout").toString() +
                                 ex.getLocalizedMessage());
         }
 
@@ -651,7 +651,7 @@
                 }
             }
             catch (javax.naming.NamingException ex) {
-                throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.connect").toString());
+                throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.connect").toString());
             }
 
         } else if (getUrl() != null) {
@@ -681,7 +681,7 @@
             }
             ps = conn.prepareStatement(getCommand(),ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
         } catch (SQLException ex) {
-            System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.prepare").toString() +
+            System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.prepare").toString() +
                                 ex.getLocalizedMessage());
 
             if (ps != null)
@@ -721,15 +721,15 @@
                     if (param[0] instanceof java.sql.Date ||
                         param[0] instanceof java.sql.Time ||
                         param[0] instanceof java.sql.Timestamp) {
-                        System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.detecteddate"));
+                        System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.detecteddate"));
                         if (param[1] instanceof java.util.Calendar) {
-                            System.err.println(jdbcResBundle.handleGetObject("jdbcrowsetimpl.detectedcalendar"));
+                            System.err.println(resBundle.handleGetObject("jdbcrowsetimpl.detectedcalendar"));
                             ps.setDate(i + 1, (java.sql.Date)param[0],
                                        (java.util.Calendar)param[1]);
                             continue;
                         }
                         else {
-                            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.paramtype").toString());
+                            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.paramtype").toString());
                         }
                     }
 
@@ -770,7 +770,7 @@
                                               (java.io.InputStream)param[0],
                                               ((Integer)param[1]).intValue());
                         default:
-                            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.paramtype").toString());
+                            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.paramtype").toString());
                         }
                     }
 
@@ -784,7 +784,7 @@
                         continue;
                     }
 
-                    throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.paramtype").toString());
+                    throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.paramtype").toString());
 
                 } else {
                     // common case - this catches all SQL92 types
@@ -3749,7 +3749,7 @@
          for( int j= 0 ;j < columnIdxes.length; j++) {
             i_val = (Integer.parseInt(iMatchColumns.get(j).toString()));
             if(columnIdxes[j] != i_val) {
-               throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.matchcols").toString());
+               throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols").toString());
             }
          }
 
@@ -3776,7 +3776,7 @@
 
         for(int j = 0 ;j < columnIdxes.length; j++) {
            if( !columnIdxes[j].equals(strMatchColumns.get(j)) ){
-              throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.matchcols").toString());
+              throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols").toString());
            }
         }
 
@@ -3800,7 +3800,7 @@
         String []str_temp = new String[strMatchColumns.size()];
 
         if( strMatchColumns.get(0) == null) {
-           throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setmatchcols").toString());
+           throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.setmatchcols").toString());
         }
 
         strMatchColumns.copyInto(str_temp);
@@ -3825,7 +3825,7 @@
         i_val = ((Integer)iMatchColumns.get(0)).intValue();
 
         if( i_val == -1 ) {
-           throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.setmatchcols").toString());
+           throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.setmatchcols").toString());
         }
 
 
@@ -3859,7 +3859,7 @@
 
         for(int j = 0 ; j < columnIdxes.length; j++) {
            if( columnIdxes[j] < 0 ) {
-              throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.matchcols1").toString());
+              throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols1").toString());
            }
         }
         for(int i = 0 ;i < columnIdxes.length; i++) {
@@ -3886,7 +3886,7 @@
 
         for(int j = 0; j < columnNames.length; j++) {
            if( columnNames[j] == null || columnNames[j].equals("")) {
-              throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.matchcols2").toString());
+              throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols2").toString());
            }
         }
         for( int i = 0; i < columnNames.length; i++) {
@@ -3915,7 +3915,7 @@
     public void setMatchColumn(int columnIdx) throws SQLException {
         // validate, if col is ok to be set
         if(columnIdx < 0) {
-            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.matchcols1").toString());
+            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols1").toString());
         } else {
             // set iMatchColumn
             iMatchColumns.set(0, new Integer(columnIdx));
@@ -3941,7 +3941,7 @@
     public void setMatchColumn(String columnName) throws SQLException {
         // validate, if col is ok to be set
         if(columnName.equals(null) || ((columnName = columnName.trim()) == "" )) {
-            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.matchcols2").toString());
+            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols2").toString());
         } else {
             // set strMatchColumn
             strMatchColumns.set(0, columnName);
@@ -3966,9 +3966,9 @@
     public void unsetMatchColumn(int columnIdx) throws SQLException {
         // check if we are unsetting the SAME column
         if(! iMatchColumns.get(0).equals(new Integer(columnIdx) )  ) {
-            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.unsetmatch").toString());
+            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.unsetmatch").toString());
         } else if(strMatchColumns.get(0) != null) {
-            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.usecolname").toString());
+            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.usecolname").toString());
         } else {
                 // that is, we are unsetting it.
                iMatchColumns.set(0, new Integer(-1));
@@ -3995,9 +3995,9 @@
         columnName = columnName.trim();
 
         if(!((strMatchColumns.get(0)).equals(columnName))) {
-            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.unsetmatch").toString());
+            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.unsetmatch").toString());
         } else if( ((Integer)(iMatchColumns.get(0))).intValue() > 0) {
-            throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.usecolid").toString());
+            throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.usecolid").toString());
         } else {
             strMatchColumns.set(0, null);   // that is, we are unsetting it.
         }
@@ -4152,7 +4152,7 @@
     private void checkTypeConcurrency() throws SQLException {
         if(rs.getType() == TYPE_FORWARD_ONLY ||
            rs.getConcurrency() == CONCUR_READ_ONLY) {
-              throw new SQLException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.resnotupd").toString());
+              throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.resnotupd").toString());
          }
     }
 
@@ -4642,7 +4642,7 @@
      * @since 6.0
      */
     public SQLXML getSQLXML(int columnIndex) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4653,7 +4653,7 @@
      * @throws SQLException if a database access error occurs
      */
     public SQLXML getSQLXML(String colName) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4668,7 +4668,7 @@
      * @since 6.0
      */
     public RowId getRowId(int columnIndex) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4683,7 +4683,7 @@
      * @since 6.0
      */
     public RowId getRowId(String columnName) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4699,7 +4699,7 @@
      * @since 6.0
      */
     public void updateRowId(int columnIndex, RowId x) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4715,7 +4715,7 @@
      * @since 6.0
      */
     public void updateRowId(String columnName, RowId x) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4725,7 +4725,7 @@
      * @since 6.0
      */
     public int getHoldability() throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4736,7 +4736,7 @@
      * @since 6.0
      */
     public boolean isClosed() throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4748,7 +4748,7 @@
      * @since 6.0
      */
     public void updateNString(int columnIndex, String nString) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4760,7 +4760,7 @@
      * @since 6.0
      */
     public void updateNString(String columnName, String nString) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
 
@@ -4773,7 +4773,7 @@
      * @since 6.0
      */
     public void updateNClob(int columnIndex, NClob nClob) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4785,7 +4785,7 @@
      * @since 6.0
      */
     public void updateNClob(String columnName, NClob nClob) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -4800,7 +4800,7 @@
      * @since 6.0
      */
     public NClob getNClob(int i) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
 
@@ -4816,7 +4816,7 @@
      * @since 6.0
      */
     public NClob getNClob(String colName) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     public <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException{
@@ -4836,7 +4836,7 @@
       * @since 1.6
       */
      public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
-         throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+         throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
      }
 
     /**
@@ -4848,7 +4848,7 @@
      * @since 1.6
      */
     public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException {
-         throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+         throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
      }
 
     /**
@@ -4863,7 +4863,7 @@
      * @since 1.6
      */
     public void setRowId(int parameterIndex, RowId x) throws SQLException {
-         throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+         throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
      }
 
     /**
@@ -4877,7 +4877,7 @@
     * @since 1.6
     */
    public void setRowId(String parameterName, RowId x) throws SQLException {
-         throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+         throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
      }
 
 
@@ -4897,7 +4897,7 @@
      * @since 1.6
      */
      public void setNString(int parameterIndex, String value) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
      }
 
 
@@ -4925,7 +4925,7 @@
     * @since 1.6
     */
     public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
   /**
@@ -4940,7 +4940,7 @@
     * @since 1.6
     */
     public void setNClob(String parameterName, NClob value) throws SQLException {
-         throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+         throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
      }
 
 
@@ -4960,7 +4960,7 @@
      * @since 1.6
      */
     public java.io.Reader getNCharacterStream(int columnIndex) throws SQLException {
-       throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+       throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
      }
 
 
@@ -4980,7 +4980,7 @@
      * @since 1.6
      */
     public java.io.Reader getNCharacterStream(String columnName) throws SQLException {
-       throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+       throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
      }
 
     /**
@@ -4996,7 +4996,7 @@
      * @since 1.6
      */
     public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5013,7 +5013,7 @@
      * @since 1.6
      */
     public void updateSQLXML(String columnName, SQLXML xmlObject) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
      /**
@@ -5031,7 +5031,7 @@
      * @since 1.6
      */
     public String getNString(int columnIndex) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5049,7 +5049,7 @@
      * @since 1.6
      */
     public String getNString(String columnName) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
      /**
@@ -5071,7 +5071,7 @@
                             java.io.Reader x,
                             long length)
                             throws SQLException {
-          throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+          throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
        }
 
      /**
@@ -5093,7 +5093,7 @@
                             java.io.Reader x,
                             long length)
                             throws SQLException {
-          throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+          throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
        }
 
     /**
@@ -5123,7 +5123,7 @@
      */
     public void updateNCharacterStream(int columnIndex,
                              java.io.Reader x) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5155,7 +5155,7 @@
      */
     public void updateNCharacterStream(String columnLabel,
                              java.io.Reader reader) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5188,7 +5188,7 @@
      * @since 1.6
      */
     public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5221,7 +5221,7 @@
      * @since 1.6
      */
     public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5256,7 +5256,7 @@
      * @since 1.6
      */
     public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5291,7 +5291,7 @@
      * @since 1.6
      */
     public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5323,7 +5323,7 @@
      * @since 1.6
      */
     public void updateClob(int columnIndex,  Reader reader, long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5355,7 +5355,7 @@
      * @since 1.6
      */
     public void updateClob(String columnLabel,  Reader reader, long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5389,7 +5389,7 @@
      * @since 1.6
      */
     public void updateClob(int columnIndex,  Reader reader) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5424,7 +5424,7 @@
      * @since 1.6
      */
     public void updateClob(String columnLabel,  Reader reader) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
    /**
@@ -5458,7 +5458,7 @@
      * @since 1.6
      */
     public void updateNClob(int columnIndex,  Reader reader, long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5492,7 +5492,7 @@
      * @since 1.6
      */
     public void updateNClob(String columnLabel,  Reader reader, long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5528,7 +5528,7 @@
      * @since 1.6
      */
     public void updateNClob(int columnIndex,  Reader reader) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5565,7 +5565,7 @@
      * @since 1.6
      */
     public void updateNClob(String columnLabel,  Reader reader) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
 
@@ -5590,7 +5590,7 @@
     public void updateAsciiStream(int columnIndex,
                            java.io.InputStream x,
                            long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5614,7 +5614,7 @@
     public void updateBinaryStream(int columnIndex,
                             java.io.InputStream x,
                             long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5638,7 +5638,7 @@
     public void updateCharacterStream(int columnIndex,
                              java.io.Reader x,
                              long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
      /**
@@ -5662,7 +5662,7 @@
     public void updateAsciiStream(String columnLabel,
                            java.io.InputStream x,
                            long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5687,7 +5687,7 @@
      */
     public void updateAsciiStream(int columnIndex,
                            java.io.InputStream x) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5713,7 +5713,7 @@
      */
     public void updateAsciiStream(String columnLabel,
                            java.io.InputStream x) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
 
@@ -5738,7 +5738,7 @@
     public void updateBinaryStream(String columnLabel,
                             java.io.InputStream x,
                             long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5763,7 +5763,7 @@
      */
     public void updateBinaryStream(int columnIndex,
                             java.io.InputStream x) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
 
@@ -5790,7 +5790,7 @@
      */
     public void updateBinaryStream(String columnLabel,
                             java.io.InputStream x) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
 
@@ -5816,7 +5816,7 @@
     public void updateCharacterStream(String columnLabel,
                              java.io.Reader reader,
                              long length) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5841,7 +5841,7 @@
      */
     public void updateCharacterStream(int columnIndex,
                              java.io.Reader x) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
     /**
@@ -5868,7 +5868,7 @@
      */
     public void updateCharacterStream(String columnLabel,
                              java.io.Reader reader) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
 
@@ -5885,7 +5885,7 @@
   * @since 1.4
   */
   public void setURL(int parameterIndex, java.net.URL x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -5914,7 +5914,7 @@
   */
   public void setNClob(int parameterIndex, Reader reader)
     throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
    /**
@@ -5942,7 +5942,7 @@
             */
             public void setNClob(String parameterName, Reader reader, long length)
     throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -5969,7 +5969,7 @@
   */
   public void setNClob(String parameterName, Reader reader)
     throws SQLException{
-             throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+             throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -5996,7 +5996,7 @@
      */
      public void setNClob(int parameterIndex, Reader reader, long length)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6012,7 +6012,7 @@
      * @since 1.6
      */
      public void setNClob(int parameterIndex, NClob value) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6029,7 +6029,7 @@
   */
  public void setNString(String parameterName, String value)
          throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6046,7 +6046,7 @@
   * @since 1.6
   */
   public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6066,7 +6066,7 @@
   */
  public void setNCharacterStream(String parameterName, Reader value, long length)
          throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
   /**
@@ -6092,7 +6092,7 @@
   * @since 1.6
   */
   public void setNCharacterStream(String parameterName, Reader value) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
   /**
@@ -6118,7 +6118,7 @@
     */
     public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
     /**
@@ -6144,7 +6144,7 @@
               */
       public  void setClob(String parameterName, Reader reader, long length)
       throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6163,7 +6163,7 @@
     * @since 1.6
     */
     public void setClob (String parameterName, Clob x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6188,7 +6188,7 @@
     */
     public void setClob(String parameterName, Reader reader)
       throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6210,7 +6210,7 @@
     */
     public void setDate(String parameterName, java.sql.Date x)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
    /**
@@ -6236,7 +6236,7 @@
     */
    public void setDate(String parameterName, java.sql.Date x, Calendar cal)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6256,7 +6256,7 @@
     */
    public void setTime(String parameterName, java.sql.Time x)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6282,7 +6282,7 @@
     */
    public void setTime(String parameterName, java.sql.Time x, Calendar cal)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
    /**
@@ -6308,7 +6308,7 @@
    */
    public void setClob(int parameterIndex, Reader reader)
      throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6333,7 +6333,7 @@
    */
    public void setClob(int parameterIndex, Reader reader, long length)
      throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6363,7 +6363,7 @@
     */
     public void setBlob(int parameterIndex, InputStream inputStream, long length)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6395,7 +6395,7 @@
     */
     public void setBlob(int parameterIndex, InputStream inputStream)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6426,7 +6426,7 @@
       */
       public void setBlob(String parameterName, InputStream inputStream, long length)
          throws SQLException{
-         throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+         throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
     }
 
 
@@ -6444,7 +6444,7 @@
     * @since 1.6
     */
    public void setBlob (String parameterName, Blob x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6470,7 +6470,7 @@
     */
     public void setBlob(String parameterName, InputStream inputStream)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
   /**
@@ -6516,7 +6516,7 @@
   */
   public void setObject(String parameterName, Object x, int targetSqlType, int scale)
      throws SQLException{
-      throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+      throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
  }
 
   /**
@@ -6542,7 +6542,7 @@
     */
     public void setObject(String parameterName, Object x, int targetSqlType)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6582,7 +6582,7 @@
    * @since 1.4
    */
    public void setObject(String parameterName, Object x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
   /**
@@ -6609,7 +6609,7 @@
   */
  public void setAsciiStream(String parameterName, java.io.InputStream x, int length)
      throws SQLException{
-      throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+      throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
  }
 
 
@@ -6636,7 +6636,7 @@
   */
  public void setBinaryStream(String parameterName, java.io.InputStream x,
                       int length) throws SQLException{
-      throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+      throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
  }
 
  /**
@@ -6665,7 +6665,7 @@
   public void setCharacterStream(String parameterName,
                           java.io.Reader reader,
                           int length) throws SQLException{
-       throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+       throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
   }
 
   /**
@@ -6692,7 +6692,7 @@
   */
   public void setAsciiStream(String parameterName, java.io.InputStream x)
           throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6719,7 +6719,7 @@
     */
    public void setBinaryStream(String parameterName, java.io.InputStream x)
    throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6748,7 +6748,7 @@
     */
    public void setCharacterStream(String parameterName,
                          java.io.Reader reader) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
    /**
@@ -6767,7 +6767,7 @@
     * @since 1.4
     */
    public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6788,7 +6788,7 @@
     * @since 1.4
     */
    public void setString(String parameterName, String x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6810,7 +6810,7 @@
     * @since 1.4
     */
    public void setBytes(String parameterName, byte x[]) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6830,7 +6830,7 @@
     */
    public void setTimestamp(String parameterName, java.sql.Timestamp x)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
     /**
@@ -6847,7 +6847,7 @@
     * @since 1.4
     */
    public void setNull(String parameterName, int sqlType) throws SQLException {
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6884,7 +6884,7 @@
     */
    public void setNull (String parameterName, int sqlType, String typeName)
        throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6902,7 +6902,7 @@
     * @since 1.4
     */
    public void setBoolean(String parameterName, boolean x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6922,7 +6922,7 @@
     * @since 1.4
     */
    public void setByte(String parameterName, byte x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6941,7 +6941,7 @@
     * @since 1.4
     */
    public void setShort(String parameterName, short x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6960,7 +6960,7 @@
     * @since 1.4
     */
    public void setInt(String parameterName, int x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -6978,7 +6978,7 @@
     * @since 1.4
     */
    public void setLong(String parameterName, long x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
 
@@ -6997,7 +6997,7 @@
     * @since 1.4
     */
    public void setFloat(String parameterName, float x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
  /**
@@ -7015,7 +7015,7 @@
     * @since 1.4
     */
    public void setDouble(String parameterName, double x) throws SQLException{
-        throw new SQLFeatureNotSupportedException(jdbcResBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
+        throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
    }
 
     /**
@@ -7023,15 +7023,25 @@
      * during the deserialization process
      *
      */
-    protected void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
         // Default state initialization happens here
         ois.defaultReadObject();
         // Initialization of transient Res Bundle happens here .
         try {
-           jdbcResBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
         } catch(IOException ioe) {}
 
     }
 
    static final long serialVersionUID = -3591946023893483003L;
+
+ //------------------------- JDBC 4.1 -----------------------------------
+
+    public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
+        throw new SQLFeatureNotSupportedException("Not supported yet.");
+    }
+
+    public <T> T getObject(String columnLabel, Class<T> type) throws SQLException {
+        throw new SQLFeatureNotSupportedException("Not supported yet.");
+    }
 }
--- a/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -153,4 +153,5 @@
        return propResBundle.handleGetObject(key);
     }
 
+    static final long serialVersionUID = 436199386225359954L;
 }
--- a/src/share/classes/com/sun/rowset/JoinRowSetImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/JoinRowSetImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -127,6 +127,11 @@
         strMatchKey = null;
         supportedJOINs =
               new boolean[] {false, true, false, false, false};
+       try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
 
     }
 
@@ -4306,5 +4311,22 @@
          return crsInternal.createCopySchema();
      }
 
-        static final long serialVersionUID = -5590501621560008453L;
+    /**
+     * This method re populates the resBundle
+     * during the deserialization process
+     *
+     */
+     private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        // Default state initialization happens here
+        ois.defaultReadObject();
+        // Initialization of transient Res Bundle happens here .
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
+     }
+
+     static final long serialVersionUID = -5590501621560008453L;
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/rowset/RowSetFactoryImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.rowset;
+
+import java.sql.SQLException;
+import javax.sql.rowset.CachedRowSet;
+import javax.sql.rowset.FilteredRowSet;
+import javax.sql.rowset.JdbcRowSet;
+import javax.sql.rowset.JoinRowSet;
+import javax.sql.rowset.WebRowSet;
+import javax.sql.rowset.RowSetFactory;
+
+/**
+ * This is the implementation specific class for the
+ * <code>javax.sql.rowset.spi.RowSetFactory</code>. This is the platform
+ * default implementation for the Java SE platform.
+ *
+ * @author Lance Andersen
+ *
+ *
+ * @version 1.7
+ */
+public  final class RowSetFactoryImpl implements RowSetFactory {
+
+    public CachedRowSet createCachedRowSet() throws SQLException {
+        return new com.sun.rowset.CachedRowSetImpl();
+    }
+
+    public FilteredRowSet createFilteredRowSet() throws SQLException {
+        return new com.sun.rowset.FilteredRowSetImpl();
+    }
+
+
+    public JdbcRowSet createJdbcRowSet() throws SQLException {
+        return new com.sun.rowset.JdbcRowSetImpl();
+    }
+
+    public JoinRowSet createJoinRowSet() throws SQLException {
+        return new com.sun.rowset.JoinRowSetImpl();
+    }
+
+    public WebRowSet createWebRowSet() throws SQLException {
+        return new com.sun.rowset.WebRowSetImpl();
+    }
+
+}
--- a/src/share/classes/com/sun/rowset/WebRowSetImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/WebRowSetImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -103,6 +103,12 @@
      */
     public WebRowSetImpl(Hashtable env) throws SQLException {
 
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
         if ( env == null) {
             throw new SQLException(resBundle.handleGetObject("webrowsetimpl.nullhash").toString());
         }
@@ -263,5 +269,23 @@
 
             this.writeXml(oStream);
     }
-static final long serialVersionUID = -8771775154092422943L;
+
+    /**
+     * This method re populates the resBundle
+     * during the deserialization process
+     *
+     */
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        // Default state initialization happens here
+        ois.defaultReadObject();
+        // Initialization of transient Res Bundle happens here .
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
+    }
+
+    static final long serialVersionUID = -8771775154092422943L;
 }
--- a/src/share/classes/com/sun/rowset/internal/CachedRowSetReader.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/internal/CachedRowSetReader.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -490,4 +490,17 @@
         startPosition = pos;
     }
 
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        // Default state initialization happens here
+        ois.defaultReadObject();
+        // Initialization of  Res Bundle happens here .
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
+    }
+
+    static final long serialVersionUID =5049738185801363801L;
 }
--- a/src/share/classes/com/sun/rowset/internal/CachedRowSetWriter.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/internal/CachedRowSetWriter.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -31,7 +31,13 @@
 import java.io.*;
 
 import com.sun.rowset.*;
+import java.text.MessageFormat;
 import javax.sql.rowset.*;
+import javax.sql.rowset.serial.SQLInputImpl;
+import javax.sql.rowset.serial.SerialArray;
+import javax.sql.rowset.serial.SerialBlob;
+import javax.sql.rowset.serial.SerialClob;
+import javax.sql.rowset.serial.SerialStruct;
 import javax.sql.rowset.spi.*;
 
 
@@ -53,6 +59,7 @@
  * Standard JDBC RowSet implementations provide an object instance of this
  * writer by invoking the <code>SyncProvider.getRowSetWriter()</code> method.
  *
+ * @version 0.2
  * @author Jonathan Bruce
  * @see javax.sql.rowset.spi.SyncProvider
  * @see javax.sql.rowset.spi.SyncFactory
@@ -508,10 +515,11 @@
 
             ResultSet rs = null;
             rs = pstmt.executeQuery();
-            if (rs.next() == true) {
+            ResultSetMetaData rsmd = rs.getMetaData();
 
+            if (rs.next()) {
                 if (rs.next()) {
-                  /**  More than one row conflict.
+                   /** More than one row conflict.
                     *  If rs has only one row we are able to
                     *  uniquely identify the row where update
                     *  have to happen else if more than one
@@ -528,7 +536,7 @@
                 // we require the record in rs to be used.
                 // rs.close();
                 // pstmt.close();
-                        rs.first();
+                rs.first();
 
                 // how many fields need to be updated
                 int colsNotChanged = 0;
@@ -552,6 +560,49 @@
                 orig = origVals.getObject(i);
                 curr = crs.getObject(i);
                 rsval = rs.getObject(i);
+                /*
+                 * the following block creates equivalent objects
+                 * that would have been created if this rs is populated
+                 * into a CachedRowSet so that comparison of the column values
+                 * from the ResultSet and CachedRowSet are possible
+                 */
+                Map map = (crs.getTypeMap() == null)?con.getTypeMap():crs.getTypeMap();
+                if (rsval instanceof Struct) {
+
+                    Struct s = (Struct)rsval;
+
+                    // look up the class in the map
+                    Class c = null;
+                    c = (Class)map.get(s.getSQLTypeName());
+                    if (c != null) {
+                        // create new instance of the class
+                        SQLData obj = null;
+                        try {
+                            obj = (SQLData)c.newInstance();
+                        } catch (java.lang.InstantiationException ex) {
+                            throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.unableins").toString(),
+                            ex.getMessage()));
+                        } catch (java.lang.IllegalAccessException ex) {
+                            throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.unableins").toString(),
+                            ex.getMessage()));
+                        }
+                        // get the attributes from the struct
+                        Object attribs[] = s.getAttributes(map);
+                        // create the SQLInput "stream"
+                        SQLInputImpl sqlInput = new SQLInputImpl(attribs, map);
+                        // read the values...
+                        obj.readSQL(sqlInput, s.getSQLTypeName());
+                        rsval = obj;
+                    }
+                } else if (rsval instanceof SQLData) {
+                    rsval = new SerialStruct((SQLData)rsval, map);
+                } else if (rsval instanceof Blob) {
+                    rsval = new SerialBlob((Blob)rsval);
+                } else if (rsval instanceof Clob) {
+                    rsval = new SerialClob((Clob)rsval);
+                } else if (rsval instanceof java.sql.Array) {
+                    rsval = new SerialArray((java.sql.Array)rsval, map);
+                }
 
                 // reset boolNull if it had been set
                 boolNull = true;
@@ -669,6 +720,9 @@
                                  }
                 } //end for
 
+                rs.close();
+                pstmt.close();
+
                this.crsResolve.insertRow();
                    this.crsResolve.moveToCurrentRow();
 
@@ -1179,11 +1233,22 @@
     private void buildKeyDesc(CachedRowSet crs) throws SQLException {
 
         keyCols = crs.getKeyColumns();
+        ResultSetMetaData resultsetmd = crs.getMetaData();
         if (keyCols == null || keyCols.length == 0) {
-            keyCols = new int[callerColumnCount];
-            for (int i = 0; i < keyCols.length; ) {
-                keyCols[i] = ++i;
+            ArrayList<Integer> listKeys = new ArrayList<Integer>();
+
+            for (int i = 0; i < callerColumnCount; i++ ) {
+                if(resultsetmd.getColumnType(i+1) != java.sql.Types.CLOB &&
+                        resultsetmd.getColumnType(i+1) != java.sql.Types.STRUCT &&
+                        resultsetmd.getColumnType(i+1) != java.sql.Types.SQLXML &&
+                        resultsetmd.getColumnType(i+1) != java.sql.Types.BLOB &&
+                        resultsetmd.getColumnType(i+1) != java.sql.Types.ARRAY &&
+                        resultsetmd.getColumnType(i+1) != java.sql.Types.OTHER )
+                    listKeys.add(i+1);
             }
+            keyCols = new int[listKeys.size()];
+            for (int i = 0; i < listKeys.size(); i++ )
+                keyCols[i] = listKeys.get(i);
         }
         params = new Object[keyCols.length];
     }
@@ -1359,4 +1424,17 @@
         }
     }
 
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        // Default state initialization happens here
+        ois.defaultReadObject();
+        // Initialization of  Res Bundle happens here .
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
+    }
+
+    static final long serialVersionUID =-8506030970299413976L;
 }
--- a/src/share/classes/com/sun/rowset/internal/InsertRow.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/internal/InsertRow.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -157,4 +157,23 @@
         origVals[idx - 1] = val;
         markColInserted(idx - 1);
     }
+
+    /**
+     * This method re populates the resBundle
+     * during the deserialization process
+     *
+     */
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        // Default state initialization happens here
+        ois.defaultReadObject();
+        // Initialization of transient Res Bundle happens here .
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
+    }
+
+    static final long serialVersionUID = 1066099658102869344L;
 }
--- a/src/share/classes/com/sun/rowset/internal/SyncResolverImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/internal/SyncResolverImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2010, Oracle and/or its affiliates. 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
@@ -35,6 +35,7 @@
 
 import com.sun.rowset.*;
 import java.io.IOException;
+import java.io.ObjectInputStream;
 
 /**
  * There will be two sets of data which will be maintained by the rowset at the
@@ -4837,4 +4838,23 @@
                             throws SQLException {
           throw new UnsupportedOperationException("Operation not yet supported");
        }
+
+      /**
+       * This method re populates the resBundle
+       * during the deserialization process
+       *
+       */
+       private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+         // Default state initialization happens here
+         ois.defaultReadObject();
+         // Initialization of transient Res Bundle happens here .
+         try {
+            resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+         } catch(IOException ioe) {
+             throw new RuntimeException(ioe);
+         }
+
+       }
+
+       static final long serialVersionUID = -3345004441725080251L;
 } //end class
--- a/src/share/classes/com/sun/rowset/internal/WebRowSetXmlReader.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/internal/WebRowSetXmlReader.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -216,4 +216,22 @@
     public void readData(RowSetInternal caller) {
     }
 
+    /**
+     * This method re populates the resBundle
+     * during the deserialization process
+     *
+     */
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        // Default state initialization happens here
+        ois.defaultReadObject();
+        // Initialization of transient Res Bundle happens here .
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
+    }
+
+    static final long serialVersionUID = -9127058392819008014L;
 }
--- a/src/share/classes/com/sun/rowset/internal/WebRowSetXmlWriter.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/internal/WebRowSetXmlWriter.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -663,4 +663,23 @@
         return s;
     }
 
+
+    /**
+     * This method re populates the resBundle
+     * during the deserialization process
+     *
+     */
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        // Default state initialization happens here
+        ois.defaultReadObject();
+        // Initialization of transient Res Bundle happens here .
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
+    }
+
+    static final long serialVersionUID = 7163134986189677641L;
 }
--- a/src/share/classes/com/sun/rowset/providers/RIOptimisticProvider.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/rowset/providers/RIOptimisticProvider.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -245,4 +245,18 @@
     public String getVendor() {
         return this.vendorName;
     }
+
+    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+        // Default state initialization happens here
+        ois.defaultReadObject();
+        // Initialization of transient Res Bundle happens here .
+        try {
+           resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+        } catch(IOException ioe) {
+            throw new RuntimeException(ioe);
+        }
+
+    }
+    static final long serialVersionUID =-3143367176751761936L;
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/security/ntlm/Client.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.security.ntlm;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.Locale;
+
+/**
+ * The NTLM client. Not multi-thread enabled.<p>
+ * Example:
+ * <pre>
+ * Client client = new Client(null, "host", "dummy",
+ *       "REALM", "t0pSeCr3t".toCharArray());
+ * byte[] type1 = client.type1();
+ * // Send type1 to server and receive response as type2
+ * byte[] type3 = client.type3(type2, nonce);
+ * // Send type3 to server
+ * </pre>
+ */
+public final class Client extends NTLM {
+    final private String hostname;
+    final private String username;
+
+    private String domain;    // might be updated by Type 2 msg
+    private byte[] pw1, pw2;
+
+    /**
+     * Creates an NTLM Client instance.
+     * @param version the NTLM version to use, which can be:
+     * <ul>
+     * <li>LM/NTLM: Original NTLM v1
+     * <li>LM: Original NTLM v1, LM only
+     * <li>NTLM: Original NTLM v1, NTLM only
+     * <li>NTLM2: NTLM v1 with Client Challenge
+     * <li>LMv2/NTLMv2: NTLM v2
+     * <li>LMv2: NTLM v2, LM only
+     * <li>NTLMv2: NTLM v2, NTLM only
+     * </ul>
+     * If null, "LMv2/NTLMv2" will be used.
+     * @param hostname hostname of the client, can be null
+     * @param username username to be authenticated, must not be null
+     * @param domain domain of {@code username}, can be null
+     * @param password password for {@code username}, must not be not null.
+     * This method does not make any modification to this parameter, it neither
+     * needs to access the content of this parameter after this method call,
+     * so you are free to modify or nullify this parameter after this call.
+     * @throws NullPointerException if {@code username} or {@code password} is null.
+     * @throws NTLMException if {@code version} is illegal
+     */
+    public Client(String version, String hostname, String username,
+            String domain, char[] password) throws NTLMException {
+        super(version);
+        if ((username == null || password == null)) {
+            throw new NullPointerException("username/password cannot be null");
+        }
+        this.hostname = hostname;
+        this.username = username;
+        this.domain = domain;
+        this.pw1 = getP1(password);
+        this.pw2 = getP2(password);
+        debug("NTLM Client: (h,u,t,version(v)) = (%s,%s,%s,%s(%s))\n",
+                    hostname, username, domain, version, v.toString());
+    }
+
+    /**
+     * Generates the Type 1 message
+     * @return the message generated
+     */
+    public byte[] type1() {
+        Writer p = new Writer(1, 32);
+        int flags = 0x8203;
+        if (hostname != null) {
+            flags |= 0x2000;
+        }
+        if (domain != null) {
+            flags |= 0x1000;
+        }
+        if (v != Version.NTLM) {
+            flags |= 0x80000;
+        }
+        p.writeInt(12, flags);
+        p.writeSecurityBuffer(24, hostname, false);
+        p.writeSecurityBuffer(16, domain, false);
+        debug("NTLM Client: Type 1 created\n");
+        debug(p.getBytes());
+        return p.getBytes();
+    }
+
+    /**
+     * Generates the Type 3 message
+     * @param type2 the responding Type 2 message from server, must not be null
+     * @param nonce random 8-byte array to be used in message generation,
+     * must not be null except for original NTLM v1
+     * @return the message generated
+     * @throws NullPointerException if {@code type2} or {@code nonce} is null
+     * for NTLM v1.
+     * @throws NTLMException if the incoming message is invalid
+     */
+    public byte[] type3(byte[] type2, byte[] nonce) throws NTLMException {
+        if (type2 == null || (v != Version.NTLM && nonce == null)) {
+            throw new NullPointerException("type2 and nonce cannot be null");
+        }
+        debug("NTLM Client: Type 2 received\n");
+        debug(type2);
+        Reader r = new Reader(type2);
+        byte[] challenge = r.readBytes(24, 8);
+        int inputFlags = r.readInt(20);
+        boolean unicode = (inputFlags & 1) == 1;
+        String domainFromServer = r.readSecurityBuffer(12, unicode);
+        if (domainFromServer != null) {
+            domain = domainFromServer;
+        }
+        if (domain == null) {
+            throw new NTLMException(NTLMException.NO_DOMAIN_INFO,
+                    "No domain info");
+        }
+
+        int flags = 0x88200 | (inputFlags & 3);
+        Writer p = new Writer(3, 64);
+        byte[] lm = null, ntlm = null;
+
+        p.writeSecurityBuffer(28, domain, unicode);
+        p.writeSecurityBuffer(36, username, unicode);
+        p.writeSecurityBuffer(44, hostname, unicode);
+
+        if (v == Version.NTLM) {
+            byte[] lmhash = calcLMHash(pw1);
+            byte[] nthash = calcNTHash(pw2);
+            if (writeLM) lm = calcResponse (lmhash, challenge);
+            if (writeNTLM) ntlm = calcResponse (nthash, challenge);
+        } else if (v == Version.NTLM2) {
+            byte[] nthash = calcNTHash(pw2);
+            lm = ntlm2LM(nonce);
+            ntlm = ntlm2NTLM(nthash, nonce, challenge);
+        } else {
+            byte[] nthash = calcNTHash(pw2);
+            if (writeLM) lm = calcV2(nthash,
+                    username.toUpperCase(Locale.US)+domain, nonce, challenge);
+            if (writeNTLM) {
+                byte[] alist = type2.length > 48 ?
+                    r.readSecurityBuffer(40) : new byte[0];
+                byte[] blob = new byte[32+alist.length];
+                System.arraycopy(new byte[]{1,1,0,0,0,0,0,0}, 0, blob, 0, 8);
+                // TS
+                byte[] time = BigInteger.valueOf(new Date().getTime())
+                        .add(new BigInteger("11644473600000"))
+                        .multiply(BigInteger.valueOf(10000))
+                        .toByteArray();
+                for (int i=0; i<time.length; i++) {
+                    blob[8+time.length-i-1] = time[i];
+                }
+                System.arraycopy(nonce, 0, blob, 16, 8);
+                System.arraycopy(new byte[]{0,0,0,0}, 0, blob, 24, 4);
+                System.arraycopy(alist, 0, blob, 28, alist.length);
+                System.arraycopy(new byte[]{0,0,0,0}, 0,
+                        blob, 28+alist.length, 4);
+                ntlm = calcV2(nthash, username.toUpperCase(Locale.US)+domain,
+                        blob, challenge);
+            }
+        }
+        p.writeSecurityBuffer(12, lm);
+        p.writeSecurityBuffer(20, ntlm);
+        p.writeSecurityBuffer(52, new byte[0]);
+
+        p.writeInt(60, flags);
+        debug("NTLM Client: Type 3 created\n");
+        debug(p.getBytes());
+        return p.getBytes();
+    }
+
+    /**
+     * Returns the domain value provided by server after the authentication
+     * is complete, or the domain value provided by the client before it.
+     * @return the domain
+     */
+    public String getDomain() {
+        return domain;
+    }
+
+    /**
+     * Disposes any password-derived information.
+     */
+    public void dispose() {
+        Arrays.fill(pw1, (byte)0);
+        Arrays.fill(pw2, (byte)0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/security/ntlm/NTLM.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,426 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.security.ntlm;
+
+import static com.sun.security.ntlm.Version.*;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+import java.util.Arrays;
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.Mac;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESKeySpec;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * NTLM authentication implemented according to MS-NLMP, version 12.1
+ * @since 1.7
+ */
+class NTLM {
+
+    private final SecretKeyFactory fac;
+    private final Cipher cipher;
+    private final MessageDigest md4;
+    private final Mac hmac;
+    private final MessageDigest md5;
+    private static final boolean DEBUG =
+            System.getProperty("ntlm.debug") != null;
+
+    final Version v;
+
+    final boolean writeLM;
+    final boolean writeNTLM;
+
+    protected NTLM(String version) throws NTLMException {
+        if (version == null) version = "LMv2/NTLMv2";
+        switch (version) {
+            case "LM": v = NTLM; writeLM = true; writeNTLM = false; break;
+            case "NTLM": v = NTLM; writeLM = false; writeNTLM = true; break;
+            case "LM/NTLM": v = NTLM; writeLM = writeNTLM = true; break;
+            case "NTLM2": v = NTLM2; writeLM = writeNTLM = true; break;
+            case "LMv2": v = NTLMv2; writeLM = true; writeNTLM = false; break;
+            case "NTLMv2": v = NTLMv2; writeLM = false; writeNTLM = true; break;
+            case "LMv2/NTLMv2": v = NTLMv2; writeLM = writeNTLM = true; break;
+            default: throw new NTLMException(NTLMException.BAD_VERSION,
+                    "Unknown version " + version);
+        }
+        try {
+            fac = SecretKeyFactory.getInstance ("DES");
+            cipher = Cipher.getInstance ("DES/ECB/NoPadding");
+            md4 = sun.security.provider.MD4.getInstance();
+            hmac = Mac.getInstance("HmacMD5");
+            md5 = MessageDigest.getInstance("MD5");
+        } catch (NoSuchPaddingException e) {
+            throw new AssertionError();
+        } catch (NoSuchAlgorithmException e) {
+            throw new AssertionError();
+        }
+    }
+
+    /**
+     * Prints out a formatted string, called in various places inside then NTLM
+     * implementation for debugging/logging purposes. When the system property
+     * "ntlm.debug" is set, <code>System.out.printf(format, args)</code> is
+     * called. This method is designed to be overridden by child classes to
+     * match their own debugging/logging mechanisms.
+     * @param format a format string
+     * @param args the arguments referenced by <code>format</code>
+     * @see java.io.PrintStream#printf(java.lang.String, java.lang.Object[])
+     */
+    public void debug(String format, Object... args) {
+        if (DEBUG) {
+            System.out.printf(format, args);
+        }
+    }
+
+    /**
+     * Prints out the content of a byte array, called in various places inside
+     * the NTLM implementation for debugging/logging purposes. When the system
+     * property "ntlm.debug" is set, the hexdump of the array is printed into
+     * System.out. This method is designed to be overridden by child classes to
+     * match their own debugging/logging mechanisms.
+     * @param bytes the byte array to print out
+     */
+    public void debug(byte[] bytes) {
+        if (DEBUG) {
+            try {
+                new sun.misc.HexDumpEncoder().encodeBuffer(bytes, System.out);
+            } catch (IOException ioe) {
+                // Impossible
+            }
+        }
+    }
+
+    /**
+     * Reading an NTLM packet
+     */
+    static class Reader {
+
+        private final byte[] internal;
+
+        Reader(byte[] data) {
+            internal = data;
+        }
+
+        int readInt(int offset) throws NTLMException {
+            try {
+                return internal[offset] & 0xff +
+                        (internal[offset+1] & 0xff << 8) +
+                        (internal[offset+2] & 0xff << 16) +
+                        (internal[offset+3] & 0xff << 24);
+            } catch (ArrayIndexOutOfBoundsException ex) {
+                throw new NTLMException(NTLMException.PACKET_READ_ERROR,
+                        "Input message incorrect size");
+            }
+        }
+
+        int readShort(int offset) throws NTLMException {
+            try {
+                return internal[offset] & 0xff +
+                        (internal[offset+1] & 0xff << 8);
+            } catch (ArrayIndexOutOfBoundsException ex) {
+                throw new NTLMException(NTLMException.PACKET_READ_ERROR,
+                        "Input message incorrect size");
+            }
+        }
+
+        byte[] readBytes(int offset, int len) throws NTLMException {
+            try {
+                return Arrays.copyOfRange(internal, offset, offset + len);
+            } catch (ArrayIndexOutOfBoundsException ex) {
+                throw new NTLMException(NTLMException.PACKET_READ_ERROR,
+                        "Input message incorrect size");
+            }
+        }
+
+        byte[] readSecurityBuffer(int offset) throws NTLMException {
+            int pos = readInt(offset+4);
+            if (pos == 0) return null;
+            try {
+                return Arrays.copyOfRange(
+                        internal, pos, pos + readShort(offset));
+            } catch (ArrayIndexOutOfBoundsException ex) {
+                throw new NTLMException(NTLMException.PACKET_READ_ERROR,
+                        "Input message incorrect size");
+            }
+        }
+
+        String readSecurityBuffer(int offset, boolean unicode)
+                throws NTLMException {
+            byte[] raw = readSecurityBuffer(offset);
+            try {
+                return raw == null ? null : new String(
+                        raw, unicode ? "UnicodeLittleUnmarked" : "ISO8859_1");
+            } catch (UnsupportedEncodingException ex) {
+                throw new NTLMException(NTLMException.PACKET_READ_ERROR,
+                        "Invalid input encoding");
+            }
+        }
+    }
+
+    /**
+     * Writing an NTLM packet
+     */
+    static class Writer {
+
+        private byte[] internal;    // buffer
+        private int current;        // current written content interface buffer
+
+        /**
+         * Starts writing a NTLM packet
+         * @param type NEGOTIATE || CHALLENGE || AUTHENTICATE
+         * @param len the base length, without security buffers
+         */
+        Writer(int type, int len) {
+            assert len < 256;
+            internal = new byte[256];
+            current = len;
+            System.arraycopy (
+                    new byte[] {'N','T','L','M','S','S','P',0,(byte)type},
+                    0, internal, 0, 9);
+        }
+
+        void writeShort(int offset, int number) {
+            internal[offset] = (byte)(number);
+            internal[offset+1] = (byte)(number >> 8);
+        }
+
+        void writeInt(int offset, int number) {
+            internal[offset] = (byte)(number);
+            internal[offset+1] = (byte)(number >> 8);
+            internal[offset+2] = (byte)(number >> 16);
+            internal[offset+3] = (byte)(number >> 24);
+        }
+
+        void writeBytes(int offset, byte[] data) {
+            System.arraycopy(data, 0, internal, offset, data.length);
+        }
+
+        void writeSecurityBuffer(int offset, byte[] data) {
+            if (data == null) {
+                writeShort(offset+4, current);
+            } else {
+                int len = data.length;
+                if (current + len > internal.length) {
+                    internal = Arrays.copyOf(internal, current + len + 256);
+                }
+                writeShort(offset, len);
+                writeShort(offset+2, len);
+                writeShort(offset+4, current);
+                System.arraycopy(data, 0, internal, current, len);
+                current += len;
+            }
+        }
+
+        void writeSecurityBuffer(int offset, String str, boolean unicode) {
+            try {
+                writeSecurityBuffer(offset, str == null ? null : str.getBytes(
+                        unicode ? "UnicodeLittleUnmarked" : "ISO8859_1"));
+            } catch (UnsupportedEncodingException ex) {
+                assert false;
+            }
+        }
+
+        byte[] getBytes() {
+            return Arrays.copyOf(internal, current);
+        }
+    }
+
+    // LM/NTLM
+
+    /* Convert a 7 byte array to an 8 byte array (for a des key with parity)
+     * input starts at offset off
+     */
+    byte[] makeDesKey (byte[] input, int off) {
+        int[] in = new int [input.length];
+        for (int i=0; i<in.length; i++ ) {
+            in[i] = input[i]<0 ? input[i]+256: input[i];
+        }
+        byte[] out = new byte[8];
+        out[0] = (byte)in[off+0];
+        out[1] = (byte)(((in[off+0] << 7) & 0xFF) | (in[off+1] >> 1));
+        out[2] = (byte)(((in[off+1] << 6) & 0xFF) | (in[off+2] >> 2));
+        out[3] = (byte)(((in[off+2] << 5) & 0xFF) | (in[off+3] >> 3));
+        out[4] = (byte)(((in[off+3] << 4) & 0xFF) | (in[off+4] >> 4));
+        out[5] = (byte)(((in[off+4] << 3) & 0xFF) | (in[off+5] >> 5));
+        out[6] = (byte)(((in[off+5] << 2) & 0xFF) | (in[off+6] >> 6));
+        out[7] = (byte)((in[off+6] << 1) & 0xFF);
+        return out;
+    }
+
+    byte[] calcLMHash (byte[] pwb) {
+        byte[] magic = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25};
+        byte[] pwb1 = new byte [14];
+        int len = pwb.length;
+        if (len > 14)
+            len = 14;
+        System.arraycopy (pwb, 0, pwb1, 0, len); /* Zero padded */
+
+        try {
+            DESKeySpec dks1 = new DESKeySpec (makeDesKey (pwb1, 0));
+            DESKeySpec dks2 = new DESKeySpec (makeDesKey (pwb1, 7));
+
+            SecretKey key1 = fac.generateSecret (dks1);
+            SecretKey key2 = fac.generateSecret (dks2);
+            cipher.init (Cipher.ENCRYPT_MODE, key1);
+            byte[] out1 = cipher.doFinal (magic, 0, 8);
+            cipher.init (Cipher.ENCRYPT_MODE, key2);
+            byte[] out2 = cipher.doFinal (magic, 0, 8);
+            byte[] result = new byte [21];
+            System.arraycopy (out1, 0, result, 0, 8);
+            System.arraycopy (out2, 0, result, 8, 8);
+            return result;
+        } catch (InvalidKeyException ive) {
+            // Will not happen, all key material are 8 bytes
+            assert false;
+        } catch (InvalidKeySpecException ikse) {
+            // Will not happen, we only feed DESKeySpec to DES factory
+            assert false;
+        } catch (IllegalBlockSizeException ibse) {
+            // Will not happen, we encrypt 8 bytes
+            assert false;
+        } catch (BadPaddingException bpe) {
+            // Will not happen, this is encryption
+            assert false;
+        }
+        return null;    // will not happen, we returned already
+    }
+
+    byte[] calcNTHash (byte[] pw) {
+        byte[] out = md4.digest (pw);
+        byte[] result = new byte [21];
+        System.arraycopy (out, 0, result, 0, 16);
+        return result;
+    }
+
+    /* key is a 21 byte array. Split it into 3 7 byte chunks,
+     * Convert each to 8 byte DES keys, encrypt the text arg with
+     * each key and return the three results in a sequential []
+     */
+    byte[] calcResponse (byte[] key, byte[] text) {
+        try {
+            assert key.length == 21;
+            DESKeySpec dks1 = new DESKeySpec(makeDesKey(key, 0));
+            DESKeySpec dks2 = new DESKeySpec(makeDesKey(key, 7));
+            DESKeySpec dks3 = new DESKeySpec(makeDesKey(key, 14));
+            SecretKey key1 = fac.generateSecret(dks1);
+            SecretKey key2 = fac.generateSecret(dks2);
+            SecretKey key3 = fac.generateSecret(dks3);
+            cipher.init(Cipher.ENCRYPT_MODE, key1);
+            byte[] out1 = cipher.doFinal(text, 0, 8);
+            cipher.init(Cipher.ENCRYPT_MODE, key2);
+            byte[] out2 = cipher.doFinal(text, 0, 8);
+            cipher.init(Cipher.ENCRYPT_MODE, key3);
+            byte[] out3 = cipher.doFinal(text, 0, 8);
+            byte[] result = new byte[24];
+            System.arraycopy(out1, 0, result, 0, 8);
+            System.arraycopy(out2, 0, result, 8, 8);
+            System.arraycopy(out3, 0, result, 16, 8);
+            return result;
+        } catch (IllegalBlockSizeException ex) {    // None will happen
+            assert false;
+        } catch (BadPaddingException ex) {
+            assert false;
+        } catch (InvalidKeySpecException ex) {
+            assert false;
+        } catch (InvalidKeyException ex) {
+            assert false;
+        }
+        return null;
+    }
+
+    // LMv2/NTLMv2
+
+    byte[] hmacMD5(byte[] key, byte[] text) {
+        try {
+            SecretKeySpec skey =
+                    new SecretKeySpec(Arrays.copyOf(key, 16), "HmacMD5");
+            hmac.init(skey);
+            return hmac.doFinal(text);
+        } catch (InvalidKeyException ex) {
+            assert false;
+        } catch (RuntimeException e) {
+            assert false;
+        }
+        return null;
+    }
+
+    byte[] calcV2(byte[] nthash, String text, byte[] blob, byte[] challenge) {
+        try {
+            byte[] ntlmv2hash = hmacMD5(nthash,
+                    text.getBytes("UnicodeLittleUnmarked"));
+            byte[] cn = new byte[blob.length+8];
+            System.arraycopy(challenge, 0, cn, 0, 8);
+            System.arraycopy(blob, 0, cn, 8, blob.length);
+            byte[] result = new byte[16+blob.length];
+            System.arraycopy(hmacMD5(ntlmv2hash, cn), 0, result, 0, 16);
+            System.arraycopy(blob, 0, result, 16, blob.length);
+            return result;
+        } catch (UnsupportedEncodingException ex) {
+            assert false;
+        }
+        return null;
+    }
+
+    // NTLM2 LM/NTLM
+
+    static byte[] ntlm2LM(byte[] nonce) {
+        return Arrays.copyOf(nonce, 24);
+    }
+
+    byte[] ntlm2NTLM(byte[] ntlmHash, byte[] nonce, byte[] challenge) {
+        byte[] b = Arrays.copyOf(challenge, 16);
+        System.arraycopy(nonce, 0, b, 8, 8);
+        byte[] sesshash = Arrays.copyOf(md5.digest(b), 8);
+        return calcResponse(ntlmHash, sesshash);
+    }
+
+    // Password in ASCII and UNICODE
+
+    static byte[] getP1(char[] password) {
+        try {
+            return new String(password).toUpperCase().getBytes("ISO8859_1");
+        } catch (UnsupportedEncodingException ex) {
+            return null;
+        }
+    }
+
+    static byte[] getP2(char[] password) {
+        try {
+            return new String(password).getBytes("UnicodeLittleUnmarked");
+        } catch (UnsupportedEncodingException ex) {
+            return null;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/security/ntlm/NTLMException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.security.ntlm;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * An NTLM-related Exception
+ */
+public final class NTLMException extends GeneralSecurityException {
+
+    /**
+     * If the incoming packet is invalid.
+     */
+    public final static int PACKET_READ_ERROR = 1;
+
+    /**
+     * If the client cannot get a domain value from the server and the
+     * caller has not provided one.
+     */
+    public final static int NO_DOMAIN_INFO = 2;
+
+    /**
+     * If the domain provided by the client does not match the one received
+     * from server.
+     */
+    //public final static int DOMAIN_UNMATCH = 3;
+
+    /**
+     * If the client name is not found on server's user database.
+     */
+    public final static int USER_UNKNOWN = 3;
+
+    /**
+     * If authentication fails.
+     */
+    public final static int AUTH_FAILED = 4;
+
+    /**
+     * If an illegal version string is provided.
+     */
+    public final static int BAD_VERSION = 5;
+
+    private int errorCode;
+
+    /**
+     * Constructs an NTLMException object.
+     * @param errorCode the error code, which can be retrieved by
+     * the {@link #errorCode() } method.
+     * @param msg the string message, which can be retrived by
+     * the {@link Exception#getMessage() } method.
+     */
+    public NTLMException(int errorCode, String msg) {
+        super(msg);
+        this.errorCode = errorCode;
+    }
+
+    /**
+     * Returns the error code associated with this NTLMException.
+     * @return the error code
+     */
+    public int errorCode() {
+        return errorCode;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/security/ntlm/Server.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.security.ntlm;
+
+import java.util.Arrays;
+import java.util.Locale;
+
+/**
+ * The NTLM server, not multi-thread enabled.<p>
+ * Example:
+ * <pre>
+ * Server server = new Server(null, "REALM") {
+ *     public char[] getPassword(String ntdomain, String username) {
+ *         switch (username) {
+ *             case "dummy": return "t0pSeCr3t".toCharArray();
+ *             case "guest": return "".toCharArray();
+ *             default: return null;
+ *         }
+ *     }
+ * };
+ * // Receive client request as type1
+ * byte[] type2 = server.type2(type1, nonce);
+ * // Send type2 to client and receive type3
+ * verify(type3, nonce);
+ * </pre>
+ */
+public abstract class Server extends NTLM {
+    final private String domain;
+    final private boolean allVersion;
+    /**
+     * Creates a Server instance.
+     * @param version the NTLM version to use, which can be:
+     * <ul>
+     * <li>NTLM: Original NTLM v1
+     * <li>NTLM2: NTLM v1 with Client Challenge
+     * <li>NTLMv2: NTLM v2
+     * </ul>
+     * If null, all versions will be supported. Please note that unless NTLM2
+     * is selected, authentication succeeds if one of LM (or LMv2) or
+     * NTLM (or NTLMv2) is verified.
+     * @param domain the domain, must not be null
+     * @throws NullPointerException if {@code domain} is null.
+     */
+    public Server(String version, String domain) throws NTLMException {
+        super(version);
+        if (domain == null) {
+            throw new NullPointerException("domain cannot be null");
+        }
+        this.allVersion = (version == null);
+        this.domain = domain;
+        debug("NTLM Server: (t,version) = (%s,%s)\n", domain, version);
+    }
+
+    /**
+     * Generates the Type 2 message
+     * @param type1 the Type1 message received, must not be null
+     * @param nonce the random 8-byte array to be used in message generation,
+     * must not be null
+     * @return the message generated
+     * @throws NullPointerException if type1 or nonce is null
+     * @throws NTLMException if the incoming message is invalid
+     */
+    public byte[] type2(byte[] type1, byte[] nonce) {
+        if (nonce == null) {
+            throw new NullPointerException("nonce cannot be null");
+        }
+        debug("NTLM Server: Type 1 received\n");
+        if (type1 != null) debug(type1);
+        Writer p = new Writer(2, 32);
+        int flags = 0x80205;
+        p.writeSecurityBuffer(12, domain, true);
+        p.writeInt(20, flags);
+        p.writeBytes(24, nonce);
+        debug("NTLM Server: Type 2 created\n");
+        debug(p.getBytes());
+        return p.getBytes();
+    }
+
+    /**
+     * Verifies the Type3 message received from client and returns
+     * various negotiated information.
+     * @param type3 the incoming Type3 message from client, must not be null
+     * @param nonce the same nonce provided in {@link #type2}, must not be null
+     * @return username and hostname of the client in a byte array
+     * @throws NullPointerException if {@code type3} or {@code nonce} is null
+     * @throws NTLMException if the incoming message is invalid
+     */
+    public String[] verify(byte[] type3, byte[] nonce)
+            throws NTLMException {
+        if (type3 == null || nonce == null) {
+            throw new NullPointerException("type1 or nonce cannot be null");
+        }
+        debug("NTLM Server: Type 3 received\n");
+        if (type3 != null) debug(type3);
+        Reader r = new Reader(type3);
+        String username = r.readSecurityBuffer(36, true);
+        String hostname = r.readSecurityBuffer(44, true);
+        String incomingDomain = r.readSecurityBuffer(28, true);
+        /*if (incomingDomain != null && !incomingDomain.equals(domain)) {
+            throw new NTLMException(NTLMException.DOMAIN_UNMATCH,
+                    "Wrong domain: " + incomingDomain +
+                    " vs " + domain); // Needed?
+        }*/
+        boolean verified = false;
+        char[] password = getPassword(domain, username);
+        if (password == null) {
+            throw new NTLMException(NTLMException.USER_UNKNOWN,
+                    "Unknown user");
+        }
+        byte[] incomingLM = r.readSecurityBuffer(12);
+        byte[] incomingNTLM = r.readSecurityBuffer(20);
+
+        if (!verified && (allVersion || v == Version.NTLM)) {
+            if (incomingLM.length > 0) {
+                byte[] pw1 = getP1(password);
+                byte[] lmhash = calcLMHash(pw1);
+                byte[] lmresponse = calcResponse (lmhash, nonce);
+                if (Arrays.equals(lmresponse, incomingLM)) {
+                    verified = true;
+                }
+            }
+            if (incomingNTLM.length > 0) {
+                byte[] pw2 = getP2(password);
+                byte[] nthash = calcNTHash(pw2);
+                byte[] ntresponse = calcResponse (nthash, nonce);
+                if (Arrays.equals(ntresponse, incomingNTLM)) {
+                    verified = true;
+                }
+            }
+            debug("NTLM Server: verify using NTLM: " + verified  + "\n");
+        }
+        if (!verified && (allVersion || v == Version.NTLM2)) {
+            byte[] pw2 = getP2(password);
+            byte[] nthash = calcNTHash(pw2);
+            byte[] clientNonce = Arrays.copyOf(incomingLM, 8);
+            byte[] ntlmresponse = ntlm2NTLM(nthash, clientNonce, nonce);
+            if (Arrays.equals(incomingNTLM, ntlmresponse)) {
+                verified = true;
+            }
+            debug("NTLM Server: verify using NTLM2: " + verified + "\n");
+        }
+        if (!verified && (allVersion || v == Version.NTLMv2)) {
+            byte[] pw2 = getP2(password);
+            byte[] nthash = calcNTHash(pw2);
+            if (incomingLM.length > 0) {
+                byte[] clientNonce = Arrays.copyOfRange(
+                        incomingLM, 16, incomingLM.length);
+                byte[] lmresponse = calcV2(nthash,
+                        username.toUpperCase(Locale.US)+incomingDomain,
+                        clientNonce, nonce);
+                if (Arrays.equals(lmresponse, incomingLM)) {
+                    verified = true;
+                }
+            }
+            if (incomingNTLM.length > 0) {
+                byte[] clientBlob = Arrays.copyOfRange(
+                        incomingNTLM, 16, incomingNTLM.length);
+                byte[] ntlmresponse = calcV2(nthash,
+                        username.toUpperCase(Locale.US)+incomingDomain,
+                        clientBlob, nonce);
+                if (Arrays.equals(ntlmresponse, incomingNTLM)) {
+                    verified = true;
+                }
+            }
+            debug("NTLM Server: verify using NTLMv2: " + verified + "\n");
+        }
+        if (!verified) {
+            throw new NTLMException(NTLMException.AUTH_FAILED,
+                    "None of LM and NTLM verified");
+        }
+        return new String[] {username, hostname};
+    }
+
+    /**
+     * Retrieves the password for a given user. This method should be
+     * overridden in a concrete class.
+     * @param domain can be null
+     * @param username must not be null
+     * @return the password for the user, or null if unknown
+     */
+    public abstract char[] getPassword(String domain, String username);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/security/ntlm/Version.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.security.ntlm;
+
+enum Version {
+    NTLM, NTLM2, NTLMv2
+}
--- a/src/share/classes/com/sun/security/sasl/Provider.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/com/sun/security/sasl/Provider.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -35,10 +35,12 @@
  * - CRAM-MD5
  * - DIGEST-MD5
  * - GSSAPI/Kerberos v5
+ * - NTLM
  * And server support for
  * - CRAM-MD5
  * - DIGEST-MD5
  * - GSSAPI/Kerberos v5
+ * - NTLM
  */
 
 public final class Provider extends java.security.Provider {
@@ -47,8 +49,8 @@
 
     private static final String info = "Sun SASL provider" +
         "(implements client mechanisms for: " +
-        "DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5;" +
-        " server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5)";
+        "DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5, NTLM;" +
+        " server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5, NTLM)";
 
     public Provider() {
         super("SunSASL", 1.7d, info);
@@ -58,6 +60,8 @@
                 // Client mechanisms
                 put("SaslClientFactory.DIGEST-MD5",
                     "com.sun.security.sasl.digest.FactoryImpl");
+                put("SaslClientFactory.NTLM",
+                    "com.sun.security.sasl.ntlm.FactoryImpl");
                 put("SaslClientFactory.GSSAPI",
                     "com.sun.security.sasl.gsskerb.FactoryImpl");
 
@@ -75,6 +79,8 @@
                     "com.sun.security.sasl.gsskerb.FactoryImpl");
                 put("SaslServerFactory.DIGEST-MD5",
                     "com.sun.security.sasl.digest.FactoryImpl");
+                put("SaslServerFactory.NTLM",
+                    "com.sun.security.sasl.ntlm.FactoryImpl");
                 return null;
             }
         });
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/security/sasl/ntlm/FactoryImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.security.sasl.ntlm;
+
+import java.util.Map;
+
+import javax.security.sasl.*;
+import javax.security.auth.callback.CallbackHandler;
+
+import com.sun.security.sasl.util.PolicyUtils;
+
+
+/**
+  * Client and server factory for NTLM SASL client/server mechanisms.
+  * See NTLMClient and NTLMServer for input requirements.
+  *
+  * @since 1.7
+  */
+
+public final class FactoryImpl implements SaslClientFactory,
+SaslServerFactory{
+
+    private static final String myMechs[] = { "NTLM" };
+    private static final int mechPolicies[] = {
+            PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS
+    };
+
+    /**
+      * Empty constructor.
+      */
+    public FactoryImpl() {
+    }
+
+    /**
+     * Returns a new instance of the NTLM SASL client mechanism.
+     * Argument checks are performed in SaslClient's constructor.
+     * @returns a new SaslClient ; otherwise null if unsuccessful.
+     * @throws SaslException If there is an error creating the NTLM
+     * SASL client.
+     */
+    public SaslClient createSaslClient(String[] mechs,
+         String authorizationId, String protocol, String serverName,
+         Map<String,?> props, CallbackHandler cbh)
+         throws SaslException {
+
+         for (int i=0; i<mechs.length; i++) {
+            if (mechs[i].equals("NTLM") &&
+                    PolicyUtils.checkPolicy(mechPolicies[0], props)) {
+
+                return new NTLMClient(mechs[i], authorizationId,
+                    protocol, serverName, props, cbh);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns a new instance of the NTLM SASL server mechanism.
+     * Argument checks are performed in SaslServer's constructor.
+     * @returns a new SaslServer ; otherwise null if unsuccessful.
+     * @throws SaslException If there is an error creating the NTLM
+     * SASL server.
+     */
+    public SaslServer createSaslServer(String mech,
+         String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
+         throws SaslException {
+
+         if (mech.equals("NTLM") &&
+                 PolicyUtils.checkPolicy(mechPolicies[0], props)) {
+             if (props != null) {
+                 String qop = (String)props.get(Sasl.QOP);
+                 if (qop != null && !qop.equals("auth")) {
+                     throw new SaslException("NTLM only support auth");
+                 }
+             }
+             if (cbh == null) {
+                 throw new SaslException(
+                        "Callback handler with support for AuthorizeCallback, "+
+                        "RealmCallback, NameCallback, and PasswordCallback " +
+                        "required");
+             }
+             return new NTLMServer(mech, protocol, serverName, props, cbh);
+         }
+         return null;
+    }
+
+    /**
+      * Returns the authentication mechanisms that this factory can produce.
+      *
+      * @returns String[] {"NTLM"} if policies in env match those of this
+      * factory.
+      */
+    public String[] getMechanismNames(Map<String,?> env) {
+        return PolicyUtils.filterMechs(myMechs, mechPolicies, env);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/security/sasl/ntlm/NTLMClient.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.security.sasl.ntlm;
+
+import com.sun.security.ntlm.Client;
+import com.sun.security.ntlm.NTLMException;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Map;
+import java.util.Random;
+import javax.security.auth.callback.Callback;
+
+
+import javax.security.sasl.*;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+/**
+  * Required callbacks:
+  * - RealmCallback
+  *    handle can provide domain info for authentication, optional
+  * - NameCallback
+  *    handler must enter username to use for authentication
+  * - PasswordCallback
+  *    handler must enter password for username to use for authentication
+  *
+  * Environment properties that affect behavior of implementation:
+  *
+  * javax.security.sasl.qop
+  *    String, quality of protection; only "auth" is accepted, default "auth"
+  *
+  * com.sun.security.sasl.ntlm.version
+  *    String, name a specific version to use; can be:
+  *      LM/NTLM: Original NTLM v1
+  *      LM: Original NTLM v1, LM only
+  *      NTLM: Original NTLM v1, NTLM only
+  *      NTLM2: NTLM v1 with Client Challenge
+  *      LMv2/NTLMv2: NTLM v2
+  *      LMv2: NTLM v2, LM only
+  *      NTLMv2: NTLM v2, NTLM only
+  *    If not specified, use system property "ntlm.version". If
+  *    still not specified, use default value "LMv2/NTLMv2".
+  *
+  * com.sun.security.sasl.ntlm.random
+  *    java.util.Random, the nonce source to be used in NTLM v2 or NTLM v1 with
+  *    Client Challenge. Default null, an internal java.util.Random object
+  *    will be used
+  *
+  * Negotiated Properties:
+  *
+  * javax.security.sasl.qop
+  *    Always "auth"
+  *
+  * com.sun.security.sasl.html.domain
+  *    The domain for the user, provided by the server
+  *
+  * @see <a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>
+  * - Simple Authentication and Security Layer (SASL)
+  *
+  */
+final class NTLMClient implements SaslClient {
+
+    private static final String NTLM_VERSION =
+            "com.sun.security.sasl.ntlm.version";
+    private static final String NTLM_RANDOM =
+            "com.sun.security.sasl.ntlm.random";
+    private final static String NTLM_DOMAIN =
+            "com.sun.security.sasl.ntlm.domain";
+    private final static String NTLM_HOSTNAME =
+            "com.sun.security.sasl.ntlm.hostname";
+
+    private final Client client;
+    private final String mech;
+    private final Random random;
+
+    private int step = 0;   // 0-start,1-nego,2-auth,3-done
+
+    /**
+     * @param mech non-null
+     * @param authorizationId can be null or empty and ignored
+     * @param protocol non-null for Sasl, useless for NTLM
+     * @param serverName non-null for Sasl, but can be null for NTLM
+     * @param props can be null
+     * @param cbh can be null for Sasl, but will throw NPE for NTLM
+     * @throws SaslException
+     */
+    NTLMClient(String mech, String authzid, String protocol, String serverName,
+            Map props, CallbackHandler cbh) throws SaslException {
+
+        this.mech = mech;
+        String version = null;
+        Random rtmp = null;
+        String hostname = null;
+
+        if (props != null) {
+            String qop = (String)props.get(Sasl.QOP);
+            if (qop != null && !qop.equals("auth")) {
+                throw new SaslException("NTLM only support auth");
+            }
+            version = (String)props.get(NTLM_VERSION);
+            rtmp = (Random)props.get(NTLM_RANDOM);
+            hostname = (String)props.get(NTLM_HOSTNAME);
+        }
+        this.random = rtmp != null ? rtmp : new Random();
+
+        if (version == null) {
+            version = System.getProperty("ntlm.version");
+        }
+
+        RealmCallback dcb = (serverName != null && !serverName.isEmpty())?
+            new RealmCallback("Realm: ", serverName) :
+            new RealmCallback("Realm: ");
+        NameCallback ncb = (authzid != null && !authzid.isEmpty()) ?
+            new NameCallback("User name: ", authzid) :
+            new NameCallback("User name: ");
+        PasswordCallback pcb =
+            new PasswordCallback("Password: ", false);
+
+        try {
+            cbh.handle(new Callback[] {dcb, ncb, pcb});
+        } catch (UnsupportedCallbackException e) {
+            throw new SaslException("NTLM: Cannot perform callback to " +
+                "acquire realm, username or password", e);
+        } catch (IOException e) {
+            throw new SaslException(
+                "NTLM: Error acquiring realm, username or password", e);
+        }
+
+        if (hostname == null) {
+            try {
+                hostname = InetAddress.getLocalHost().getCanonicalHostName();
+            } catch (UnknownHostException e) {
+                hostname = "localhost";
+            }
+        }
+        try {
+            client = new Client(version, hostname,
+                    ncb.getName(),
+                    dcb.getText(),
+                    pcb.getPassword());
+        } catch (NTLMException ne) {
+            throw new SaslException(
+                    "NTLM: Invalid version string: " + version, ne);
+        }
+    }
+
+    @Override
+    public String getMechanismName() {
+        return mech;
+    }
+
+    @Override
+    public boolean isComplete() {
+        return step >= 2;
+    }
+
+    @Override
+    public byte[] unwrap(byte[] incoming, int offset, int len)
+            throws SaslException {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public byte[] wrap(byte[] outgoing, int offset, int len)
+            throws SaslException {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public Object getNegotiatedProperty(String propName) {
+        if (propName.equals(Sasl.QOP)) {
+            return "auth";
+        } else if (propName.equals(NTLM_DOMAIN)) {
+            return client.getDomain();
+        } else {
+            return null;
+        }
+    }
+
+    @Override
+    public void dispose() throws SaslException {
+        client.dispose();
+    }
+
+    @Override
+    public boolean hasInitialResponse() {
+        return true;
+    }
+
+    @Override
+    public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
+        step++;
+        if (step == 1) {
+            return client.type1();
+        } else {
+            try {
+                byte[] nonce = new byte[8];
+                random.nextBytes(nonce);
+                return client.type3(challenge, nonce);
+            } catch (NTLMException ex) {
+                throw new SaslException("Type3 creation failed", ex);
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/security/sasl/ntlm/NTLMServer.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.security.sasl.ntlm;
+
+import com.sun.security.ntlm.NTLMException;
+import com.sun.security.ntlm.Server;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.util.Map;
+import java.util.Random;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.sasl.*;
+
+/**
+  * Required callbacks:
+  * - RealmCallback
+  *      used as key by handler to fetch password, optional
+  * - NameCallback
+  *      used as key by handler to fetch password
+  * - PasswordCallback
+  *      handler must enter password for username/realm supplied
+  *
+  * Environment properties that affect the implementation:
+  *
+  * javax.security.sasl.qop
+  *    String, quality of protection; only "auth" is accepted, default "auth"
+  *
+  * com.sun.security.sasl.ntlm.version
+  *    String, name a specific version to accept:
+  *      LM/NTLM: Original NTLM v1
+  *      LM: Original NTLM v1, LM only
+  *      NTLM: Original NTLM v1, NTLM only
+  *      NTLM2: NTLM v1 with Client Challenge
+  *      LMv2/NTLMv2: NTLM v2
+  *      LMv2: NTLM v2, LM only
+  *      NTLMv2: NTLM v2, NTLM only
+  *    If not specified, use system property "ntlm.version". If also
+  *    not specfied, all versions are accepted.
+  *
+  * com.sun.security.sasl.ntlm.domain
+  *    String, the domain of the server, default is server name (fqdn parameter)
+  *
+  * com.sun.security.sasl.ntlm.random
+  *    java.util.Random, the nonce source. Default null, an internal
+  *    java.util.Random object will be used
+  *
+  * Negotiated Properties:
+  *
+  * javax.security.sasl.qop
+  *    Always "auth"
+  *
+  * com.sun.security.sasl.ntlm.hostname
+  *    The hostname for the user, provided by the client
+  *
+  */
+
+final class NTLMServer implements SaslServer {
+
+    private final static String NTLM_VERSION =
+            "com.sun.security.sasl.ntlm.version";
+    private final static String NTLM_DOMAIN =
+            "com.sun.security.sasl.ntlm.domain";
+    private final static String NTLM_HOSTNAME =
+            "com.sun.security.sasl.ntlm.hostname";
+    private static final String NTLM_RANDOM =
+            "com.sun.security.sasl.ntlm.random";
+
+    private final Random random;
+    private final Server server;
+    private byte[] nonce;
+    private int step = 0;
+    private String authzId;
+    private final String mech;
+    private String hostname;
+
+    /**
+     * @param mech not null
+     * @param protocol not null for Sasl, ignored in NTLM
+     * @param serverName not null for Sasl, can be null in NTLM. If non-null,
+     * might be used as domain if not provided in props
+     * @param props can be null
+     * @param cbh can be null for Sasl, but will throw NPE in auth for NTLM
+     * @throws SaslException
+     */
+    NTLMServer(String mech, String protocol, String serverName,
+            Map props, final CallbackHandler cbh) throws SaslException {
+
+        this.mech = mech;
+        String version = null;
+        String domain = null;
+        Random rtmp = null;
+
+        if (props != null) {
+            domain = (String) props.get(NTLM_DOMAIN);
+            version = (String)props.get(NTLM_VERSION);
+            rtmp = (Random)props.get(NTLM_RANDOM);
+        }
+        random = rtmp != null ? rtmp : new Random();
+
+        if (version == null) {
+            version = System.getProperty("ntlm.version");
+        }
+        if (domain == null) {
+            domain = serverName;
+        }
+        if (domain == null) {
+            throw new NullPointerException("Domain must be provided as"
+                    + " the serverName argument or in props");
+        }
+
+        try {
+            server = new Server(version, domain) {
+                public char[] getPassword(String ntdomain, String username) {
+                    try {
+                        RealmCallback rcb = new RealmCallback(
+                                "Domain: ", ntdomain);
+                        NameCallback ncb = new NameCallback(
+                                "Name: ", username);
+                        PasswordCallback pcb = new PasswordCallback(
+                                "Password: ", false);
+                        cbh.handle(new Callback[] { rcb, ncb, pcb });
+                        char[] passwd = pcb.getPassword();
+                        pcb.clearPassword();
+                        return passwd;
+                    } catch (IOException ioe) {
+                        return null;
+                    } catch (UnsupportedCallbackException uce) {
+                        return null;
+                    }
+                }
+            };
+        } catch (NTLMException ne) {
+            throw new SaslException(
+                    "NTLM: Invalid version string: " + version, ne);
+        }
+        nonce = new byte[8];
+    }
+
+    @Override
+    public String getMechanismName() {
+        return mech;
+    }
+
+    @Override
+    public byte[] evaluateResponse(byte[] response) throws SaslException {
+        try {
+            step++;
+            if (step == 1) {
+                random.nextBytes(nonce);
+                return server.type2(response, nonce);
+            } else {
+                String[] out = server.verify(response, nonce);
+                authzId = out[0];
+                hostname = out[1];
+                return null;
+            }
+        } catch (GeneralSecurityException ex) {
+            throw new SaslException("", ex);
+        }
+    }
+
+    @Override
+    public boolean isComplete() {
+        return step >= 2;
+    }
+
+    @Override
+    public String getAuthorizationID() {
+        return authzId;
+    }
+
+    @Override
+    public byte[] unwrap(byte[] incoming, int offset, int len)
+            throws SaslException {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public byte[] wrap(byte[] outgoing, int offset, int len)
+            throws SaslException {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public Object getNegotiatedProperty(String propName) {
+        if (propName.equals(Sasl.QOP)) {
+            return "auth";
+        } else if (propName.equals(NTLM_HOSTNAME)) {
+            return hostname;
+        } else {
+            return null;
+        }
+    }
+
+    @Override
+    public void dispose() throws SaslException {
+        return;
+    }
+}
--- a/src/share/classes/java/awt/Dialog.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/awt/Dialog.java	Fri Sep 24 16:41:32 2010 -0700
@@ -277,10 +277,8 @@
      */
     String title;
 
-    private transient volatile boolean keepBlockingEDT = false;
-    private transient volatile boolean keepBlockingCT = false;
-
     private transient ModalEventFilter modalFilter;
+    private transient volatile SecondaryLoop secondaryLoop;
 
     /*
      * Indicates that this dialog is being hidden. This flag is set to true at
@@ -1005,12 +1003,6 @@
         super.setVisible(b);
     }
 
-    /**
-    * Stores the app context on which event dispatch thread the dialog
-    * is being shown. Initialized in show(), used in hideAndDisposeHandler()
-    */
-    transient private AppContext showAppContext;
-
    /**
      * Makes the {@code Dialog} visible. If the dialog and/or its owner
      * are not yet displayable, both are made displayable.  The
@@ -1037,39 +1029,18 @@
         if (!isModal()) {
             conditionalShow(null, null);
         } else {
-            // Set this variable before calling conditionalShow(). That
-            // way, if the Dialog is hidden right after being shown, we
-            // won't mistakenly block this thread.
-            keepBlockingEDT = true;
-            keepBlockingCT = true;
-
-            // Store the app context on which this dialog is being shown.
-            // Event dispatch thread of this app context will be sleeping until
-            // we wake it by any event from hideAndDisposeHandler().
-            showAppContext = AppContext.getAppContext();
+            AppContext showAppContext = AppContext.getAppContext();
 
             AtomicLong time = new AtomicLong();
             Component predictedFocusOwner = null;
             try {
                 predictedFocusOwner = getMostRecentFocusOwner();
                 if (conditionalShow(predictedFocusOwner, time)) {
-                    // We have two mechanisms for blocking: 1. If we're on the
-                    // EventDispatchThread, start a new event pump. 2. If we're
-                    // on any other thread, call wait() on the treelock.
-
                     modalFilter = ModalEventFilter.createFilterForDialog(this);
-
-                    final Runnable pumpEventsForFilter = new Runnable() {
-                        public void run() {
-                            EventDispatchThread dispatchThread =
-                                (EventDispatchThread)Thread.currentThread();
-                            dispatchThread.pumpEventsForFilter(new Conditional() {
-                                public boolean evaluate() {
-                                    synchronized (getTreeLock()) {
-                                        return keepBlockingEDT && windowClosingException == null;
-                                    }
-                                }
-                            }, modalFilter);
+                    Conditional cond = new Conditional() {
+                        @Override
+                        public boolean evaluate() {
+                            return windowClosingException == null;
                         }
                     };
 
@@ -1096,44 +1067,10 @@
 
                     modalityPushed();
                     try {
-                        if (EventQueue.isDispatchThread()) {
-                            /*
-                             * dispose SequencedEvent we are dispatching on current
-                             * AppContext, to prevent us from hang.
-                             *
-                             */
-                            // BugId 4531693 (son@sparc.spb.su)
-                            SequencedEvent currentSequencedEvent = KeyboardFocusManager.
-                                getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
-                            if (currentSequencedEvent != null) {
-                                currentSequencedEvent.dispose();
-                            }
-
-                            /*
-                             * Event processing is done inside doPrivileged block so that
-                             * it wouldn't matter even if user code is on the stack
-                             * Fix for BugId 6300270
-                             */
-
-                             AccessController.doPrivileged(new PrivilegedAction() {
-                                     public Object run() {
-                                        pumpEventsForFilter.run();
-                                        return null;
-                                     }
-                             });
-                        } else {
-                            synchronized (getTreeLock()) {
-                                Toolkit.getEventQueue().postEvent(new PeerEvent(this,
-                                                                                pumpEventsForFilter,
-                                                                                PeerEvent.PRIORITY_EVENT));
-                                while (keepBlockingCT && windowClosingException == null) {
-                                    try {
-                                        getTreeLock().wait();
-                                    } catch (InterruptedException e) {
-                                        break;
-                                    }
-                                }
-                            }
+                        EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
+                        secondaryLoop = eventQueue.createSecondaryLoop(cond, modalFilter, 5000);
+                        if (!secondaryLoop.enter()) {
+                            secondaryLoop = null;
                         }
                     } finally {
                         modalityPopped();
@@ -1194,18 +1131,11 @@
             windowClosingException = null;
         }
     }
-    final class WakingRunnable implements Runnable {
-        public void run() {
-            synchronized (getTreeLock()) {
-                keepBlockingCT = false;
-                getTreeLock().notifyAll();
-            }
-        }
-    }
+
     private void hideAndDisposePreHandler() {
         isInHide = true;
         synchronized (getTreeLock()) {
-            if (keepBlockingEDT) {
+            if (secondaryLoop != null) {
                 modalHide();
                 // dialog can be shown and then disposed before its
                 // modal filter is created
@@ -1217,20 +1147,9 @@
         }
     }
     private void hideAndDisposeHandler() {
-        synchronized (getTreeLock()) {
-            if (keepBlockingEDT) {
-                keepBlockingEDT = false;
-                PeerEvent wakingEvent = new PeerEvent(getToolkit(), new WakingRunnable(), PeerEvent.PRIORITY_EVENT);
-                AppContext curAppContext = AppContext.getAppContext();
-                if (showAppContext != curAppContext) {
-                    // Wake up event dispatch thread on which the dialog was
-                    // initially shown
-                    SunToolkit.postEvent(showAppContext, wakingEvent);
-                    showAppContext = null;
-                } else {
-                    Toolkit.getEventQueue().postEvent(wakingEvent);
-                }
-            }
+        if (secondaryLoop != null) {
+            secondaryLoop.exit();
+            secondaryLoop = null;
         }
         isInHide = false;
     }
--- a/src/share/classes/java/awt/EventDispatchThread.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/awt/EventDispatchThread.java	Fri Sep 24 16:41:32 2010 -0700
@@ -113,8 +113,7 @@
         pumpEventsForHierarchy(id, cond, null);
     }
 
-    void pumpEventsForHierarchy(int id, Conditional cond, Component modalComponent)
-    {
+    void pumpEventsForHierarchy(int id, Conditional cond, Component modalComponent) {
         pumpEventsForFilter(id, cond, new HierarchyEventFilter(modalComponent));
     }
 
@@ -124,6 +123,7 @@
 
     void pumpEventsForFilter(int id, Conditional cond, EventFilter filter) {
         addEventFilter(filter);
+        doDispatch = true;
         while (doDispatch && cond.evaluate()) {
             if (isInterrupted() || !pumpOneEventForFilters(id)) {
                 doDispatch = false;
@@ -133,6 +133,7 @@
     }
 
     void addEventFilter(EventFilter filter) {
+        eventLog.finest("adding the event filter: " + filter);
         synchronized (eventFilters) {
             if (!eventFilters.contains(filter)) {
                 if (filter instanceof ModalEventFilter) {
@@ -156,6 +157,7 @@
     }
 
     void removeEventFilter(EventFilter filter) {
+        eventLog.finest("removing the event filter: " + filter);
         synchronized (eventFilters) {
             eventFilters.remove(filter);
         }
--- a/src/share/classes/java/awt/EventQueue.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/awt/EventQueue.java	Fri Sep 24 16:41:32 2010 -0700
@@ -884,6 +884,41 @@
     }
 
     /**
+     * Creates a new {@code secondary loop} associated with this
+     * event queue. Use the {@link SecondaryLoop#enter} and
+     * {@link SecondaryLoop#exit} methods to start and stop the
+     * event loop and dispatch the events from this queue.
+     *
+     * @return secondaryLoop A new secondary loop object, which can
+     *                       be used to launch a new nested event
+     *                       loop and dispatch events from this queue
+     *
+     * @see SecondaryLoop#enter
+     * @see SecondaryLoop#exit
+     *
+     * @since 1.7
+     */
+    public SecondaryLoop createSecondaryLoop() {
+        return createSecondaryLoop(null, null, 0);
+    }
+
+    SecondaryLoop createSecondaryLoop(Conditional cond, EventFilter filter, long interval) {
+        pushPopLock.lock();
+        try {
+            if (nextQueue != null) {
+                // Forward the request to the top of EventQueue stack
+                return nextQueue.createSecondaryLoop(cond, filter, interval);
+            }
+            if (dispatchThread == null) {
+                initDispatchThread();
+            }
+            return new WaitDispatchSupport(dispatchThread, cond, filter, interval);
+        } finally {
+            pushPopLock.unlock();
+        }
+    }
+
+    /**
      * Returns true if the calling thread is
      * {@link Toolkit#getSystemEventQueue the current AWT EventQueue}'s
      * dispatch thread. Use this method to ensure that a particular
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/awt/SecondaryLoop.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.awt;
+
+/**
+ * A helper interface to run the nested event loop.
+ * <p>
+ * Objects that implement this interface are created with the
+ * {@link EventQueue#createSecondaryLoop} method. The interface
+ * provides two methods, {@link enter} and {@link exit},
+ * which can be used to start and stop the event loop.
+ * <p>
+ * When the {@link enter} method is called, the current
+ * thread is blocked until the loop is terminated by the
+ * {@link exit} method. Also, a new event loop is started
+ * on the event dispatch thread, which may or may not be
+ * the current thread. The loop can be terminated on any
+ * thread by calling its {@link exit} method. After the
+ * loop is terminated, the {@code SecondaryLoop} object can
+ * be reused to run a new nested event loop.
+ * <p>
+ * A typical use case of applying this interface is AWT
+ * and Swing modal dialogs. When a modal dialog is shown on
+ * the event dispatch thread, it enters a new secondary loop.
+ * Later, when the dialog is hidden or disposed, it exits
+ * the loop, and the thread continues its execution.
+ * <p>
+ * The following example illustrates a simple use case of
+ * secondary loops:
+ *
+ * <pre>
+ *   SecondaryLoop loop;
+ *
+ *   JButton jButton = new JButton("Button");
+ *   jButton.addActionListener(new ActionListener() {
+ *       {@code @Override}
+ *       public void actionPerformed(ActionEvent e) {
+ *           Toolkit tk = Toolkit.getDefaultToolkit();
+ *           EventQueue eq = tk.getSystemEventQueue();
+ *           loop = eq.createSecondaryLoop();
+ *
+ *           // Spawn a new thread to do the work
+ *           Thread worker = new WorkerThread();
+ *           worker.start();
+ *
+ *           // Enter the loop to block the current event
+ *           // handler, but leave UI responsive
+ *           if (!loop.enter()) {
+ *               // Report an error
+ *           }
+ *       }
+ *   });
+ *
+ *   class WorkerThread extends Thread {
+ *       {@code @Override}
+ *       public void run() {
+ *           // Perform calculations
+ *           doSomethingUseful();
+ *
+ *           // Exit the loop
+ *           loop.exit();
+ *       }
+ *   }
+ * </pre>
+ *
+ * @see Dialog#show
+ * @see EventQueue#createSecondaryLoop
+ * @see Toolkit#getSystemEventQueue
+ *
+ * @author Anton Tarasov, Artem Ananiev
+ *
+ * @since 1.7
+ */
+public interface SecondaryLoop {
+
+    /**
+     * Blocks the execution of the current thread and enters a new
+     * secondary event loop on the event dispatch thread.
+     * <p>
+     * This method can be called by any thread including the event
+     * dispatch thread. This thread will be blocked until the {@link
+     * exit} method is called or the loop is terminated. A new
+     * secondary loop will be created on the event dispatch thread
+     * for dispatching events in either case.
+     * <p>
+     * This method can only start one new event loop at a time per
+     * object. If a secondary event loop has already been started
+     * by this object and is currently still running, this method
+     * returns {@code false} to indicate that it was not successful
+     * in starting a new event loop. Otherwise, this method blocks
+     * the calling thread and later returns {@code true} when the
+     * new event loop is terminated. At such time, this object can
+     * again be used to start another new event loop.
+     *
+     * @return {@code true} after termination of the secondary loop,
+     *         if the secondary loop was started by this call,
+     *         {@code false} otherwise
+     */
+    public boolean enter();
+
+    /**
+     * Unblocks the execution of the thread blocked by the {@link
+     * enter} method and exits the secondary loop.
+     * <p>
+     * This method resumes the thread that called the {@link enter}
+     * method and exits the secondary loop that was created when
+     * the {@link enter} method was invoked.
+     * <p>
+     * Note that if any other secondary loop is started while this
+     * loop is running, the blocked thread will not resume execution
+     * until the nested loop is terminated.
+     * <p>
+     * If this secondary loop has not been started with the {@link
+     * enter} method, or this secondary loop has already finished
+     * with the {@link exit} method, this method returns {@code
+     * false}, otherwise {@code true} is returned.
+     *
+     * @return {@code true} if this loop was previously started and
+     *         has not yet been finished with the {@link exit} method,
+     *         {@code false} otherwise
+     */
+    public boolean exit();
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/awt/WaitDispatchSupport.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,302 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.awt;
+
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import java.security.PrivilegedAction;
+import java.security.AccessController;
+
+import sun.awt.PeerEvent;
+
+import sun.util.logging.PlatformLogger;
+
+/**
+ * This utility class is used to suspend execution on a thread
+ * while still allowing {@code EventDispatchThread} to dispatch events.
+ * The API methods of the class are thread-safe.
+ *
+ * @author Anton Tarasov, Artem Ananiev
+ *
+ * @since 1.7
+ */
+class WaitDispatchSupport implements SecondaryLoop {
+
+    private final static PlatformLogger log =
+        PlatformLogger.getLogger("java.awt.event.WaitDispatchSupport");
+
+    private EventDispatchThread dispatchThread;
+    private EventFilter filter;
+
+    private volatile Conditional extCondition;
+    private volatile Conditional condition;
+
+    private long interval;
+    // Use a shared daemon timer to serve all the WaitDispatchSupports
+    private static Timer timer;
+    // When this WDS expires, we cancel the timer task leaving the
+    // shared timer up and running
+    private TimerTask timerTask;
+
+    private AtomicBoolean keepBlockingEDT = new AtomicBoolean(false);
+    private AtomicBoolean keepBlockingCT = new AtomicBoolean(false);
+
+    private static synchronized void initializeTimer() {
+        if (timer == null) {
+            timer = new Timer("AWT-WaitDispatchSupport-Timer", true);
+        }
+    }
+
+    /**
+     * Creates a {@code WaitDispatchSupport} instance to
+     * serve the given event dispatch thread.
+     *
+     * @param dispatchThread An event dispatch thread that
+     *        should not stop dispatching events while waiting
+     *
+     * @since 1.7
+     */
+    public WaitDispatchSupport(EventDispatchThread dispatchThread) {
+        this(dispatchThread, null);
+    }
+
+    /**
+     * Creates a {@code WaitDispatchSupport} instance to
+     * serve the given event dispatch thread.
+     *
+     * @param dispatchThread An event dispatch thread that
+     *        should not stop dispatching events while waiting
+     * @param extCondition A conditional object used to determine
+     *        if the loop should be terminated
+     *
+     * @since 1.7
+     */
+    public WaitDispatchSupport(EventDispatchThread dispatchThread,
+                               Conditional extCond)
+    {
+        if (dispatchThread == null) {
+            throw new IllegalArgumentException("The dispatchThread can not be null");
+        }
+
+        this.dispatchThread = dispatchThread;
+        this.extCondition = extCond;
+        this.condition = new Conditional() {
+            @Override
+            public boolean evaluate() {
+                if (log.isLoggable(PlatformLogger.FINEST)) {
+                    log.finest("evaluate(): blockingEDT=" + keepBlockingEDT.get() +
+                               ", blockingCT=" + keepBlockingCT.get());
+                }
+                boolean extEvaluate =
+                    (extCondition != null) ? extCondition.evaluate() : true;
+                if (!keepBlockingEDT.get() || !extEvaluate) {
+                    if (timerTask != null) {
+                        timerTask.cancel();
+                        timerTask = null;
+                    }
+                    return false;
+                }
+                return true;
+            }
+        };
+    }
+
+    /**
+     * Creates a {@code WaitDispatchSupport} instance to
+     * serve the given event dispatch thread.
+     * <p>
+     * The {@link EventFilter} is set on the {@code dispatchThread}
+     * while waiting. The filter is removed on completion of the
+     * waiting process.
+     * <p>
+     *
+     *
+     * @param dispatchThread An event dispatch thread that
+     *        should not stop dispatching events while waiting
+     * @param filter {@code EventFilter} to be set
+     * @param interval A time interval to wait for. Note that
+     *        when the waiting process takes place on EDT
+     *        there is no guarantee to stop it in the given time
+     *
+     * @since 1.7
+     */
+    public WaitDispatchSupport(EventDispatchThread dispatchThread,
+                               Conditional extCondition,
+                               EventFilter filter, long interval)
+    {
+        this(dispatchThread, extCondition);
+        this.filter = filter;
+        if (interval < 0) {
+            throw new IllegalArgumentException("The interval value must be >= 0");
+        }
+        this.interval = interval;
+        if (interval != 0) {
+            initializeTimer();
+        }
+    }
+
+    /**
+     * @inheritDoc
+     */
+    @Override
+    public boolean enter() {
+        log.fine("enter(): blockingEDT=" + keepBlockingEDT.get() +
+                 ", blockingCT=" + keepBlockingCT.get());
+
+        if (!keepBlockingEDT.compareAndSet(false, true)) {
+            log.fine("The secondary loop is already running, aborting");
+            return false;
+        }
+
+        final Runnable run = new Runnable() {
+            public void run() {
+                log.fine("Starting a new event pump");
+                if (filter == null) {
+                    dispatchThread.pumpEvents(condition);
+                } else {
+                    dispatchThread.pumpEventsForFilter(condition, filter);
+                }
+            }
+        };
+
+        // We have two mechanisms for blocking: if we're on the
+        // dispatch thread, start a new event pump; if we're
+        // on any other thread, call wait() on the treelock
+
+        Thread currentThread = Thread.currentThread();
+        if (currentThread == dispatchThread) {
+            log.finest("On dispatch thread: " + dispatchThread);
+            if (interval != 0) {
+                log.finest("scheduling the timer for " + interval + " ms");
+                timer.schedule(timerTask = new TimerTask() {
+                    @Override
+                    public void run() {
+                        if (keepBlockingEDT.compareAndSet(true, false)) {
+                            wakeupEDT();
+                        }
+                    }
+                }, interval);
+            }
+            // Dispose SequencedEvent we are dispatching on the the current
+            // AppContext, to prevent us from hang - see 4531693 for details
+            SequencedEvent currentSE = KeyboardFocusManager.
+                getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
+            if (currentSE != null) {
+                log.fine("Dispose current SequencedEvent: " + currentSE);
+                currentSE.dispose();
+            }
+            // In case the exit() method is called before starting
+            // new event pump it will post the waking event to EDT.
+            // The event will be handled after the the new event pump
+            // starts. Thus, the enter() method will not hang.
+            //
+            // Event pump should be privileged. See 6300270.
+            AccessController.doPrivileged(new PrivilegedAction() {
+                public Object run() {
+                    run.run();
+                    return null;
+                }
+            });
+        } else {
+            log.finest("On non-dispatch thread: " + currentThread);
+            synchronized (getTreeLock()) {
+                if (filter != null) {
+                    dispatchThread.addEventFilter(filter);
+                }
+                try {
+                    EventQueue eq = dispatchThread.getEventQueue();
+                    eq.postEvent(new PeerEvent(this, run, PeerEvent.PRIORITY_EVENT));
+                    keepBlockingCT.set(true);
+                    if (interval > 0) {
+                        long currTime = System.currentTimeMillis();
+                        while (keepBlockingCT.get() &&
+                               ((extCondition != null) ? extCondition.evaluate() : true) &&
+                               (currTime + interval > System.currentTimeMillis()))
+                        {
+                            getTreeLock().wait(interval);
+                        }
+                    } else {
+                        while (keepBlockingCT.get() &&
+                               ((extCondition != null) ? extCondition.evaluate() : true))
+                        {
+                            getTreeLock().wait();
+                        }
+                    }
+                    log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
+                } catch (InterruptedException e) {
+                    log.fine("Exception caught while waiting: " + e);
+                } finally {
+                    if (filter != null) {
+                        dispatchThread.removeEventFilter(filter);
+                    }
+                }
+                // If the waiting process has been stopped because of the
+                // time interval passed or an exception occurred, the state
+                // should be changed
+                keepBlockingEDT.set(false);
+                keepBlockingCT.set(false);
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * @inheritDoc
+     */
+    public boolean exit() {
+        log.fine("exit(): blockingEDT=" + keepBlockingEDT.get() +
+                 ", blockingCT=" + keepBlockingCT.get());
+        if (keepBlockingEDT.compareAndSet(true, false)) {
+            wakeupEDT();
+            return true;
+        }
+        return false;
+    }
+
+    private final static Object getTreeLock() {
+        return Component.LOCK;
+    }
+
+    private final Runnable wakingRunnable = new Runnable() {
+        public void run() {
+            log.fine("Wake up EDT");
+            synchronized (getTreeLock()) {
+                keepBlockingCT.set(false);
+                getTreeLock().notifyAll();
+            }
+            log.fine("Wake up EDT done");
+        }
+    };
+
+    private void wakeupEDT() {
+        log.finest("wakeupEDT(): EDT == " + dispatchThread);
+        EventQueue eq = dispatchThread.getEventQueue();
+        eq.postEvent(new PeerEvent(this, wakingRunnable, PeerEvent.PRIORITY_EVENT));
+    }
+}
--- a/src/share/classes/java/lang/AutoCloseable.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/lang/AutoCloseable.java	Fri Sep 24 16:41:32 2010 -0700
@@ -34,8 +34,8 @@
 public interface AutoCloseable {
     /**
      * Close this resource, relinquishing any underlying resources.
-     * This method is invoked automatically by the automatic resource
-     * management block construct.
+     * This method is invoked automatically by the {@code
+     * try}-with-resources statement.
      *
      * <p>Classes implementing this method are strongly encouraged to
      * be declared to throw more specific exceptions (or no exception
--- a/src/share/classes/java/lang/Character.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/lang/Character.java	Fri Sep 24 16:41:32 2010 -0700
@@ -595,7 +595,6 @@
         /**
          * Constructs a new <code>Subset</code> instance.
          *
-         * @exception NullPointerException if name is <code>null</code>
          * @param  name  The name of this subset
          * @exception NullPointerException if name is <code>null</code>
          */
--- a/src/share/classes/java/lang/ClassLoader.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/lang/ClassLoader.java	Fri Sep 24 16:41:32 2010 -0700
@@ -823,7 +823,7 @@
      * </tt></blockquote>
      *
      * @param  name
-     *         The expected <a href="#name">binary name</a. of the class, or
+     *         The expected <a href="#name">binary name</a>. of the class, or
      *         <tt>null</tt> if not known
      *
      * @param  b
--- a/src/share/classes/java/lang/Object.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/lang/Object.java	Fri Sep 24 16:41:32 2010 -0700
@@ -189,7 +189,9 @@
      * specific cloning operation. First, if the class of this object does
      * not implement the interface {@code Cloneable}, then a
      * {@code CloneNotSupportedException} is thrown. Note that all arrays
-     * are considered to implement the interface {@code Cloneable}.
+     * are considered to implement the interface {@code Cloneable} and that
+     * the return type of the {@code clone} method of an array type {@code T[]}
+     * is {@code T[]} where T is any reference or primitive type.
      * Otherwise, this method creates a new instance of the class of this
      * object and initializes all its fields with exactly the contents of
      * the corresponding fields of this object, as if by assignment; the
--- a/src/share/classes/java/lang/Throwable.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/lang/Throwable.java	Fri Sep 24 16:41:32 2010 -0700
@@ -498,8 +498,8 @@
      * }
      * </pre>
      * As of release 7, the platform supports the notion of
-     * <i>suppressed exceptions</i> (in conjunction with automatic
-     * resource management blocks). Any exceptions that were
+     * <i>suppressed exceptions</i> (in conjunction with the {@code
+     * try}-with-resources statement). Any exceptions that were
      * suppressed in order to deliver an exception are printed out
      * beneath the stack trace.  The format of this information
      * depends on the implementation, but the following example may be
@@ -805,7 +805,7 @@
 
     /**
      * Adds the specified exception to the list of exceptions that
-     * were suppressed, typically by the automatic resource management
+     * were suppressed, typically by the {@code try}-with-resources
      * statement, in order to deliver this exception.
      *
      * <p>Note that when one exception {@linkplain
@@ -839,7 +839,7 @@
 
     /**
      * Returns an array containing all of the exceptions that were
-     * suppressed, typically by the automatic resource management
+     * suppressed, typically by the {@code try}-with-resources
      * statement, in order to deliver this exception.
      *
      * @return an array containing all of the exceptions that were
--- a/src/share/classes/java/lang/reflect/Constructor.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/lang/reflect/Constructor.java	Fri Sep 24 16:41:32 2010 -0700
@@ -166,8 +166,7 @@
 
     /**
      * Returns the name of this constructor, as a string.  This is
-     * always the same as the simple name of the constructor's declaring
-     * class.
+     * the binary name of the constructor's declaring class.
      */
     public String getName() {
         return getDeclaringClass().getName();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/net/SdpSocketImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.net;
+
+import java.io.IOException;
+import java.io.FileDescriptor;
+
+import sun.net.sdp.SdpSupport;
+
+/**
+ * SocketImpl that supports the SDP protocol
+ */
+class SdpSocketImpl extends PlainSocketImpl {
+    SdpSocketImpl() { }
+
+    @Override
+    protected void create(boolean stream) throws IOException {
+        if (!stream)
+            throw new UnsupportedOperationException("Must be a stream socket");
+        fd = SdpSupport.createSocket();
+        if (socket != null)
+            socket.setCreated();
+        if (serverSocket != null)
+            serverSocket.setCreated();
+    }
+}
--- a/src/share/classes/java/net/ServerSocket.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/net/ServerSocket.java	Fri Sep 24 16:41:32 2010 -0700
@@ -69,6 +69,15 @@
     private boolean oldImpl = false;
 
     /**
+     * Package-private constructor to create a ServerSocket associated with
+     * the given SocketImpl.
+     */
+    ServerSocket(SocketImpl impl) {
+        this.impl = impl;
+        impl.setServerSocket(this);
+    }
+
+    /**
      * Creates an unbound server socket.
      *
      * @exception IOException IO error when opening the socket.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/nio/file/DirectoryIteratorException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.nio.file;
+
+import java.util.ConcurrentModificationException;
+import java.util.Objects;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.InvalidObjectException;
+
+/**
+ * Runtime exception thrown if an I/O error is encountered when iterating over
+ * the entries in a directory. The I/O error is retrieved as an {@link
+ * IOException} using the {@link #getCause() getCause()} method.
+ *
+ * @since 1.7
+ * @see DirectoryStream
+ */
+
+public final class DirectoryIteratorException
+    extends ConcurrentModificationException
+{
+    private static final long serialVersionUID = -6012699886086212874L;
+
+    /**
+     * Constructs an instance of this class.
+     *
+     * @param   cause
+     *          the {@code IOException} that caused the directory iteration
+     *          to fail
+     *
+     * @throws  NullPointerException
+     *          if the cause is {@code null}
+     */
+    public DirectoryIteratorException(IOException cause) {
+        super(Objects.nonNull(cause));
+    }
+
+    /**
+     * Returns the cause of this exception.
+     *
+     * @return  the cause
+     */
+    @Override
+    public IOException getCause() {
+        return (IOException)super.getCause();
+    }
+
+    /**
+     * Called to read the object from a stream.
+     *
+     * @throws  InvalidObjectException
+     *          if the object is invalid or has a cause that is not
+     *          an {@code IOException}
+     */
+    private void readObject(ObjectInputStream s)
+        throws IOException, ClassNotFoundException
+    {
+        s.defaultReadObject();
+        Throwable cause = super.getCause();
+        if (!(cause instanceof IOException))
+            throw new InvalidObjectException("Cause must be an IOException");
+    }
+}
--- a/src/share/classes/java/nio/file/DirectoryStream.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/nio/file/DirectoryStream.java	Fri Sep 24 16:41:32 2010 -0700
@@ -31,60 +31,84 @@
 
 /**
  * An object to iterate over the entries in a directory. A directory stream
- * allows for convenient use of the for-each construct:
+ * allows for the convenient use of the for-each construct to iterate over a
+ * directory.
+ *
+ * <p> <b> While {@code DirectoryStream} extends {@code Iterable}, it is not a
+ * general-purpose {@code Iterable} as it supports only a single {@code
+ * Iterator}; invoking the {@link #iterator iterator} method to obtain a second
+ * or subsequent iterator throws {@code IllegalStateException}. </b>
+ *
+ * <p> An important property of the directory stream's {@code Iterator} is that
+ * its {@link Iterator#hasNext() hasNext} method is guaranteed to read-ahead by
+ * at least one element. If {@code hasNext} method returns {@code true}, and is
+ * followed by a call to the {@code next} method, it is guaranteed that the
+ * {@code next} method will not throw an exception due to an I/O error, or
+ * because the stream has been {@link #close closed}. The {@code Iterator} does
+ * not support the {@link Iterator#remove remove} operation.
+ *
+ * <p> A {@code DirectoryStream} is opened upon creation and is closed by
+ * invoking the {@code close} method. Closing a directory stream releases any
+ * resources associated with the stream. Failure to close the stream may result
+ * in a resource leak. The try-with-resources statement provides a useful
+ * construct to ensure that the stream is closed:
  * <pre>
  *   Path dir = ...
- *   DirectoryStream&lt;Path&gt; stream = dir.newDirectoryStream();
- *   try {
+ *   try (DirectoryStream&lt;Path&gt; stream = dir.newDirectoryStream()) {
  *       for (Path entry: stream) {
- *         ..
+ *           ...
  *       }
- *   } finally {
- *       stream.close();
  *   }
  * </pre>
  *
- * <p><b> A {@code DirectoryStream} is not a general-purpose {@code Iterable}.
- * While this interface extends {@code Iterable}, the {@code iterator} method
- * may only be invoked once to obtain the iterator; a second, or subsequent,
- * call to the {@code iterator} method throws {@code IllegalStateException}. </b>
- *
- * <p> A {@code DirectoryStream} is opened upon creation and is closed by
- * invoking the {@link #close close} method. Closing the directory stream
- * releases any resources associated with the stream. Once a directory stream
- * is closed, all further method invocations on the iterator throw {@link
- * java.util.ConcurrentModificationException} with cause {@link
- * ClosedDirectoryStreamException}.
+ * <p> Once a directory stream is closed, then further access to the directory,
+ * using the {@code Iterator}, behaves as if the end of stream has been reached.
+ * Due to read-ahead, the {@code Iterator} may return one or more elements
+ * after the directory stream has been closed. Once these buffered elements
+ * have been read, then subsequent calls to the {@code hasNext} method returns
+ * {@code false}, and subsequent calls to the {@code next} method will throw
+ * {@code NoSuchElementException}.
  *
  * <p> A directory stream is not required to be <i>asynchronously closeable</i>.
  * If a thread is blocked on the directory stream's iterator reading from the
  * directory, and another thread invokes the {@code close} method, then the
  * second thread may block until the read operation is complete.
  *
- * <p> The {@link Iterator#hasNext() hasNext} and {@link Iterator#next() next}
- * methods can encounter an I/O error when iterating over the directory in which
- * case {@code ConcurrentModificationException} is thrown with cause
- * {@link java.io.IOException}. The {@code hasNext} method is guaranteed to
- * read-ahead by at least one element. This means that if the {@code hasNext}
- * method returns {@code true} and is followed by a call to the {@code next}
- * method then it is guaranteed not to fail with a {@code
- * ConcurrentModificationException}.
+ * <p> If an I/O error is encountered when accessing the directory then it
+ * causes the {@code Iterator}'s {@code hasNext} or {@code next} methods to
+ * throw {@link DirectoryIteratorException} with the {@link IOException} as the
+ * cause. As stated above, the {@code hasNext} method is guaranteed to
+ * read-ahead by at least one element. This means that if {@code hasNext} method
+ * returns {@code true}, and is followed by a call to the {@code next} method,
+ * then it is guaranteed that the {@code next} method will not fail with a
+ * {@code DirectoryIteratorException}.
  *
  * <p> The elements returned by the iterator are in no specific order. Some file
  * systems maintain special links to the directory itself and the directory's
  * parent directory. Entries representing these links are not returned by the
  * iterator.
  *
- * <p> The iterator's {@link Iterator#remove() remove} method removes the
- * directory entry for the last element returned by the iterator, as if by
- * invoking the {@link Path#delete delete} method. If an I/O error or
- * security exception occurs then {@code ConcurrentModificationException} is
- * thrown with the cause.
- *
  * <p> The iterator is <i>weakly consistent</i>. It is thread safe but does not
  * freeze the directory while iterating, so it may (or may not) reflect updates
  * to the directory that occur after the {@code DirectoryStream} is created.
  *
+ * <p> <b>Usage Examples:</b>
+ * Suppose we want a list of the source files in a directory. This example uses
+ * both the for-each and try-with-resources constructs.
+ * <pre>
+ *   List&lt;Path&gt; listSourceFiles(Path dir) throws IOException {
+ *       List&lt;Path&gt; result = new ArrayList&lt;Path&gt;();
+ *       try (DirectoryStream&lt;Path&gt; stream = dir.newDirectoryStream("*.{c,h,cpp,hpp,java}")) {
+ *           for (Path entry: stream) {
+ *               result.add(entry);
+ *           }
+ *       } catch (DirectoryIteratorException ex) {
+ *           // I/O error encounted during the iteration, the cause is an IOException
+ *           throw ex.getCause();
+ *       }
+ *       return result;
+ *   }
+ * </pre>
  * @param   <T>     The type of element returned by the iterator
  *
  * @since 1.7
--- a/src/share/classes/java/nio/file/Path.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/nio/file/Path.java	Fri Sep 24 16:41:32 2010 -0700
@@ -984,11 +984,11 @@
      * directory.
      *
      * <p> Where the filter terminates due to an uncaught error or runtime
-     * exception then it is propogated to the iterator's {@link Iterator#hasNext()
+     * exception then it is propagated to the {@link Iterator#hasNext()
      * hasNext} or {@link Iterator#next() next} method. Where an {@code
-     * IOException} is thrown, it is propogated as a {@link
-     * java.util.ConcurrentModificationException} with the {@code
-     * IOException} as the cause.
+     * IOException} is thrown, it results in the {@code hasNext} or {@code
+     * next} method throwing a {@link DirectoryIteratorException} with the
+     * {@code IOException} as the cause.
      *
      * <p> When an implementation supports operations on entries in the
      * directory that execute in a race-free manner then the returned directory
--- a/src/share/classes/java/nio/file/SecureDirectoryStream.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/nio/file/SecureDirectoryStream.java	Fri Sep 24 16:41:32 2010 -0700
@@ -47,15 +47,6 @@
  * newDirectoryStream} method will be a {@code SecureDirectoryStream} and must
  * be cast to that type in order to invoke the methods defined by this interface.
  *
- * <p> As specified by {@code DirectoryStream}, the iterator's {@link
- * java.util.Iterator#remove() remove} method removes the directory entry for
- * the last element returned by the iterator. In the case of a {@code
- * SecureDirectoryStream} the {@code remove} method behaves as if by invoking
- * the {@link #deleteFile deleteFile} or {@link #deleteDirectory deleteDirectory}
- * methods defined by this interface. The {@code remove} may require to examine
- * the file to determine if the file is a directory, and consequently, it may
- * not be atomic with respect to other file system operations.
- *
  * <p> In the case of the default {@link java.nio.file.spi.FileSystemProvider
  * provider}, and a security manager is set, then the permission checks are
  * performed using the path obtained by resolving the given relative path
--- a/src/share/classes/java/sql/CallableStatement.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/CallableStatement.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -2436,4 +2436,64 @@
      */
      void setNClob(String parameterName, Reader reader)
        throws SQLException;
+
+    //------------------------- JDBC 4.1 -----------------------------------
+
+
+    /**
+     *<p>Returns an object representing the value of OUT parameter
+     * {@code parameterIndex} and will convert from the
+     * SQL type of the parameter to the requested Java data type, if the
+     * conversion is supported. If the conversion is not
+     * supported or null is specified for the type, a
+     * <code>SQLException</code> is thrown.
+     *<p>
+     * At a minimum, an implementation must support the conversions defined in
+     * Appendix B, Table B-3 and conversion of appropriate user defined SQL
+     * types to a Java type which implements {@code SQLData}, or {@code Struct}.
+     * Additional conversions may be supported and are vendor defined.
+     *
+     * @param parameterIndex the first parameter is 1, the second is 2, and so on
+     * @param type Class representing the Java data type to convert the
+     * designated parameter to.
+     * @return an instance of {@code type} holding the OUT parameter value
+     * @throws SQLException if conversion is not supported, type is null or
+     *         another error occurs. The getCause() method of the
+     * exception may provide a more detailed exception, for example, if
+     * a conversion error occurs
+     * @throws SQLFeatureNotSupportedException if the JDBC driver does not support
+     * this method
+     * @since 1.7
+     */
+     public <T> T getObject(int parameterIndex, Class<T> type) throws SQLException;
+
+
+    /**
+     *<p>Returns an object representing the value of OUT parameter
+     * {@code parameterName} and will convert from the
+     * SQL type of the parameter to the requested Java data type, if the
+     * conversion is supported. If the conversion is not
+     * supported  or null is specified for the type, a
+     * <code>SQLException</code> is thrown.
+     *<p>
+     * At a minimum, an implementation must support the conversions defined in
+     * Appendix B, Table B-3 and conversion of appropriate user defined SQL
+     * types to a Java type which implements {@code SQLData}, or {@code Struct}.
+     * Additional conversions may be supported and are vendor defined.
+     *
+     * @param parameterName the name of the parameter
+     * @param type Class representing the Java data type to convert
+     * the designated parameter to.
+     * @return an instance of {@code type} holding the OUT parameter
+     * value
+     * @throws SQLException if conversion is not supported, type is null or
+     *         another error occurs. The getCause() method of the
+     * exception may provide a more detailed exception, for example, if
+     * a conversion error occurs
+     * @throws SQLFeatureNotSupportedException if the JDBC driver does not support
+     * this method
+     * @since 1.7
+     */
+     public <T> T getObject(String parameterName, Class<T> type) throws SQLException;
+
 }
--- a/src/share/classes/java/sql/Connection.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/Connection.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -26,6 +26,7 @@
 package java.sql;
 
 import java.util.Properties;
+import java.util.concurrent.Executor;
 
 /**
  * <P>A connection (session) with a specific
@@ -38,7 +39,7 @@
  * information is obtained with the <code>getMetaData</code> method.
  *
  * <P><B>Note:</B> When configuring a <code>Connection</code>, JDBC applications
- *  should use the appropritate <code>Connection</code> method such as
+ *  should use the appropriate <code>Connection</code> method such as
  *  <code>setAutoCommit</code> or <code>setTransactionIsolation</code>.
  *  Applications should not invoke SQL commands directly to change the connection's
  *   configuration when there is a JDBC method available.  By default a <code>Connection</code> object is in
@@ -80,7 +81,7 @@
  * @see ResultSet
  * @see DatabaseMetaData
  */
-public interface Connection  extends Wrapper {
+public interface Connection  extends Wrapper, AutoCloseable {
 
     /**
      * Creates a <code>Statement</code> object for sending
@@ -347,6 +348,13 @@
      * <P>
      * If the driver does not support catalogs, it will
      * silently ignore this request.
+     * <p>
+     * Calling {@code setCatalog} has no effect on previously created or prepared
+     * {@code Statement} objects. It is implementation defined whether a DBMS
+     * prepare operation takes place immediately when the {@code Connection}
+     * method {@code prepareStatement} or {@code prepareCall} is invoked.
+     * For maximum portability, {@code setCatalog} should be called before a
+     * {@code Statement} is created or prepared.
      *
      * @param catalog the name of a catalog (subspace in this
      *        <code>Connection</code> object's database) in which to work
@@ -598,7 +606,17 @@
      * <code>Connection</code> object.
      * Unless the application has added an entry, the type map returned
      * will be empty.
-     *
+     * <p>
+     * You must invoke <code>setTypeMap</code> after making changes to the
+     * <code>Map</code> object returned from
+     *  <code>getTypeMap</code> as a JDBC driver may create an internal
+     * copy of the <code>Map</code> object passed to <code>setTypeMap</code>:
+     * <p>
+     * <pre>
+     *      Map&lt;String,Class&lt;?&gt;&gt; myMap = con.getTypeMap();
+     *      myMap.put("mySchemaName.ATHLETES", Athletes.class);
+     *      con.setTypeMap(myMap);
+     * </pre>
      * @return the <code>java.util.Map</code> object associated
      *         with this <code>Connection</code> object
      * @exception SQLException if a database access error occurs
@@ -614,7 +632,16 @@
      * Installs the given <code>TypeMap</code> object as the type map for
      * this <code>Connection</code> object.  The type map will be used for the
      * custom mapping of SQL structured types and distinct types.
-     *
+     *<p>
+     * You must set the the values for the <code>TypeMap</code> prior to
+     * callng <code>setMap</code> as a JDBC driver may create an internal copy
+     * of the <code>TypeMap</code>:
+     * <p>
+     * <pre>
+     *      Map myMap&lt;String,Class&lt;?&gt;&gt; = new HashMap&lt;String,Class&lt;?&gt;&gt;();
+     *      myMap.put("mySchemaName.ATHLETES", Athletes.class);
+     *      con.setTypeMap(myMap);
+     * </pre>
      * @param map the <code>java.util.Map</code> object to install
      *        as the replacement for this <code>Connection</code>
      *        object's default type map
@@ -1274,4 +1301,186 @@
   */
  Struct createStruct(String typeName, Object[] attributes)
 throws SQLException;
+
+   //--------------------------JDBC 4.1 -----------------------------
+
+   /**
+    * Sets the given schema name to access.
+    * <P>
+    * If the driver does not support schemas, it will
+    * silently ignore this request.
+    * <p>
+    * Calling {@code setSchema} has no effect on previously created or prepared
+    * {@code Statement} objects. It is implementation defined whether a DBMS
+    * prepare operation takes place immediately when the {@code Connection}
+    * method {@code prepareStatement} or {@code prepareCall} is invoked.
+    * For maximum portability, {@code setSchema} should be called before a
+    * {@code Statement} is created or prepared.
+    *
+    * @param schema the name of a schema  in which to work
+    * @exception SQLException if a database access error occurs
+    * or this method is called on a closed connection
+    * @see #getSchema
+    * @since 1.7
+    */
+    void setSchema(String schema) throws SQLException;
+
+    /**
+     * Retrieves this <code>Connection</code> object's current schema name.
+     *
+     * @return the current schema name or <code>null</code> if there is none
+     * @exception SQLException if a database access error occurs
+     * or this method is called on a closed connection
+     * @see #setSchema
+     * @since 1.7
+     */
+    String getSchema() throws SQLException;
+
+    /**
+     * Terminates an open connection.  Calling <code>abort</code> results in:
+     * <ul>
+     * <li>The connection marked as closed
+     * <li>Closes any physical connection to the database
+     * <li>Releases resources used by the connection
+     * <li>Insures that any thread that is currently accessing the connection
+     * will either progress to completion or throw an <code>SQLException</code>.
+     * </ul>
+     * <p>
+     * Calling <code>abort</code> marks the connection closed and releases any
+     * resources. Calling <code>abort</code> on a closed connection is a
+     * no-op.
+     * <p>
+     * It is possible that the aborting and releasing of the resources that are
+     * held by the connection can take an extended period of time.  When the
+     * <code>abort</code> method returns, the connection will have been marked as
+     * closed and the <code>Executor</code> that was passed as a parameter to abort
+     * may still be executing tasks to release resources.
+     * <p>
+     * This method checks to see that there is an <code>SQLPermission</code>
+     * object before allowing the method to proceed.  If a
+     * <code>SecurityManager</code> exists and its
+     * <code>checkPermission</code> method denies calling <code>abort</code>,
+     * this method throws a
+     * <code>java.lang.SecurityException</code>.
+     * @param executor  The <code>Executor</code>  implementation which will
+     * be used by <code>abort</code>.
+     * @throws java.sql.SQLException if a database access error occurs or
+     * the {@code executor} is {@code null},
+     * @throws java.lang.SecurityException if a security manager exists and its
+     *    <code>checkPermission</code> method denies calling <code>abort</code>
+     * @see SecurityManager#checkPermission
+     * @see Executor
+     * @since 1.7
+     */
+    void abort(Executor executor) throws SQLException;
+
+    /**
+     *
+     * Sets the maximum period a <code>Connection</code> or
+     * objects created from the <code>Connection</code>
+     * will wait for the database to reply to any one request. If any
+     *  request remains unanswered, the waiting method will
+     * return with a <code>SQLException</code>, and the <code>Connection</code>
+     * or objects created from the <code>Connection</code>  will be marked as
+     * closed. Any subsequent use of
+     * the objects, with the exception of the <code>close</code>,
+     * <code>isClosed</code> or <code>Connection.isValid</code>
+     * methods, will result in  a <code>SQLException</code>.
+     * <p>
+     * <b>Note</b>: This method is intended to address a rare but serious
+     * condition where network partitions can cause threads issuing JDBC calls
+     * to hang uninterruptedly in socket reads, until the OS TCP-TIMEOUT
+     * (typically 10 minutes). This method is related to the
+     * {@link #abort abort() } method which provides an administrator
+     * thread a means to free any such threads in cases where the
+     * JDBC connection is accessible to the administrator thread.
+     * The <code>setNetworkTimeout</code> method will cover cases where
+     * there is no administrator thread, or it has no access to the
+     * connection. This method is severe in it's effects, and should be
+     * given a high enough value so it is never triggered before any more
+     * normal timeouts, such as transaction timeouts.
+     * <p>
+     * JDBC driver implementations  may also choose to support the
+     * {@code setNetworkTimeout} method to impose a limit on database
+     * response time, in environments where no network is present.
+     * <p>
+     * Drivers may internally implement some or all of their API calls with
+     * multiple internal driver-database transmissions, and it is left to the
+     * driver implementation to determine whether the limit will be
+     * applied always to the response to the API call, or to any
+     * single  request made during the API call.
+     * <p>
+     *
+     * This method can be invoked more than once, such as to set a limit for an
+     * area of JDBC code, and to reset to the default on exit from this area.
+     * Invocation of this method has no impact on already outstanding
+     * requests.
+     * <p>
+     * The {@code Statement.setQueryTimeout()} timeout value is independent of the
+     * timeout value specified in {@code setNetworkTimeout}. If the query timeout
+     * expires  before the network timeout then the
+     * statement execution will be canceled. If the network is still
+     * active the result will be that both the statement and connection
+     * are still usable. However if the network timeout expires before
+     * the query timeout or if the statement timeout fails due to network
+     * problems, the connection will be marked as closed, any resources held by
+     * the connection will be released and both the connection and
+     * statement will be unusable.
+     *<p>
+     * When the driver determines that the {@code setNetworkTimeout} timeout
+     * value has expired, the JDBC driver marks the connection
+     * closed and releases any resources held by the connection.
+     * <p>
+     *
+     * This method checks to see that there is an <code>SQLPermission</code>
+     * object before allowing the method to proceed.  If a
+     * <code>SecurityManager</code> exists and its
+     * <code>checkPermission</code> method denies calling
+     * <code>setNetworkTimeout</code>, this method throws a
+     * <code>java.lang.SecurityException</code>.
+     *
+     * @param executor  The <code>Executor</code>  implementation which will
+     * be used by <code>setNetworkTimeout</code>.
+     * @param milliseconds The time in milliseconds to wait for the database
+     * operation
+     *  to complete.  If the JDBC driver does not support milliseconds, the
+     * JDBC driver will round the value up to the nearest second.  If the
+     * timeout period expires before the operation
+     * completes, a SQLException will be thrown.
+     * A value of 0 indicates that there is not timeout for database operations.
+     * @throws java.sql.SQLException if a database access error occurs, this
+     * method is called on a closed connection,
+     * the {@code executor} is {@code null},
+     * or the value specified for <code>seconds</code> is less than 0.
+     * @throws java.lang.SecurityException if a security manager exists and its
+     *    <code>checkPermission</code> method denies calling
+     * <code>setNetworkTimeout</code>.
+     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+     * this method
+     * @see SecurityManager#checkPermission
+     * @see Statement#setQueryTimeout
+     * @see #getNetworkTimeout
+     * @see #abort
+     * @see Executor
+     * @since 1.7
+     */
+    void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException;
+
+
+    /**
+     * Retrieves the number of milliseconds the driver will
+     * wait for a database request to complete.
+     * If the limit is exceeded, a
+     * <code>SQLException</code> is thrown.
+     *
+     * @return the current timeout limit in milliseconds; zero means there is
+     *         no limit
+     * @throws SQLException if a database access error occurs or
+     * this method is called on a closed <code>Connection</code>
+     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+     * this method
+     * @see #setNetworkTimeout
+     * @since 1.7
+     */
+    int getNetworkTimeout() throws SQLException;
 }
--- a/src/share/classes/java/sql/DatabaseMetaData.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/DatabaseMetaData.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -1342,10 +1342,10 @@
      * defined.
      *  <LI><B>IS_NULLABLE</B> String  => ISO rules are used to determine the nullability for a column.
      *       <UL>
-     *       <LI> YES           --- if the parameter can include NULLs
-     *       <LI> NO            --- if the parameter cannot include NULLs
+     *       <LI> YES           --- if the column can include NULLs
+     *       <LI> NO            --- if the column cannot include NULLs
      *       <LI> empty string  --- if the nullability for the
-     * parameter is unknown
+     * column is unknown
      *       </UL>
      *  <LI><B>SPECIFIC_NAME</B> String  => the name which uniquely identifies this procedure within its schema.
      *  </OL>
@@ -1610,17 +1610,17 @@
      *      (starting at 1)
      *  <LI><B>IS_NULLABLE</B> String  => ISO rules are used to determine the nullability for a column.
      *       <UL>
-     *       <LI> YES           --- if the parameter can include NULLs
-     *       <LI> NO            --- if the parameter cannot include NULLs
+     *       <LI> YES           --- if the column can include NULLs
+     *       <LI> NO            --- if the column cannot include NULLs
      *       <LI> empty string  --- if the nullability for the
-     * parameter is unknown
+     * column is unknown
      *       </UL>
-     *  <LI><B>SCOPE_CATLOG</B> String => catalog of table that is the scope
+     *  <LI><B>SCOPE_CATALOG</B> String => catalog of table that is the scope
      *      of a reference attribute (<code>null</code> if DATA_TYPE isn't REF)
      *  <LI><B>SCOPE_SCHEMA</B> String => schema of table that is the scope
      *      of a reference attribute (<code>null</code> if the DATA_TYPE isn't REF)
      *  <LI><B>SCOPE_TABLE</B> String => table name that this the scope
-     *      of a reference attribure (<code>null</code> if the DATA_TYPE isn't REF)
+     *      of a reference attribute (<code>null</code> if the DATA_TYPE isn't REF)
      *  <LI><B>SOURCE_DATA_TYPE</B> short => source type of a distinct type or user-generated
      *      Ref type, SQL type from java.sql.Types (<code>null</code> if DATA_TYPE
      *      isn't DISTINCT or user-generated REF)
@@ -1629,11 +1629,16 @@
      *       <LI> YES           --- if the column is auto incremented
      *       <LI> NO            --- if the column is not auto incremented
      *       <LI> empty string  --- if it cannot be determined whether the column is auto incremented
-     * parameter is unknown
+     *       </UL>
+     *   <LI><B>IS_GENERATEDCOLUMN</B> String  => Indicates whether this is a generated column
+     *       <UL>
+     *       <LI> YES           --- if this a generated column
+     *       <LI> NO            --- if this not a generated column
+     *       <LI> empty string  --- if it cannot be determined whether this is a generated column
      *       </UL>
      *  </OL>
      *
-     * <p>The COLUMN_SIZE column the specified column size for the given column.
+     * <p>The COLUMN_SIZE column specifies the column size for the given column.
      * For numeric data, this is the maximum precision.  For character data, this is the length in characters.
      * For datetime datatypes, this is the length in characters of the String representation (assuming the
      * maximum allowed precision of the fractional seconds component). For binary data, this is the length in bytes.  For the ROWID datatype,
@@ -3186,7 +3191,7 @@
      * Retrieves whether this database supports statement pooling.
      *
      * @return <code>true</code> if so; <code>false</code> otherwise
-     * @throws SQLExcpetion if a database access error occurs
+     * @throws SQLException if a database access error occurs
      * @since 1.4
      */
     boolean supportsStatementPooling() throws SQLException;
@@ -3568,4 +3573,83 @@
      */
     int functionReturnsTable    = 2;
 
+    //--------------------------JDBC 4.1 -----------------------------
+
+    /**
+     * Retrieves a description of the pseudo or hidden columns available
+     * in a given table within the specified catalog and schema.
+     * Pseudo or hidden columns may not always be stored within
+     * a table and are not visible in a ResultSet unless they are
+     * specified in the query's outermost SELECT list. Pseudo or hidden
+     * columns may not necessarily be able to be modified. If there are
+     * no pseudo or hidden columns, an empty ResultSet is returned.
+     *
+     * <P>Only column descriptions matching the catalog, schema, table
+     * and column name criteria are returned.  They are ordered by
+     * <code>TABLE_CAT</code>,<code>TABLE_SCHEM</code>, <code>TABLE_NAME</code>
+     * and <code>COLUMN_NAME</code>.
+     *
+     * <P>Each column description has the following columns:
+     *  <OL>
+     *  <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String => table name
+     *  <LI><B>COLUMN_NAME</B> String => column name
+     *  <LI><B>DATA_TYPE</B> int => SQL type from java.sql.Types
+     *  <LI><B>COLUMN_SIZE</B> int => column size.
+     *  <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits. Null is returned for data types where
+     * DECIMAL_DIGITS is not applicable.
+     *  <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2)
+     *  <LI><B>COLUMN_USAGE</B> String => The allowed usage for the column.  The
+     *  value returned will correspond to the enum name returned by {@link PseudoColumnUsage#name PseudoColumnUsage.name()}
+     *  <LI><B>REMARKS</B> String => comment describing column (may be <code>null</code>)
+     *  <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the
+     *       maximum number of bytes in the column
+     *  <LI><B>IS_NULLABLE</B> String  => ISO rules are used to determine the nullability for a column.
+     *       <UL>
+     *       <LI> YES           --- if the column can include NULLs
+     *       <LI> NO            --- if the column cannot include NULLs
+     *       <LI> empty string  --- if the nullability for the column is unknown
+     *       </UL>
+     *  </OL>
+     *
+     * <p>The COLUMN_SIZE column specifies the column size for the given column.
+     * For numeric data, this is the maximum precision.  For character data, this is the length in characters.
+     * For datetime datatypes, this is the length in characters of the String representation (assuming the
+     * maximum allowed precision of the fractional seconds component). For binary data, this is the length in bytes.  For the ROWID datatype,
+     * this is the length in bytes. Null is returned for data types where the
+     * column size is not applicable.
+     *
+     * @param catalog a catalog name; must match the catalog name as it
+     *        is stored in the database; "" retrieves those without a catalog;
+     *        <code>null</code> means that the catalog name should not be used to narrow
+     *        the search
+     * @param schemaPattern a schema name pattern; must match the schema name
+     *        as it is stored in the database; "" retrieves those without a schema;
+     *        <code>null</code> means that the schema name should not be used to narrow
+     *        the search
+     * @param tableNamePattern a table name pattern; must match the
+     *        table name as it is stored in the database
+     * @param columnNamePattern a column name pattern; must match the column
+     *        name as it is stored in the database
+     * @return <code>ResultSet</code> - each row is a column description
+     * @exception SQLException if a database access error occurs
+     * @see PseudoColumnUsage
+     * @since 1.7
+     */
+    ResultSet getPseudoColumns(String catalog, String schemaPattern,
+                         String tableNamePattern, String columnNamePattern)
+        throws SQLException;
+
+    /**
+     * Retrieves whether a generated key will always be returned if the column
+     * name(s) or indexe(s) specified for the auto generated key column(s)
+     * are valid and the statement succeeds.  The key that is returned may or
+     * may not be based on the column(s) for the auto generated key.
+     * Consult your JDBC driver documentation for additional details.
+     * @return <code>true</code> if so; <code>false</code> otherwise
+     * @exception SQLException if a database access error occurs
+     * @since 1.7
+     */
+    boolean  generatedKeyAlwaysReturned() throws SQLException;
 }
--- a/src/share/classes/java/sql/Date.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/Date.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -96,11 +96,12 @@
      * a <code>Date</code> value.
      *
      * @param s a <code>String</code> object representing a date in
-     *        in the format "yyyy-mm-dd"
+     *        in the format "yyyy-[m]m-[d]d". The leading zero for <code>mm</code>
+     * and <code>dd</code> may also be omitted.
      * @return a <code>java.sql.Date</code> object representing the
      *         given date
      * @throws IllegalArgumentException if the date given is not in the
-     *         JDBC date escape format (yyyy-mm-dd)
+     *         JDBC date escape format (yyyy-[m]m-[d]d)
      */
     public static Date valueOf(String s) {
         final int YEAR_LENGTH = 4;
@@ -123,8 +124,9 @@
             String yyyy = s.substring(0, firstDash);
             String mm = s.substring(firstDash + 1, secondDash);
             String dd = s.substring(secondDash + 1);
-            if (yyyy.length() == YEAR_LENGTH && mm.length() == MONTH_LENGTH &&
-                    dd.length() == DAY_LENGTH) {
+            if (yyyy.length() == YEAR_LENGTH &&
+                    (mm.length() >= 1 && mm.length() <= MONTH_LENGTH) &&
+                    (dd.length() >= 1 && dd.length() <= DAY_LENGTH)) {
                 int year = Integer.parseInt(yyyy);
                 int month = Integer.parseInt(mm);
                 int day = Integer.parseInt(dd);
--- a/src/share/classes/java/sql/Driver.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/Driver.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -25,6 +25,8 @@
 
 package java.sql;
 
+import java.util.logging.Logger;
+
 /**
  * The interface that every driver class must implement.
  * <P>The Java SQL framework allows for multiple database drivers.
@@ -150,4 +152,19 @@
      *         otherwise
      */
     boolean jdbcCompliant();
+
+    //------------------------- JDBC 4.1 -----------------------------------
+
+    /**
+     * Return the parent Logger of all the Loggers used by this driver. This
+     * should be the Logger farthest from the root Logger that is
+     * still an ancestor of all of the Loggers used by this driver. Configuring
+     * this Logger will affect all of the log messages generated by the driver.
+     * In the worst case, this may be the root Logger.
+     *
+     * @return the parent Logger for this driver
+     * @throws SQLFeatureNotSupportedException if the driver does not use <code>java.util.logging<code>.
+     * @since 1.7
+     */
+    public Logger getParentLogger() throws SQLFeatureNotSupportedException;
 }
--- a/src/share/classes/java/sql/PreparedStatement.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/PreparedStatement.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -69,6 +69,10 @@
      * @exception SQLException if a database access error occurs;
      * this method is called on a closed  <code>PreparedStatement</code> or the SQL
      *            statement does not return a <code>ResultSet</code> object
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      */
     ResultSet executeQuery() throws SQLException;
 
@@ -82,8 +86,11 @@
      *         or (2) 0 for SQL statements that return nothing
      * @exception SQLException if a database access error occurs;
      * this method is called on a closed  <code>PreparedStatement</code>
-     * or the SQL
-     *            statement returns a <code>ResultSet</code> object
+     * or the SQL statement returns a <code>ResultSet</code> object
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      */
     int executeUpdate() throws SQLException;
 
@@ -463,6 +470,10 @@
      * @exception SQLException if a database access error occurs;
      * this method is called on a closed <code>PreparedStatement</code>
      * or an argument is supplied to this method
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      * @see Statement#execute
      * @see Statement#getResultSet
      * @see Statement#getUpdateCount
@@ -1208,4 +1219,5 @@
      void setNClob(int parameterIndex, Reader reader)
        throws SQLException;
 
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/sql/PseudoColumnUsage.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.sql;
+
+
+/**
+ * Enumeration for pseudo/hidden column usage.
+ *
+ * @since 1.7
+ * @see DatabaseMetaData#getPseudoColumns
+ */
+public enum PseudoColumnUsage {
+
+    /**
+     * The pseudo/hidden column may only be used in a SELECT list.
+     */
+    SELECT_LIST_ONLY,
+
+    /**
+     * The pseudo/hidden column may only be used in a WHERE clause.
+     */
+    WHERE_CLAUSE_ONLY,
+
+    /**
+     * There are no restrictions on the usage of the pseudo/hidden columns.
+     */
+    NO_USAGE_RESTRICTIONS,
+
+    /**
+     * The usage of the pseudo/hidden column cannot be determined.
+     */
+    USAGE_UNKNOWN
+
+}
--- a/src/share/classes/java/sql/ResultSet.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/ResultSet.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -145,7 +145,7 @@
  * @see ResultSetMetaData
  */
 
-public interface ResultSet extends Wrapper {
+public interface ResultSet extends Wrapper, AutoCloseable {
 
     /**
      * Moves the cursor froward one row from its current position.
@@ -1187,6 +1187,9 @@
      * cursor on the last row; calling the method <code>absolute(-2)</code>
      * moves the cursor to the next-to-last row, and so on.
      *
+     * <p>If the row number specified is zero, the cursor is moved to
+     * before the first row.
+     *
      * <p>An attempt to position the cursor beyond the first/last row in
      * the result set leaves the cursor before the first row or after
      * the last row.
@@ -1196,9 +1199,10 @@
      * is the same as calling <code>last()</code>.
      *
      * @param row the number of the row to which the cursor should move.
-     *        A positive number indicates the row number counting from the
-     *        beginning of the result set; a negative number indicates the
-     *        row number counting from the end of the result set
+     *        A value of zero indicates that the cursor will be positioned
+     *        before the first row; a positive number indicates the row number
+     *        counting from the beginning of the result set; a negative number
+     *        indicates the row number counting from the end of the result set
      * @return <code>true</code> if the cursor is moved to a position in this
      * <code>ResultSet</code> object;
      * <code>false</code> if the cursor is before the first row or after the
@@ -2529,7 +2533,7 @@
      * @exception SQLException if the columnLabel is not valid;
      * if a database access error occurs
      * or this method is called on a closed result set
-      * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
      * this method
      * @since 1.2
      */
@@ -4072,4 +4076,64 @@
      */
     void updateNClob(String columnLabel,  Reader reader) throws SQLException;
 
+    //------------------------- JDBC 4.1 -----------------------------------
+
+
+    /**
+     *<p>Retrieves the value of the designated column in the current row
+     * of this <code>ResultSet</code> object and will convert from the
+     * SQL type of the column to the requested Java data type, if the
+     * conversion is supported. If the conversion is not
+     * supported  or null is specified for the type, a
+     * <code>SQLException</code> is thrown.
+     *<p>
+     * At a minimum, an implementation must support the conversions defined in
+     * Appendix B, Table B-3 and conversion of appropriate user defined SQL
+     * types to a Java type which implements {@code SQLData}, or {@code Struct}.
+     * Additional conversions may be supported and are vendor defined.
+     *
+     * @param columnIndex the first column is 1, the second is 2, ...
+     * @param type Class representing the Java data type to convert the designated
+     * column to.
+     * @return an instance of {@code type} holding the column value
+     * @throws SQLException if conversion is not supported, type is null or
+     *         another error occurs. The getCause() method of the
+     * exception may provide a more detailed exception, for example, if
+     * a conversion error occurs
+     * @throws SQLFeatureNotSupportedException if the JDBC driver does not support
+     * this method
+     * @since 1.7
+     */
+     public <T> T getObject(int columnIndex, Class<T> type) throws SQLException;
+
+
+    /**
+     *<p>Retrieves the value of the designated column in the current row
+     * of this <code>ResultSet</code> object and will convert from the
+     * SQL type of the column to the requested Java data type, if the
+     * conversion is supported. If the conversion is not
+     * supported  or null is specified for the type, a
+     * <code>SQLException</code> is thrown.
+     *<p>
+     * At a minimum, an implementation must support the conversions defined in
+     * Appendix B, Table B-3 and conversion of appropriate user defined SQL
+     * types to a Java type which implements {@code SQLData}, or {@code Struct}.
+     * Additional conversions may be supported and are vendor defined.
+     *
+     * @param columnLabel the label for the column specified with the SQL AS clause.
+     * If the SQL AS clause was not specified, then the label is the name
+     * of the column
+     * @param type Class representing the Java data type to convert the designated
+     * column to.
+     * @return an instance of {@code type} holding the column value
+     * @throws SQLException if conversion is not supported, type is null or
+     *         another error occurs. The getCause() method of the
+     * exception may provide a more detailed exception, for example, if
+     * a conversion error occurs
+     * @throws SQLFeatureNotSupportedException if the JDBC driver does not support
+     * this method
+     * @since 1.7
+     */
+     public <T> T getObject(String columnLabel, Class<T> type) throws SQLException;
+
 }
--- a/src/share/classes/java/sql/SQLDataException.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/SQLDataException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -26,10 +26,13 @@
 package java.sql;
 
 /**
- * The subclass of {@link SQLException} thrown when the SQLState class value is '<i>22</i>'. This indicates
- * various data errors, including but not limited to not-allowed conversion, division by 0
- * and invalid arguments to functions.
- *
+ * The subclass of {@link SQLException} thrown when the SQLState class value
+ * is '<i>22</i>', or under vendor-specified conditions.  This indicates
+ * various data errors, including but not limited to data conversion errors,
+ * division by 0, and invalid arguments to functions.
+ * <p>
+ * Please consult your driver vendor documentation for the vendor-specified
+ * conditions for which this <code>Exception</code> may be thrown.
  * @since 1.6
  */
 public class SQLDataException extends SQLNonTransientException {
--- a/src/share/classes/java/sql/SQLIntegrityConstraintViolationException.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/SQLIntegrityConstraintViolationException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -26,9 +26,13 @@
 package java.sql;
 
 /**
- * The subclass of {@link SQLException} thrown when the SQLState class value is '<i>23</i>'. This indicates that an integrity
+ * The subclass of {@link SQLException} thrown when the SQLState class value
+ * is '<i>23</i>', or under vendor-specified conditions.
+ * This indicates that an integrity
  * constraint (foreign key, primary key or unique key) has been violated.
- *
+ * <p>
+ * Please consult your driver vendor documentation for the vendor-specified
+ * conditions for which this <code>Exception</code> may be thrown.
  * @since 1.6
  */
 public class SQLIntegrityConstraintViolationException extends SQLNonTransientException {
--- a/src/share/classes/java/sql/SQLInvalidAuthorizationSpecException.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/SQLInvalidAuthorizationSpecException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -26,9 +26,13 @@
 package java.sql;
 
 /**
- * The subclass of {@link SQLException} thrown when the SQLState class value is '<i>28</i>'. This indicated that the
- * authorization credentials presented during connection establishment are not valid.
- *
+ * The subclass of {@link SQLException} thrown when the SQLState class value
+ * is '<i>28</i>', or under vendor-specified conditions. This indicates that
+ * the authorization credentials presented during connection establishment
+ * are not valid.
+ * <p>
+ * Please consult your driver vendor documentation for the vendor-specified
+ * conditions for which this <code>Exception</code> may be thrown.
  * @since 1.6
  */
 public class SQLInvalidAuthorizationSpecException extends SQLNonTransientException {
--- a/src/share/classes/java/sql/SQLNonTransientConnectionException.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/SQLNonTransientConnectionException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -26,11 +26,13 @@
 package java.sql;
 
 /**
- * <P> The subclass of {@link SQLException} thrown for the SQLState
- * class value '<i>08</i>', representing
- * that the connection operation that failed will not succeed when
+ * The subclass of {@link SQLException} thrown for the SQLState
+ * class value '<i>08</i>', or under vendor-specified conditions.  This
+ * indicates that the connection operation that failed will not succeed if
  * the operation is retried without the cause of the failure being corrected.
  * <p>
+ * Please consult your driver vendor documentation for the vendor-specified
+ * conditions for which this <code>Exception</code> may be thrown.
  * @since 1.6
  */
 public class SQLNonTransientConnectionException extends java.sql.SQLNonTransientException {
--- a/src/share/classes/java/sql/SQLPermission.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/SQLPermission.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2010, Oracle and/or its affiliates. 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
@@ -30,9 +30,14 @@
 
 /**
  * The permission for which the <code>SecurityManager</code> will check
- * when code that is running in an applet calls the
- * <code>DriverManager.setLogWriter</code> method or the
- * <code>DriverManager.setLogStream</code> (deprecated) method.
+ * when code that is running in an applet, or an application with a
+ * <code>SecurityManager</code> enabled, calls the
+ * <code>DriverManager.setLogWriter</code> method,
+ * <code>DriverManager.setLogStream</code> (deprecated) method,
+ * {@code SyncFactory.setJNDIContext} method,
+ * {@code SyncFactory.setLogger} method,
+ * {@code Connection.setNetworktimeout} method,
+ * or the <code>Connection.abort</code> method.
  * If there is no <code>SQLPermission</code> object, these methods
  * throw a <code>java.lang.SecurityException</code> as a runtime exception.
  * <P>
@@ -48,7 +53,6 @@
  * but <code>*loadLibrary</code> or <code>a*b</code> is not valid.
  * <P>
  * The following table lists all the possible <code>SQLPermission</code> target names.
- * Currently, the only name allowed is <code>setLog</code>.
  * The table gives a description of what the permission allows
  * and a discussion of the risks of granting code the permission.
  * <P>
@@ -67,9 +71,33 @@
  * The contents of the log may contain usernames and passwords,
  * SQL statements, and SQL data.</td>
  * </tr>
+ * <tr>
+ * <td>callAbort</td>
+ *   <td>Allows the invocation of the {@code Connection} method
+ *   {@code abort}</td>
+ *   <td>Permits an application to terminate a physical connection to a
+ *  database.</td>
+ * </tr>
+ * <tr>
+ * <td>setSyncFactory</td>
+ *   <td>Allows the invocation of the {@code SyncFactory} methods
+ *   {@code setJNDIContext} and {@code setLogger}</td>
+ *   <td>Permits an application to specify the JNDI context from which the
+ *   {@code SyncProvider} implementations can be retrieved from and the logging
+ *   object to be used by the{@codeSyncProvider} implementation.</td>
+ * </tr>
  *
+ * <tr>
+ * <td>setNetworkTimeout</td>
+ *   <td>Allows the invocation of the {@code Connection} method
+ *   {@code setNetworkTimeout}</td>
+ *   <td>Permits an application to specify the maximum period a
+ * <code>Connection</code> or
+ * objects created from the <code>Connection</code>
+ * will wait for the database to reply to any one request.</td>
+ * </tr>
  * </table>
- *
+ *<p>
  * The person running an applet decides what permissions to allow
  * and will run the <code>Policy Tool</code> to create an
  * <code>SQLPermission</code> in a policy file.  A programmer does
--- a/src/share/classes/java/sql/SQLSyntaxErrorException.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/SQLSyntaxErrorException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -26,9 +26,12 @@
 package java.sql;
 
 /**
- * The subclass of {@link SQLException} thrown when the SQLState class value is '<i>42</i>'. This indicates that the
+ * The subclass of {@link SQLException} thrown when the SQLState class value
+ * is '<i>42</i>', or under vendor-specified conditions. This indicates that the
  * in-progress query has violated SQL syntax rules.
- *
+ * <p>
+ * Please consult your driver vendor documentation for the vendor-specified
+ * conditions for which this <code>Exception</code> may be thrown.
  * @since 1.6
  */
 public class SQLSyntaxErrorException extends SQLNonTransientException {
--- a/src/share/classes/java/sql/SQLTransactionRollbackException.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/SQLTransactionRollbackException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -26,10 +26,13 @@
 package java.sql;
 
 /**
- * The subclass of {@link SQLException} thrown when the SQLState class value is '<i>40</i>'. This indicates that the
- * current statement was automatically rolled back by the database becuase of deadlock or other
- * transaction serialization failures.
- *
+ * The subclass of {@link SQLException} thrown when the SQLState class value
+ * is '<i>40</i>', or under vendor-specified conditions. This indicates that the
+ * current statement was automatically rolled back by the database because
+ * of deadlock or other transaction serialization failures.
+ * <p>
+ * Please consult your driver vendor documentation for the vendor-specified
+ * conditions for which this <code>Exception</code> may be thrown.
  * @since 1.6
  */
 public class SQLTransactionRollbackException extends SQLTransientException {
--- a/src/share/classes/java/sql/SQLTransientConnectionException.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/SQLTransientConnectionException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -27,11 +27,12 @@
 
 /**
  * The subclass of {@link SQLException} for the SQLState class
- * value '<i>08</i>', representing
- * that the connection operation that failed might be able to succeed when
+ * value '<i>08</i>', or under vendor-specified conditions.  This indicates
+ * that the connection operation that failed might be able to succeed if
  * the operation is retried without any application-level changes.
- *<p>
- *
+ * <p>
+ * Please consult your driver vendor documentation for the vendor-specified
+ * conditions for which this <code>Exception</code> may be thrown.
  * @since 1.6
  */
 public class SQLTransientConnectionException extends java.sql.SQLTransientException {
--- a/src/share/classes/java/sql/Statement.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/Statement.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -40,20 +40,27 @@
  * @see Connection#createStatement
  * @see ResultSet
  */
-public interface Statement extends Wrapper {
+public interface Statement extends Wrapper, AutoCloseable {
 
     /**
      * Executes the given SQL statement, which returns a single
      * <code>ResultSet</code> object.
-     *
+     *<p>
+     * <strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql an SQL statement to be sent to the database, typically a
      *        static SQL <code>SELECT</code> statement
      * @return a <code>ResultSet</code> object that contains the data produced
      *         by the given query; never <code>null</code>
      * @exception SQLException if a database access error occurs,
-     * this method is called on a closed <code>Statement</code> or the given
+     * this method is called on a closed <code>Statement</code>, the given
      *            SQL statement produces anything other than a single
-     *            <code>ResultSet</code> object
+     *            <code>ResultSet</code> object, the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      */
     ResultSet executeQuery(String sql) throws SQLException;
 
@@ -61,7 +68,9 @@
      * Executes the given SQL statement, which may be an <code>INSERT</code>,
      * <code>UPDATE</code>, or <code>DELETE</code> statement or an
      * SQL statement that returns nothing, such as an SQL DDL statement.
-     *
+     *<p>
+     * <strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, <code>UPDATE</code> or
      * <code>DELETE</code>; or an SQL statement that returns nothing,
      * such as a DDL statement.
@@ -70,8 +79,13 @@
      *         or (2) 0 for SQL statements that return nothing
      *
      * @exception SQLException if a database access error occurs,
-     * this method is called on a closed <code>Statement</code> or the given
-     *            SQL statement produces a <code>ResultSet</code> object
+     * this method is called on a closed <code>Statement</code>, the given
+     * SQL statement produces a <code>ResultSet</code> object, the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      */
     int executeUpdate(String sql) throws SQLException;
 
@@ -198,11 +212,21 @@
     /**
      * Sets the number of seconds the driver will wait for a
      * <code>Statement</code> object to execute to the given number of seconds.
-     * If the limit is exceeded, an <code>SQLException</code> is thrown. A JDBC
-     * driver must apply this limit to the <code>execute</code>,
-     * <code>executeQuery</code> and <code>executeUpdate</code> methods. JDBC driver
-     * implementations may also apply this limit to <code>ResultSet</code> methods
+     *By default there is no limit on the amount of time allowed for a running
+     * statement to complete. If the limit is exceeded, an
+     * <code>SQLTimeoutException</code> is thrown.
+     * A JDBC driver must apply this limit to the <code>execute</code>,
+     * <code>executeQuery</code> and <code>executeUpdate</code> methods.
+     * <p>
+     * <strong>Note:</strong> JDBC driver implementations may also apply this
+     * limit to {@code ResultSet} methods
      * (consult your driver vendor documentation for details).
+     * <p>
+     * <strong>Note:</strong> In the case of {@code Statement} batching, it is
+     * implementation defined as to whether the time-out is applied to
+     * individual SQL commands added via the {@code addBatch} method or to
+     * the entire batch of SQL commands invoked by the {@code executeBatch}
+     * method (consult your driver vendor documentation for details).
      *
      * @param seconds the new query timeout limit in seconds; zero means
      *        there is no limit
@@ -300,13 +324,21 @@
      * <code>getResultSet</code> or <code>getUpdateCount</code>
      * to retrieve the result, and <code>getMoreResults</code> to
      * move to any subsequent result(s).
-     *
+     * <p>
+     *<strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql any SQL statement
      * @return <code>true</code> if the first result is a <code>ResultSet</code>
      *         object; <code>false</code> if it is an update count or there are
      *         no results
-     * @exception SQLException if a database access error occurs or
-     * this method is called on a closed <code>Statement</code>
+     * @exception SQLException if a database access error occurs,
+     * this method is called on a closed <code>Statement</code>,
+     * the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      * @see #getResultSet
      * @see #getUpdateCount
      * @see #getMoreResults
@@ -465,12 +497,14 @@
      * <code>Statement</code> object. The commands in this list can be
      * executed as a batch by calling the method <code>executeBatch</code>.
      * <P>
-     *
+     *<strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql typically this is a SQL <code>INSERT</code> or
      * <code>UPDATE</code> statement
      * @exception SQLException if a database access error occurs,
-     * this method is called on a closed <code>Statement</code> or the
-     * driver does not support batch updates
+     * this method is called on a closed <code>Statement</code>, the
+     * driver does not support batch updates, the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
      * @see #executeBatch
      * @see DatabaseMetaData#supportsBatchUpdates
      * @since 1.2
@@ -536,7 +570,10 @@
      * driver does not support batch statements. Throws {@link BatchUpdateException}
      * (a subclass of <code>SQLException</code>) if one of the commands sent to the
      * database fails to execute properly or attempts to return a result set.
-     *
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      *
      * @see #addBatch
      * @see DatabaseMetaData#supportsBatchUpdates
@@ -678,7 +715,9 @@
      * flag if the SQL statement
      * is not an <code>INSERT</code> statement, or an SQL statement able to return
      * auto-generated keys (the list of such statements is vendor-specific).
-     *
+     *<p>
+     * <strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, <code>UPDATE</code> or
      * <code>DELETE</code>; or an SQL statement that returns nothing,
      * such as a DDL statement.
@@ -693,10 +732,15 @@
      *
      * @exception SQLException if a database access error occurs,
      *  this method is called on a closed <code>Statement</code>, the given
-     *            SQL statement returns a <code>ResultSet</code> object, or
-     *            the given constant is not one of those allowed
+     *            SQL statement returns a <code>ResultSet</code> object,
+     *            the given constant is not one of those allowed, the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
      * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
      * this method with a constant of Statement.RETURN_GENERATED_KEYS
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      * @since 1.4
      */
     int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException;
@@ -709,7 +753,9 @@
      * available. The driver will ignore the array if the SQL statement
      * is not an <code>INSERT</code> statement, or an SQL statement able to return
      * auto-generated keys (the list of such statements is vendor-specific).
-     *
+     *<p>
+     * <strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, <code>UPDATE</code> or
      * <code>DELETE</code>; or an SQL statement that returns nothing,
      * such as a DDL statement.
@@ -721,10 +767,15 @@
      *
      * @exception SQLException if a database access error occurs,
      * this method is called on a closed <code>Statement</code>, the SQL
-     *            statement returns a <code>ResultSet</code> object, or the
-     *            second argument supplied to this method is not an <code>int</code> array
-     *            whose elements are valid column indexes
+     * statement returns a <code>ResultSet</code> object,the second argument
+     * supplied to this method is not an
+     * <code>int</code> array whose elements are valid column indexes, the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
      * @throws SQLFeatureNotSupportedException  if the JDBC driver does not support this method
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      * @since 1.4
      */
     int executeUpdate(String sql, int columnIndexes[]) throws SQLException;
@@ -737,7 +788,9 @@
      * available. The driver will ignore the array if the SQL statement
      * is not an <code>INSERT</code> statement, or an SQL statement able to return
      * auto-generated keys (the list of such statements is vendor-specific).
-     *
+     *<p>
+     * <strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, <code>UPDATE</code> or
      * <code>DELETE</code>; or an SQL statement that returns nothing,
      * such as a DDL statement.
@@ -748,11 +801,15 @@
      *         that return nothing
      * @exception SQLException if a database access error occurs,
      *  this method is called on a closed <code>Statement</code>, the SQL
-     *            statement returns a <code>ResultSet</code> object, or the
+     *            statement returns a <code>ResultSet</code> object, the
      *            second argument supplied to this method is not a <code>String</code> array
-     *            whose elements are valid column names
-     *
+     *            whose elements are valid column names, the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
      * @throws SQLFeatureNotSupportedException  if the JDBC driver does not support this method
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      * @since 1.4
      */
     int executeUpdate(String sql, String columnNames[]) throws SQLException;
@@ -776,7 +833,9 @@
      * <code>getResultSet</code> or <code>getUpdateCount</code>
      * to retrieve the result, and <code>getMoreResults</code> to
      * move to any subsequent result(s).
-     *
+     *<p>
+     *<strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql any SQL statement
      * @param autoGeneratedKeys a constant indicating whether auto-generated
      *        keys should be made available for retrieval using the method
@@ -787,12 +846,18 @@
      *         object; <code>false</code> if it is an update count or there are
      *         no results
      * @exception SQLException if a database access error occurs,
-     * this method is called on a closed <code>Statement</code> or the second
+     * this method is called on a closed <code>Statement</code>, the second
      *         parameter supplied to this method is not
      *         <code>Statement.RETURN_GENERATED_KEYS</code> or
-     *         <code>Statement.NO_GENERATED_KEYS</code>.
+     *         <code>Statement.NO_GENERATED_KEYS</code>,
+     * the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
      * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
      * this method with a constant of Statement.RETURN_GENERATED_KEYS
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      * @see #getResultSet
      * @see #getUpdateCount
      * @see #getMoreResults
@@ -823,7 +888,9 @@
      * <code>getResultSet</code> or <code>getUpdateCount</code>
      * to retrieve the result, and <code>getMoreResults</code> to
      * move to any subsequent result(s).
-     *
+     *<p>
+     * <strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql any SQL statement
      * @param columnIndexes an array of the indexes of the columns in the
      *        inserted row that should be  made available for retrieval by a
@@ -832,10 +899,15 @@
      *         object; <code>false</code> if it is an update count or there
      *         are no results
      * @exception SQLException if a database access error occurs,
-     * this method is called on a closed <code>Statement</code> or the
+     * this method is called on a closed <code>Statement</code>, the
      *            elements in the <code>int</code> array passed to this method
-     *            are not valid column indexes
+     *            are not valid column indexes, the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
      * @throws SQLFeatureNotSupportedException  if the JDBC driver does not support this method
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      * @see #getResultSet
      * @see #getUpdateCount
      * @see #getMoreResults
@@ -865,7 +937,9 @@
      * <code>getResultSet</code> or <code>getUpdateCount</code>
      * to retrieve the result, and <code>getMoreResults</code> to
      * move to any subsequent result(s).
-     *
+     *<p>
+     * <strong>Note:</strong>This method cannot be called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>.
      * @param sql any SQL statement
      * @param columnNames an array of the names of the columns in the inserted
      *        row that should be made available for retrieval by a call to the
@@ -874,10 +948,15 @@
      *         object; <code>false</code> if it is an update count or there
      *         are no more results
      * @exception SQLException if a database access error occurs,
-     * this method is called on a closed <code>Statement</code> or the
+     * this method is called on a closed <code>Statement</code>,the
      *          elements of the <code>String</code> array passed to this
-     *          method are not valid column names
+     *          method are not valid column names, the method is called on a
+     * <code>PreparedStatement</code> or <code>CallableStatement</code>
      * @throws SQLFeatureNotSupportedException  if the JDBC driver does not support this method
+     * @throws SQLTimeoutException when the driver has determined that the
+     * timeout value that was specified by the {@code setQueryTimeout}
+     * method has been exceeded and has at least attempted to cancel
+     * the currently running {@code Statement}
      * @see #getResultSet
      * @see #getUpdateCount
      * @see #getMoreResults
@@ -951,4 +1030,34 @@
         boolean isPoolable()
                 throws SQLException;
 
+    //--------------------------JDBC 4.1 -----------------------------
+
+    /**
+     * Specifies that this {@code Statement} will be closed when all its
+     * dependent result sets are closed. If execution of the {@code Statement}
+     * does not produce any result sets, this method has no effect.
+     * <p>
+     * <strong>Note:</strong> Multiple calls to {@code closeOnCompletion} do
+     * not toggle the effect on this {@code Statement}. However, a call to
+     * {@code closeOnCompletion} does effect both the subsequent execution of
+     * statements, and statements that currently have open, dependent,
+     * result sets.
+     *
+     * @throws SQLException if this method is called on a closed
+     * {@code Statement}
+     * @since 1.7
+     */
+    public void closeOnCompletion() throws SQLException;
+
+    /**
+     * Returns a value indicating whether this {@code Statement} will be
+     * closed when all dependent objects such as resultsets are closed.
+     * @return {@code true} if the {@code Statement} will be closed when all
+     * of its dependent objects are closed; {@code false} otherwise
+     * @throws SQLException if this method is called on a closed
+     * {@code Statement}
+     * @since 1.7
+     */
+    public boolean isCloseOnCompletion() throws SQLException;
+
 }
--- a/src/share/classes/java/sql/Timestamp.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/sql/Timestamp.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -155,19 +155,26 @@
      * Converts a <code>String</code> object in JDBC timestamp escape format to a
      * <code>Timestamp</code> value.
      *
-     * @param s timestamp in format <code>yyyy-mm-dd hh:mm:ss[.f...]</code>.  The
-     * fractional seconds may be omitted.
+     * @param s timestamp in format <code>yyyy-[m]m-[d]d hh:mm:ss[.f...]</code>.  The
+     * fractional seconds may be omitted. The leading zero for <code>mm</code>
+     * and <code>dd</code> may also be omitted.
+     *
      * @return corresponding <code>Timestamp</code> value
      * @exception java.lang.IllegalArgumentException if the given argument
-     * does not have the format <code>yyyy-mm-dd hh:mm:ss[.f...]</code>
+     * does not have the format <code>yyyy-[m]m-[d]d hh:mm:ss[.f...]</code>
      */
     public static Timestamp valueOf(String s) {
+        final int YEAR_LENGTH = 4;
+        final int MONTH_LENGTH = 2;
+        final int DAY_LENGTH = 2;
+        final int MAX_MONTH = 12;
+        final int MAX_DAY = 31;
         String date_s;
         String time_s;
         String nanos_s;
-        int year;
-        int month;
-        int day;
+        int year = 0;
+        int month = 0;
+        int day = 0;
         int hour;
         int minute;
         int second;
@@ -182,17 +189,9 @@
         String zeros = "000000000";
         String delimiterDate = "-";
         String delimiterTime = ":";
-        StringTokenizer stringTokeninzerDate;
-        StringTokenizer stringTokeninzerTime;
 
         if (s == null) throw new java.lang.IllegalArgumentException("null string");
 
-        int counterD = 0;
-        int intDate[] = {4,2,2};
-
-        int counterT = 0;
-        int intTime[] = {2,2,12};
-
         // Split the string into date and time components
         s = s.trim();
         dividingSpace = s.indexOf(' ');
@@ -203,30 +202,6 @@
             throw new java.lang.IllegalArgumentException(formatError);
         }
 
-        stringTokeninzerTime = new StringTokenizer(time_s, delimiterTime);
-        stringTokeninzerDate = new StringTokenizer(date_s, delimiterDate);
-
-        while(stringTokeninzerDate.hasMoreTokens()) {
-             String tokenDate = stringTokeninzerDate.nextToken();
-             if(tokenDate.length() != intDate[counterD] ) {
-                throw new java.lang.IllegalArgumentException(formatError);
-             }
-             counterD++;
-        }
-
-        /*
-         //Commenting this portion out for checking of time
-
-        while(stringTokeninzerTime.hasMoreTokens()) {
-             String tokenTime = stringTokeninzerTime.nextToken();
-
-             if (counterT < 2 && tokenTime.length() != intTime[counterT]  ) {
-                throw new java.lang.IllegalArgumentException(formatError);
-             }
-             counterT++;
-        }
-        */
-
         // Parse the date
         firstDash = date_s.indexOf('-');
         secondDash = date_s.indexOf('-', firstDash+1);
@@ -239,14 +214,24 @@
         period = time_s.indexOf('.', secondColon+1);
 
         // Convert the date
-        if ((firstDash > 0) && (secondDash > 0) &&
-            (secondDash < date_s.length()-1)) {
-            year = Integer.parseInt(date_s.substring(0, firstDash)) - 1900;
-            month =
-                Integer.parseInt(date_s.substring
-                                 (firstDash+1, secondDash)) - 1;
-            day = Integer.parseInt(date_s.substring(secondDash+1));
-        } else {
+        boolean parsedDate = false;
+        if ((firstDash > 0) && (secondDash > 0) && (secondDash < date_s.length() - 1)) {
+            String yyyy = date_s.substring(0, firstDash);
+            String mm = date_s.substring(firstDash + 1, secondDash);
+            String dd = date_s.substring(secondDash + 1);
+            if (yyyy.length() == YEAR_LENGTH &&
+                    (mm.length() >= 1 && mm.length() <= MONTH_LENGTH) &&
+                    (dd.length() >= 1 && dd.length() <= DAY_LENGTH)) {
+                 year = Integer.parseInt(yyyy);
+                 month = Integer.parseInt(mm);
+                 day = Integer.parseInt(dd);
+
+                if ((month >= 1 && month <= MAX_MONTH) && (day >= 1 && day <= MAX_DAY)) {
+                    parsedDate = true;
+                }
+            }
+        }
+        if (! parsedDate) {
             throw new java.lang.IllegalArgumentException(formatError);
         }
 
@@ -272,10 +257,10 @@
                 second = Integer.parseInt(time_s.substring(secondColon+1));
             }
         } else {
-            throw new java.lang.IllegalArgumentException();
+            throw new java.lang.IllegalArgumentException(formatError);
         }
 
-        return new Timestamp(year, month, day, hour, minute, second, a_nanos);
+        return new Timestamp(year - 1900, month - 1, day, hour, minute, second, a_nanos);
     }
 
     /**
@@ -502,14 +487,10 @@
 
     /**
      * Compares this <code>Timestamp</code> object to the given
-     * <code>Date</code>, which must be a <code>Timestamp</code>
-     * object. If the argument is not a <code>Timestamp</code> object,
-     * this method throws a <code>ClassCastException</code> object.
-     * (<code>Timestamp</code> objects are
-     * comparable only to other <code>Timestamp</code> objects.)
+     * <code>Date</code> object.
      *
-     * @param o the <code>Date</code> to be compared, which must be a
-     *        <code>Timestamp</code> object
+     * @param o the <code>Date</code> to be compared to
+     *          this <code>Timestamp</code> object
      * @return  the value <code>0</code> if this <code>Timestamp</code> object
      *          and the given object are equal; a value less than <code>0</code>
      *          if this  <code>Timestamp</code> object is before the given argument;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/text/CalendarBuilder.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.text;
+
+import java.util.Calendar;
+import static java.util.GregorianCalendar.*;
+
+/**
+ * {@code CalendarBuilder} keeps field-value pairs for setting
+ * the calendar fields of the given {@code Calendar}. It has the
+ * {@link Calendar#FIELD_COUNT FIELD_COUNT}-th field for the week year
+ * support. Also {@code ISO_DAY_OF_WEEK} is used to specify
+ * {@code DAY_OF_WEEK} in the ISO day of week numbering.
+ *
+ * <p>{@code CalendarBuilder} retains the semantic of the pseudo
+ * timestamp for fields. {@code CalendarBuilder} uses a single
+ * int array combining fields[] and stamp[] of {@code Calendar}.
+ *
+ * @author Masayoshi Okutsu
+ */
+class CalendarBuilder {
+    /*
+     * Pseudo time stamp constants used in java.util.Calendar
+     */
+    private static final int UNSET = 0;
+    private static final int COMPUTED = 1;
+    private static final int MINIMUM_USER_STAMP = 2;
+
+    private static final int MAX_FIELD = FIELD_COUNT + 1;
+
+    public static final int WEEK_YEAR = FIELD_COUNT;
+    public static final int ISO_DAY_OF_WEEK = 1000; // pseudo field index
+
+    // stamp[] (lower half) and field[] (upper half) combined
+    private final int[] field;
+    private int nextStamp;
+    private int maxFieldIndex;
+
+    CalendarBuilder() {
+        field = new int[MAX_FIELD * 2];
+        nextStamp = MINIMUM_USER_STAMP;
+        maxFieldIndex = -1;
+    }
+
+    CalendarBuilder set(int index, int value) {
+        if (index == ISO_DAY_OF_WEEK) {
+            index = DAY_OF_WEEK;
+            value = toCalendarDayOfWeek(value);
+        }
+        field[index] = nextStamp++;
+        field[MAX_FIELD + index] = value;
+        if (index > maxFieldIndex && index < FIELD_COUNT) {
+            maxFieldIndex = index;
+        }
+        return this;
+    }
+
+    CalendarBuilder addYear(int value) {
+        field[MAX_FIELD + YEAR] += value;
+        field[MAX_FIELD + WEEK_YEAR] += value;
+        return this;
+    }
+
+    boolean isSet(int index) {
+        if (index == ISO_DAY_OF_WEEK) {
+            index = DAY_OF_WEEK;
+        }
+        return field[index] > UNSET;
+    }
+
+    Calendar establish(Calendar cal) {
+        boolean weekDate = isSet(WEEK_YEAR)
+                            && field[WEEK_YEAR] > field[YEAR];
+        if (weekDate && !cal.isWeekDateSupported()) {
+            // Use YEAR instead
+            if (!isSet(YEAR)) {
+                set(YEAR, field[MAX_FIELD + WEEK_YEAR]);
+            }
+            weekDate = false;
+        }
+
+        cal.clear();
+        // Set the fields from the min stamp to the max stamp so that
+        // the field resolution works in the Calendar.
+        for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
+            for (int index = 0; index <= maxFieldIndex; index++) {
+                if (field[index] == stamp) {
+                    cal.set(index, field[MAX_FIELD + index]);
+                    break;
+                }
+            }
+        }
+
+        if (weekDate) {
+            int weekOfYear = isSet(WEEK_OF_YEAR) ? field[MAX_FIELD + WEEK_OF_YEAR] : 1;
+            int dayOfWeek = isSet(DAY_OF_WEEK) ?
+                                field[MAX_FIELD + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
+            if (!isValidDayOfWeek(dayOfWeek) && cal.isLenient()) {
+                if (dayOfWeek >= 8) {
+                    dayOfWeek--;
+                    weekOfYear += dayOfWeek / 7;
+                    dayOfWeek = (dayOfWeek % 7) + 1;
+                } else {
+                    while (dayOfWeek <= 0) {
+                        dayOfWeek += 7;
+                        weekOfYear--;
+                    }
+                }
+                dayOfWeek = toCalendarDayOfWeek(dayOfWeek);
+            }
+            cal.setWeekDate(field[MAX_FIELD + WEEK_YEAR], weekOfYear, dayOfWeek);
+        }
+        return cal;
+    }
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("CalendarBuilder:[");
+        for (int i = 0; i < field.length; i++) {
+            if (isSet(i)) {
+                sb.append(i).append('=').append(field[MAX_FIELD + i]).append(',');
+            }
+        }
+        int lastIndex = sb.length() - 1;
+        if (sb.charAt(lastIndex) == ',') {
+            sb.setLength(lastIndex);
+        }
+        sb.append(']');
+        return sb.toString();
+    }
+
+    static int toISODayOfWeek(int calendarDayOfWeek) {
+        return calendarDayOfWeek == SUNDAY ? 7 : calendarDayOfWeek - 1;
+    }
+
+    static int toCalendarDayOfWeek(int isoDayOfWeek) {
+        if (!isValidDayOfWeek(isoDayOfWeek)) {
+            // adjust later for lenient mode
+            return isoDayOfWeek;
+        }
+        return isoDayOfWeek == 7 ? SUNDAY : isoDayOfWeek + 1;
+    }
+
+    static boolean isValidDayOfWeek(int dayOfWeek) {
+        return dayOfWeek > 0 && dayOfWeek <= 7;
+    }
+}
--- a/src/share/classes/java/text/DateFormat.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/text/DateFormat.java	Fri Sep 24 16:41:32 2010 -0700
@@ -443,7 +443,7 @@
      */
     public final static DateFormat getTimeInstance()
     {
-        return get(DEFAULT, 0, 1, Locale.getDefault());
+        return get(DEFAULT, 0, 1, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -455,7 +455,7 @@
      */
     public final static DateFormat getTimeInstance(int style)
     {
-        return get(style, 0, 1, Locale.getDefault());
+        return get(style, 0, 1, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -479,7 +479,7 @@
      */
     public final static DateFormat getDateInstance()
     {
-        return get(0, DEFAULT, 2, Locale.getDefault());
+        return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -491,7 +491,7 @@
      */
     public final static DateFormat getDateInstance(int style)
     {
-        return get(0, style, 2, Locale.getDefault());
+        return get(0, style, 2, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -515,7 +515,7 @@
      */
     public final static DateFormat getDateTimeInstance()
     {
-        return get(DEFAULT, DEFAULT, 3, Locale.getDefault());
+        return get(DEFAULT, DEFAULT, 3, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -530,7 +530,7 @@
     public final static DateFormat getDateTimeInstance(int dateStyle,
                                                        int timeStyle)
     {
-        return get(timeStyle, dateStyle, 3, Locale.getDefault());
+        return get(timeStyle, dateStyle, 3, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
--- a/src/share/classes/java/text/DateFormatSymbols.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/text/DateFormatSymbols.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -118,7 +118,7 @@
      */
     public DateFormatSymbols()
     {
-        initializeData(Locale.getDefault());
+        initializeData(Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -226,7 +226,30 @@
      * Unlocalized date-time pattern characters. For example: 'y', 'd', etc.
      * All locales use the same these unlocalized pattern characters.
      */
-    static final String  patternChars = "GyMdkHmsSEDFwWahKzZ";
+    static final String  patternChars = "GyMdkHmsSEDFwWahKzZYuX";
+
+    static final int PATTERN_ERA                  =  0; // G
+    static final int PATTERN_YEAR                 =  1; // y
+    static final int PATTERN_MONTH                =  2; // M
+    static final int PATTERN_DAY_OF_MONTH         =  3; // d
+    static final int PATTERN_HOUR_OF_DAY1         =  4; // k
+    static final int PATTERN_HOUR_OF_DAY0         =  5; // H
+    static final int PATTERN_MINUTE               =  6; // m
+    static final int PATTERN_SECOND               =  7; // s
+    static final int PATTERN_MILLISECOND          =  8; // S
+    static final int PATTERN_DAY_OF_WEEK          =  9; // E
+    static final int PATTERN_DAY_OF_YEAR          = 10; // D
+    static final int PATTERN_DAY_OF_WEEK_IN_MONTH = 11; // F
+    static final int PATTERN_WEEK_OF_YEAR         = 12; // w
+    static final int PATTERN_WEEK_OF_MONTH        = 13; // W
+    static final int PATTERN_AM_PM                = 14; // a
+    static final int PATTERN_HOUR1                = 15; // h
+    static final int PATTERN_HOUR0                = 16; // K
+    static final int PATTERN_ZONE_NAME            = 17; // z
+    static final int PATTERN_ZONE_VALUE           = 18; // Z
+    static final int PATTERN_WEEK_YEAR            = 19; // Y
+    static final int PATTERN_ISO_DAY_OF_WEEK      = 20; // u
+    static final int PATTERN_ISO_ZONE             = 21; // X
 
     /**
      * Localized date-time pattern characters. For example, a locale may
@@ -282,7 +305,7 @@
      * @since 1.6
      */
     public static final DateFormatSymbols getInstance() {
-        return getInstance(Locale.getDefault());
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -505,7 +528,7 @@
      * @return the localized date-time pattern characters.
      */
     public String getLocalPatternChars() {
-        return new String(localPatternChars);
+        return localPatternChars;
     }
 
     /**
@@ -514,7 +537,8 @@
      * pattern characters.
      */
     public void setLocalPatternChars(String newLocalPatternChars) {
-        localPatternChars = new String(newLocalPatternChars);
+        // Call toString() to throw an NPE in case the argument is null
+        localPatternChars = newLocalPatternChars.toString();
     }
 
     /**
@@ -699,7 +723,7 @@
         } else {
             dst.zoneStrings = null;
         }
-        dst.localPatternChars = new String (src.localPatternChars);
+        dst.localPatternChars = src.localPatternChars;
     }
 
     /**
--- a/src/share/classes/java/text/DecimalFormat.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/text/DecimalFormat.java	Fri Sep 24 16:41:32 2010 -0700
@@ -392,7 +392,7 @@
      * @see java.text.NumberFormat#getPercentInstance
      */
     public DecimalFormat() {
-        Locale def = Locale.getDefault();
+        Locale def = Locale.getDefault(Locale.Category.FORMAT);
         // try to get the pattern from the cache
         String pattern = (String) cachedLocaleData.get(def);
         if (pattern == null) {  /* cache miss */
@@ -430,7 +430,7 @@
      */
     public DecimalFormat(String pattern) {
         // Always applyPattern after the symbols are set
-        this.symbols = new DecimalFormatSymbols(Locale.getDefault());
+        this.symbols = new DecimalFormatSymbols(Locale.getDefault(Locale.Category.FORMAT));
         applyPattern(pattern, false);
     }
 
--- a/src/share/classes/java/text/DecimalFormatSymbols.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/text/DecimalFormatSymbols.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -43,10 +43,10 @@
 import java.io.Serializable;
 import java.text.spi.DecimalFormatSymbolsProvider;
 import java.util.Currency;
-import java.util.Hashtable;
 import java.util.Locale;
 import java.util.ResourceBundle;
-import java.util.spi.LocaleServiceProvider;
+import java.util.concurrent.ConcurrentHashMap;
+
 import sun.util.LocaleServiceProviderPool;
 import sun.util.resources.LocaleData;
 
@@ -76,7 +76,7 @@
      * {@link #getInstance(Locale) getInstance} method.
      */
     public DecimalFormatSymbols() {
-        initialize( Locale.getDefault() );
+        initialize( Locale.getDefault(Locale.Category.FORMAT) );
     }
 
     /**
@@ -125,7 +125,7 @@
      * @since 1.6
      */
     public static final DecimalFormatSymbols getInstance() {
-        return getInstance(Locale.getDefault());
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -527,10 +527,17 @@
 
         // get resource bundle data - try the cache first
         boolean needCacheUpdate = false;
-        Object[] data = (Object[]) cachedLocaleData.get(locale);
+        Object[] data = cachedLocaleData.get(locale);
         if (data == null) {  /* cache miss */
+            // When numbering system is thai (Locale's extension contains u-nu-thai),
+            // we read the data from th_TH_TH.
+            Locale lookupLocale = locale;
+            String numberType = locale.getUnicodeLocaleType("nu");
+            if (numberType != null && numberType.equals("thai")) {
+                lookupLocale = new Locale("th", "TH", "TH");
+            }
             data = new Object[3];
-            ResourceBundle rb = LocaleData.getNumberFormatData(locale);
+            ResourceBundle rb = LocaleData.getNumberFormatData(lookupLocale);
             data[0] = rb.getStringArray("NumberElements");
             needCacheUpdate = true;
         }
@@ -586,7 +593,7 @@
         monetarySeparator = decimalSeparator;
 
         if (needCacheUpdate) {
-            cachedLocaleData.put(locale, data);
+            cachedLocaleData.putIfAbsent(locale, data);
         }
     }
 
@@ -806,7 +813,7 @@
      * cache to hold the NumberElements and the Currency
      * of a Locale.
      */
-    private static final Hashtable cachedLocaleData = new Hashtable(3);
+    private static final ConcurrentHashMap<Locale, Object[]> cachedLocaleData = new ConcurrentHashMap<Locale, Object[]>(3);
 
     /**
      * Obtains a DecimalFormatSymbols instance from a DecimalFormatSymbolsProvider
--- a/src/share/classes/java/text/MessageFormat.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/text/MessageFormat.java	Fri Sep 24 16:41:32 2010 -0700
@@ -363,7 +363,7 @@
      * @exception IllegalArgumentException if the pattern is invalid
      */
     public MessageFormat(String pattern) {
-        this.locale = Locale.getDefault();
+        this.locale = Locale.getDefault(Locale.Category.FORMAT);
         applyPattern(pattern);
     }
 
--- a/src/share/classes/java/text/NumberFormat.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/text/NumberFormat.java	Fri Sep 24 16:41:32 2010 -0700
@@ -381,7 +381,7 @@
      * {@link #getNumberInstance() getNumberInstance()}.
      */
     public final static NumberFormat getInstance() {
-        return getInstance(Locale.getDefault(), NUMBERSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
     }
 
     /**
@@ -397,7 +397,7 @@
      * Returns a general-purpose number format for the current default locale.
      */
     public final static NumberFormat getNumberInstance() {
-        return getInstance(Locale.getDefault(), NUMBERSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
     }
 
     /**
@@ -420,7 +420,7 @@
      * @since 1.4
      */
     public final static NumberFormat getIntegerInstance() {
-        return getInstance(Locale.getDefault(), INTEGERSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), INTEGERSTYLE);
     }
 
     /**
@@ -443,7 +443,7 @@
      * Returns a currency format for the current default locale.
      */
     public final static NumberFormat getCurrencyInstance() {
-        return getInstance(Locale.getDefault(), CURRENCYSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), CURRENCYSTYLE);
     }
 
     /**
@@ -457,7 +457,7 @@
      * Returns a percentage format for the current default locale.
      */
     public final static NumberFormat getPercentInstance() {
-        return getInstance(Locale.getDefault(), PERCENTSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), PERCENTSTYLE);
     }
 
     /**
@@ -471,7 +471,7 @@
      * Returns a scientific format for the current default locale.
      */
     /*public*/ final static NumberFormat getScientificInstance() {
-        return getInstance(Locale.getDefault(), SCIENTIFICSTYLE);
+        return getInstance(Locale.getDefault(Locale.Category.FORMAT), SCIENTIFICSTYLE);
     }
 
     /**
--- a/src/share/classes/java/text/SimpleDateFormat.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/text/SimpleDateFormat.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -55,6 +55,8 @@
 import sun.util.calendar.ZoneInfoFile;
 import sun.util.resources.LocaleData;
 
+import static java.text.DateFormatSymbols.*;
+
 /**
  * <code>SimpleDateFormat</code> is a concrete class for formatting and
  * parsing dates in a locale-sensitive manner. It allows for formatting
@@ -108,40 +110,50 @@
  *         <td><a href="#year">Year</a>
  *         <td><code>1996</code>; <code>96</code>
  *     <tr>
+ *         <td><code>Y</code>
+ *         <td>Week year
+ *         <td><a href="#year">Year</a>
+ *         <td><code>2009</code>; <code>09</code>
+ *     <tr bgcolor="#eeeeff">
  *         <td><code>M</code>
  *         <td>Month in year
  *         <td><a href="#month">Month</a>
  *         <td><code>July</code>; <code>Jul</code>; <code>07</code>
- *     <tr bgcolor="#eeeeff">
+ *     <tr>
  *         <td><code>w</code>
  *         <td>Week in year
  *         <td><a href="#number">Number</a>
  *         <td><code>27</code>
- *     <tr>
+ *     <tr bgcolor="#eeeeff">
  *         <td><code>W</code>
  *         <td>Week in month
  *         <td><a href="#number">Number</a>
  *         <td><code>2</code>
- *     <tr bgcolor="#eeeeff">
+ *     <tr>
  *         <td><code>D</code>
  *         <td>Day in year
  *         <td><a href="#number">Number</a>
  *         <td><code>189</code>
- *     <tr>
+ *     <tr bgcolor="#eeeeff">
  *         <td><code>d</code>
  *         <td>Day in month
  *         <td><a href="#number">Number</a>
  *         <td><code>10</code>
- *     <tr bgcolor="#eeeeff">
+ *     <tr>
  *         <td><code>F</code>
  *         <td>Day of week in month
  *         <td><a href="#number">Number</a>
  *         <td><code>2</code>
- *     <tr>
+ *     <tr bgcolor="#eeeeff">
  *         <td><code>E</code>
- *         <td>Day in week
+ *         <td>Day name in week
  *         <td><a href="#text">Text</a>
  *         <td><code>Tuesday</code>; <code>Tue</code>
+ *     <tr>
+ *         <td><code>u</code>
+ *         <td>Day number of week (1 = Monday, ..., 7 = Sunday)
+ *         <td><a href="#number">Number</a>
+ *         <td><code>1</code>
  *     <tr bgcolor="#eeeeff">
  *         <td><code>a</code>
  *         <td>Am/pm marker
@@ -192,6 +204,11 @@
  *         <td>Time zone
  *         <td><a href="#rfc822timezone">RFC 822 time zone</a>
  *         <td><code>-0800</code>
+ *     <tr bgcolor="#eeeeff">
+ *         <td><code>X</code>
+ *         <td>Time zone
+ *         <td><a href="#iso8601timezone">ISO 8601 time zone</a>
+ *         <td><code>-08</code>; <code>-0800</code>;  <code>-08:00</code>
  * </table>
  * </blockquote>
  * Pattern letters are usually repeated, as their number determines the
@@ -202,12 +219,12 @@
  *     the full form is used; otherwise a short or abbreviated form
  *     is used if available.
  *     For parsing, both forms are accepted, independent of the number
- *     of pattern letters.
+ *     of pattern letters.<br><br></li>
  * <li><strong><a name="number">Number:</a></strong>
  *     For formatting, the number of pattern letters is the minimum
  *     number of digits, and shorter numbers are zero-padded to this amount.
  *     For parsing, the number of pattern letters is ignored unless
- *     it's needed to separate two adjacent fields.
+ *     it's needed to separate two adjacent fields.<br><br></li>
  * <li><strong><a name="year">Year:</a></strong>
  *     If the formatter's {@link #getCalendar() Calendar} is the Gregorian
  *     calendar, the following rules are applied.<br>
@@ -239,11 +256,20 @@
  *     letters is 4 or more, a calendar specific {@linkplain
  *     Calendar#LONG long form} is used. Otherwise, a calendar
  *     specific {@linkplain Calendar#SHORT short or abbreviated form}
- *     is used.
+ *     is used.<br>
+ *     <br>
+ *     If week year {@code 'Y'} is specified and the {@linkplain
+ *     #getCalendar() calendar} doesn't support any <a
+ *     href="../util/GregorianCalendar.html#week_year"> week
+ *     years</a>, the calendar year ({@code 'y'}) is used instead. The
+ *     support of week years can be tested with a call to {@link
+ *     DateFormat#getCalendar() getCalendar()}.{@link
+ *     java.util.Calendar#isWeekDateSupported()
+ *     isWeekDateSupported()}.<br><br></li>
  * <li><strong><a name="month">Month:</a></strong>
  *     If the number of pattern letters is 3 or more, the month is
  *     interpreted as <a href="#text">text</a>; otherwise,
- *     it is interpreted as a <a href="#number">number</a>.
+ *     it is interpreted as a <a href="#number">number</a>.<br><br></li>
  * <li><strong><a name="timezone">General time zone:</a></strong>
  *     Time zones are interpreted as <a href="#text">text</a> if they have
  *     names. For time zones representing a GMT offset value, the
@@ -264,9 +290,10 @@
  *     00 and 59. The format is locale independent and digits must be taken
  *     from the Basic Latin block of the Unicode standard.
  *     <p>For parsing, <a href="#rfc822timezone">RFC 822 time zones</a> are also
- *     accepted.
+ *     accepted.<br><br></li>
  * <li><strong><a name="rfc822timezone">RFC 822 time zone:</a></strong>
  *     For formatting, the RFC 822 4-digit time zone format is used:
+ *
  *     <pre>
  *     <i>RFC822TimeZone:</i>
  *             <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
@@ -274,8 +301,41 @@
  *             <i>Digit Digit</i></pre>
  *     <i>TwoDigitHours</i> must be between 00 and 23. Other definitions
  *     are as for <a href="#timezone">general time zones</a>.
+ *
  *     <p>For parsing, <a href="#timezone">general time zones</a> are also
  *     accepted.
+ * <li><strong><a name="iso8601timezone">ISO 8601 Time zone:</a></strong>
+ *     The number of pattern letters designates the format for both formatting
+ *     and parsing as follows:
+ *     <pre>
+ *     <i>ISO8601TimeZone:</i>
+ *             <i>OneLetterISO8601TimeZone</i>
+ *             <i>TwoLetterISO8601TimeZone</i>
+ *             <i>ThreeLetterISO8601TimeZone</i>
+ *     <i>OneLetterISO8601TimeZone:</i>
+ *             <i>Sign</i> <i>TwoDigitHours</i>
+ *             {@code Z}
+ *     <i>TwoLetterISO8601TimeZone:</i>
+ *             <i>Sign</i> <i>TwoDigitHours</i> <i>Minutes</i>
+ *             {@code Z}
+ *     <i>ThreeLetterISO8601TimeZone:</i>
+ *             <i>Sign</i> <i>TwoDigitHours</i> {@code :} <i>Minutes</i>
+ *             {@code Z}</pre>
+ *     Other definitions are as for <a href="#timezone">general time zones</a> or
+ *     <a href="#rfc822timezone">RFC 822 time zones</a>.
+ *
+ *     <p>For formatting, if the offset value from GMT is 0, {@code "Z"} is
+ *     produced. If the number of pattern letters is 1, any fraction of an hour
+ *     is ignored. For example, if the pattern is {@code "X"} and the time zone is
+ *     {@code "GMT+05:30"}, {@code "+05"} is produced.
+ *
+ *     <p>For parsing, {@code "Z"} is parsed as the UTC time zone designator.
+ *     <a href="#timezone">General time zones</a> are <em>not</em> accepted.
+ *
+ *     <p>If the number of pattern letters is 4 or more, {@link
+ *     IllegalArgumentException} is thrown when constructing a {@code
+ *     SimpleDateFormat} or {@linkplain #applyPattern(String) applying a
+ *     pattern}.
  * </ul>
  * <code>SimpleDateFormat</code> also supports <em>localized date and time
  * pattern</em> strings. In these strings, the pattern letters described above
@@ -321,6 +381,12 @@
  *     <tr>
  *         <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSZ"</code>
  *         <td><code>2001-07-04T12:08:56.235-0700</code>
+ *     <tr bgcolor="#eeeeff">
+ *         <td><code>"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"</code>
+ *         <td><code>2001-07-04T12:08:56.235-07:00</code>
+ *     <tr>
+ *         <td><code>"YYYY-'W'ww-u"</code>
+ *         <td><code>2001-W27-3</code>
  * </table>
  * </blockquote>
  *
@@ -474,7 +540,7 @@
      * class.
      */
     public SimpleDateFormat() {
-        this(SHORT, SHORT, Locale.getDefault());
+        this(SHORT, SHORT, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -490,7 +556,7 @@
      */
     public SimpleDateFormat(String pattern)
     {
-        this(pattern, Locale.getDefault());
+        this(pattern, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -535,7 +601,7 @@
 
         this.pattern = pattern;
         this.formatData = (DateFormatSymbols) formatSymbols.clone();
-        this.locale = Locale.getDefault();
+        this.locale = Locale.getDefault(Locale.Category.FORMAT);
         initializeCalendar(this.locale);
         initialize(this.locale);
         useDateFormatSymbols = true;
@@ -815,6 +881,9 @@
      * Encodes the given tag and length and puts encoded char(s) into buffer.
      */
     private static final void encode(int tag, int length, StringBuilder buffer) {
+        if (tag == PATTERN_ISO_ZONE && length >= 4) {
+            throw new IllegalArgumentException("invalid ISO 8601 format: length=" + length);
+        }
         if (length < 255) {
             buffer.append((char)(tag << 8 | length));
         } else {
@@ -877,7 +946,7 @@
      * @param pos the formatting position. On input: an alignment field,
      * if desired. On output: the offsets of the alignment field.
      * @return the formatted date-time string.
-     * @exception NullPointerException if the given date is null
+     * @exception NullPointerException if the given {@code date} is {@code null}.
      */
     public StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldPosition pos)
@@ -968,6 +1037,10 @@
         Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK_IN_MONTH,
         Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH,
         Calendar.AM_PM, Calendar.HOUR, Calendar.HOUR, Calendar.ZONE_OFFSET,
+        Calendar.ZONE_OFFSET,
+        // Pseudo Calendar fields
+        CalendarBuilder.WEEK_YEAR,
+        CalendarBuilder.ISO_DAY_OF_WEEK,
         Calendar.ZONE_OFFSET
     };
 
@@ -982,6 +1055,8 @@
         DateFormat.WEEK_OF_MONTH_FIELD, DateFormat.AM_PM_FIELD,
         DateFormat.HOUR1_FIELD, DateFormat.HOUR0_FIELD,
         DateFormat.TIMEZONE_FIELD, DateFormat.TIMEZONE_FIELD,
+        DateFormat.YEAR_FIELD, DateFormat.DAY_OF_WEEK_FIELD,
+        DateFormat.TIMEZONE_FIELD
     };
 
     // Maps from DecimalFormatSymbols index to Field constant
@@ -993,6 +1068,8 @@
         Field.WEEK_OF_YEAR, Field.WEEK_OF_MONTH,
         Field.AM_PM, Field.HOUR1, Field.HOUR0, Field.TIME_ZONE,
         Field.TIME_ZONE,
+        Field.YEAR, Field.DAY_OF_WEEK,
+        Field.TIME_ZONE
     };
 
     /**
@@ -1007,9 +1084,24 @@
         int     beginOffset = buffer.length();
 
         int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
-        int value = calendar.get(field);
+        int value;
+        if (field == CalendarBuilder.WEEK_YEAR) {
+            if (calendar.isWeekDateSupported()) {
+                value = calendar.getWeekYear();
+            } else {
+                // use calendar year 'y' instead
+                patternCharIndex = PATTERN_YEAR;
+                field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
+                value = calendar.get(field);
+            }
+        } else if (field == CalendarBuilder.ISO_DAY_OF_WEEK) {
+            value = CalendarBuilder.toISODayOfWeek(calendar.get(Calendar.DAY_OF_WEEK));
+        } else {
+            value = calendar.get(field);
+        }
+
         int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
-        if (!useDateFormatSymbols) {
+        if (!useDateFormatSymbols && field != CalendarBuilder.ISO_DAY_OF_WEEK) {
             current = calendar.getDisplayName(field, style, locale);
         }
 
@@ -1018,7 +1110,7 @@
         // zeroPaddingNumber() must be fixed.
 
         switch (patternCharIndex) {
-        case 0: // 'G' - ERA
+        case PATTERN_ERA: // 'G'
             if (useDateFormatSymbols) {
                 String[] eras = formatData.getEras();
                 if (value < eras.length)
@@ -1028,7 +1120,8 @@
                 current = "";
             break;
 
-        case 1: // 'y' - YEAR
+        case PATTERN_WEEK_YEAR: // 'Y'
+        case PATTERN_YEAR:      // 'y'
             if (calendar instanceof GregorianCalendar) {
                 if (count != 2)
                     zeroPaddingNumber(value, count, maxIntCount, buffer);
@@ -1042,7 +1135,7 @@
             }
             break;
 
-        case 2: // 'M' - MONTH
+        case PATTERN_MONTH: // 'M'
             if (useDateFormatSymbols) {
                 String[] months;
                 if (count >= 4) {
@@ -1062,7 +1155,7 @@
             }
             break;
 
-        case 4: // 'k' - HOUR_OF_DAY: 1-based.  eg, 23:59 + 1 hour =>> 24:59
+        case PATTERN_HOUR_OF_DAY1: // 'k' 1-based.  eg, 23:59 + 1 hour =>> 24:59
             if (current == null) {
                 if (value == 0)
                     zeroPaddingNumber(calendar.getMaximum(Calendar.HOUR_OF_DAY)+1,
@@ -1072,7 +1165,7 @@
             }
             break;
 
-        case 9: // 'E' - DAY_OF_WEEK
+        case PATTERN_DAY_OF_WEEK: // 'E'
             if (useDateFormatSymbols) {
                 String[] weekdays;
                 if (count >= 4) {
@@ -1085,14 +1178,14 @@
             }
             break;
 
-        case 14:    // 'a' - AM_PM
+        case PATTERN_AM_PM:    // 'a'
             if (useDateFormatSymbols) {
                 String[] ampm = formatData.getAmPmStrings();
                 current = ampm[value];
             }
             break;
 
-        case 15: // 'h' - HOUR:1-based.  eg, 11PM + 1 hour =>> 12 AM
+        case PATTERN_HOUR1:    // 'h' 1-based.  eg, 11PM + 1 hour =>> 12 AM
             if (current == null) {
                 if (value == 0)
                     zeroPaddingNumber(calendar.getLeastMaximum(Calendar.HOUR)+1,
@@ -1102,7 +1195,7 @@
             }
             break;
 
-        case 17: // 'z' - ZONE_OFFSET
+        case PATTERN_ZONE_NAME: // 'z'
             if (current == null) {
                 if (formatData.locale == null || formatData.isZoneStringsSet) {
                     int zoneIndex =
@@ -1129,7 +1222,7 @@
             }
             break;
 
-        case 18: // 'Z' - ZONE_OFFSET ("-/+hhmm" form)
+        case PATTERN_ZONE_VALUE: // 'Z' ("-/+hhmm" form)
             value = (calendar.get(Calendar.ZONE_OFFSET) +
                      calendar.get(Calendar.DST_OFFSET)) / 60000;
 
@@ -1144,17 +1237,46 @@
             CalendarUtils.sprintf0d(buffer, num, width);
             break;
 
+        case PATTERN_ISO_ZONE:   // 'X'
+            value = calendar.get(Calendar.ZONE_OFFSET)
+                    + calendar.get(Calendar.DST_OFFSET);
+
+            if (value == 0) {
+                buffer.append('Z');
+                break;
+            }
+
+            value /=  60000;
+            if (value >= 0) {
+                buffer.append('+');
+            } else {
+                buffer.append('-');
+                value = -value;
+            }
+
+            CalendarUtils.sprintf0d(buffer, value / 60, 2);
+            if (count == 1) {
+                break;
+            }
+
+            if (count == 3) {
+                buffer.append(':');
+            }
+            CalendarUtils.sprintf0d(buffer, value % 60, 2);
+            break;
+
         default:
-            // case 3: // 'd' - DATE
-            // case 5: // 'H' - HOUR_OF_DAY:0-based.  eg, 23:59 + 1 hour =>> 00:59
-            // case 6: // 'm' - MINUTE
-            // case 7: // 's' - SECOND
-            // case 8: // 'S' - MILLISECOND
-            // case 10: // 'D' - DAY_OF_YEAR
-            // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
-            // case 12: // 'w' - WEEK_OF_YEAR
-            // case 13: // 'W' - WEEK_OF_MONTH
-            // case 16: // 'K' - HOUR: 0-based.  eg, 11PM + 1 hour =>> 0 AM
+     // case PATTERN_DAY_OF_MONTH:         // 'd'
+     // case PATTERN_HOUR_OF_DAY0:         // 'H' 0-based.  eg, 23:59 + 1 hour =>> 00:59
+     // case PATTERN_MINUTE:               // 'm'
+     // case PATTERN_SECOND:               // 's'
+     // case PATTERN_MILLISECOND:          // 'S'
+     // case PATTERN_DAY_OF_YEAR:          // 'D'
+     // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
+     // case PATTERN_WEEK_OF_YEAR:         // 'w'
+     // case PATTERN_WEEK_OF_MONTH:        // 'W'
+     // case PATTERN_HOUR0:                // 'K' eg, 11PM + 1 hour =>> 0 AM
+     // case PATTERN_ISO_DAY_OF_WEEK:      // 'u' pseudo field, Monday = 1, ..., Sunday = 7
             if (current == null) {
                 zeroPaddingNumber(value, count, maxIntCount, buffer);
             }
@@ -1264,10 +1386,9 @@
         int oldStart = start;
         int textLength = text.length();
 
-        calendar.clear(); // Clears all the time fields
-
         boolean[] ambiguousYear = {false};
 
+        CalendarBuilder calb = new CalendarBuilder();
 
         for (int i = 0; i < compiledPattern.length; ) {
             int tag = compiledPattern[i] >>> 8;
@@ -1340,7 +1461,7 @@
                 }
                 start = subParse(text, start, tag, count, obeyCount,
                                  ambiguousYear, pos,
-                                 useFollowingMinusSignAsDelimiter);
+                                 useFollowingMinusSignAsDelimiter, calb);
                 if (start < 0) {
                     pos.index = oldStart;
                     return null;
@@ -1354,46 +1475,16 @@
 
         pos.index = start;
 
-        // This part is a problem:  When we call parsedDate.after, we compute the time.
-        // Take the date April 3 2004 at 2:30 am.  When this is first set up, the year
-        // will be wrong if we're parsing a 2-digit year pattern.  It will be 1904.
-        // April 3 1904 is a Sunday (unlike 2004) so it is the DST onset day.  2:30 am
-        // is therefore an "impossible" time, since the time goes from 1:59 to 3:00 am
-        // on that day.  It is therefore parsed out to fields as 3:30 am.  Then we
-        // add 100 years, and get April 3 2004 at 3:30 am.  Note that April 3 2004 is
-        // a Saturday, so it can have a 2:30 am -- and it should. [LIU]
-        /*
-        Date parsedDate = calendar.getTime();
-        if( ambiguousYear[0] && !parsedDate.after(defaultCenturyStart) ) {
-            calendar.add(Calendar.YEAR, 100);
-            parsedDate = calendar.getTime();
-        }
-        */
-        // Because of the above condition, save off the fields in case we need to readjust.
-        // The procedure we use here is not particularly efficient, but there is no other
-        // way to do this given the API restrictions present in Calendar.  We minimize
-        // inefficiency by only performing this computation when it might apply, that is,
-        // when the two-digit year is equal to the start year, and thus might fall at the
-        // front or the back of the default century.  This only works because we adjust
-        // the year correctly to start with in other cases -- see subParse().
         Date parsedDate;
         try {
-            if (ambiguousYear[0]) // If this is true then the two-digit year == the default start year
-            {
-                // We need a copy of the fields, and we need to avoid triggering a call to
-                // complete(), which will recalculate the fields.  Since we can't access
-                // the fields[] array in Calendar, we clone the entire object.  This will
-                // stop working if Calendar.clone() is ever rewritten to call complete().
-                Calendar savedCalendar = (Calendar)calendar.clone();
-                parsedDate = calendar.getTime();
-                if (parsedDate.before(defaultCenturyStart))
-                {
-                    // We can't use add here because that does a complete() first.
-                    savedCalendar.set(Calendar.YEAR, defaultCenturyStartYear + 100);
-                    parsedDate = savedCalendar.getTime();
+            parsedDate = calb.establish(calendar).getTime();
+            // If the year value is ambiguous,
+            // then the two-digit year == the default start year
+            if (ambiguousYear[0]) {
+                if (parsedDate.before(defaultCenturyStart)) {
+                    parsedDate = calb.addYear(100).establish(calendar).getTime();
                 }
             }
-            else parsedDate = calendar.getTime();
         }
         // An IllegalArgumentException will be thrown by Calendar.getTime()
         // if any fields are out of range, e.g., MONTH == 17.
@@ -1415,7 +1506,7 @@
      * @return the new start position if matching succeeded; a negative number
      * indicating matching failure, otherwise.
      */
-    private int matchString(String text, int start, int field, String[] data)
+    private int matchString(String text, int start, int field, String[] data, CalendarBuilder calb)
     {
         int i = 0;
         int count = data.length;
@@ -1441,7 +1532,7 @@
         }
         if (bestMatch >= 0)
         {
-            calendar.set(field, bestMatch);
+            calb.set(field, bestMatch);
             return start + bestMatchLength;
         }
         return -start;
@@ -1452,7 +1543,8 @@
      * String[]). This method takes a Map<String, Integer> instead of
      * String[].
      */
-    private int matchString(String text, int start, int field, Map<String,Integer> data) {
+    private int matchString(String text, int start, int field,
+                            Map<String,Integer> data, CalendarBuilder calb) {
         if (data != null) {
             String bestMatch = null;
 
@@ -1466,7 +1558,7 @@
             }
 
             if (bestMatch != null) {
-                calendar.set(field, data.get(bestMatch));
+                calb.set(field, data.get(bestMatch));
                 return start + bestMatch.length();
             }
         }
@@ -1486,11 +1578,22 @@
         return -1;
     }
 
+    private boolean matchDSTString(String text, int start, int zoneIndex, int standardIndex,
+                                   String[][] zoneStrings) {
+        int index = standardIndex + 2;
+        String zoneName  = zoneStrings[zoneIndex][index];
+        if (text.regionMatches(true, start,
+                               zoneName, 0, zoneName.length())) {
+            return true;
+        }
+        return false;
+    }
+
     /**
      * find time zone 'text' matched zoneStrings and set to internal
      * calendar.
      */
-    private int subParseZoneString(String text, int start) {
+    private int subParseZoneString(String text, int start, CalendarBuilder calb) {
         boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
         TimeZone currentTimeZone = getTimeZone();
 
@@ -1524,6 +1627,7 @@
                 }
             }
         }
+
         if (tz == null) {
             int len = zoneStrings.length;
             for (int i = 0; i < len; i++) {
@@ -1549,8 +1653,8 @@
             // determine the local time. (6645292)
             int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
             if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
-                calendar.set(Calendar.ZONE_OFFSET, tz.getRawOffset());
-                calendar.set(Calendar.DST_OFFSET, dstAmount);
+                calb.set(Calendar.ZONE_OFFSET, tz.getRawOffset())
+                    .set(Calendar.DST_OFFSET, dstAmount);
             }
             return (start + zoneNames[nameIndex].length());
         }
@@ -1577,11 +1681,15 @@
     private int subParse(String text, int start, int patternCharIndex, int count,
                          boolean obeyCount, boolean[] ambiguousYear,
                          ParsePosition origPos,
-                         boolean useFollowingMinusSignAsDelimiter) {
+                         boolean useFollowingMinusSignAsDelimiter, CalendarBuilder calb) {
         Number number = null;
         int value = 0;
         ParsePosition pos = new ParsePosition(0);
         pos.index = start;
+        if (patternCharIndex == PATTERN_WEEK_YEAR && !calendar.isWeekDateSupported()) {
+            // use calendar year 'y' instead
+            patternCharIndex = PATTERN_YEAR;
+        }
         int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
 
         // If there are any spaces here, skip over them.  If we hit the end
@@ -1602,10 +1710,11 @@
             // a number value.  We handle further, more generic cases below.  We need
             // to handle some of them here because some fields require extra processing on
             // the parsed value.
-            if (patternCharIndex == 4 /* HOUR_OF_DAY1_FIELD */ ||
-                patternCharIndex == 15 /* HOUR1_FIELD */ ||
-                (patternCharIndex == 2 /* MONTH_FIELD */ && count <= 2) ||
-                patternCharIndex == 1 /* YEAR_FIELD */) {
+            if (patternCharIndex == PATTERN_HOUR_OF_DAY1 ||
+                patternCharIndex == PATTERN_HOUR1 ||
+                (patternCharIndex == PATTERN_MONTH && count <= 2) ||
+                patternCharIndex == PATTERN_YEAR ||
+                patternCharIndex == PATTERN_WEEK_YEAR) {
                 // It would be good to unify this with the obeyCount logic below,
                 // but that's going to be difficult.
                 if (obeyCount) {
@@ -1617,7 +1726,7 @@
                     number = numberFormat.parse(text, pos);
                 }
                 if (number == null) {
-                    if (patternCharIndex != 1 || calendar instanceof GregorianCalendar) {
+                    if (patternCharIndex != PATTERN_YEAR || calendar instanceof GregorianCalendar) {
                         break parsing;
                     }
                 } else {
@@ -1638,33 +1747,34 @@
 
             int index;
             switch (patternCharIndex) {
-            case 0: // 'G' - ERA
+            case PATTERN_ERA: // 'G'
                 if (useDateFormatSymbols) {
-                    if ((index = matchString(text, start, Calendar.ERA, formatData.getEras())) > 0) {
+                    if ((index = matchString(text, start, Calendar.ERA, formatData.getEras(), calb)) > 0) {
                         return index;
                     }
                 } else {
                     Map<String, Integer> map = calendar.getDisplayNames(field,
                                                                         Calendar.ALL_STYLES,
                                                                         locale);
-                    if ((index = matchString(text, start, field, map)) > 0) {
+                    if ((index = matchString(text, start, field, map, calb)) > 0) {
                         return index;
                     }
                 }
                 break parsing;
 
-            case 1: // 'y' - YEAR
+            case PATTERN_WEEK_YEAR: // 'Y'
+            case PATTERN_YEAR:      // 'y'
                 if (!(calendar instanceof GregorianCalendar)) {
                     // calendar might have text representations for year values,
                     // such as "\u5143" in JapaneseImperialCalendar.
                     int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
                     Map<String, Integer> map = calendar.getDisplayNames(field, style, locale);
                     if (map != null) {
-                        if ((index = matchString(text, start, field, map)) > 0) {
+                        if ((index = matchString(text, start, field, map, calb)) > 0) {
                             return index;
                         }
                     }
-                    calendar.set(field, value);
+                    calb.set(field, value);
                     return pos.index;
                 }
 
@@ -1676,8 +1786,7 @@
                 // is treated literally:  "2250", "-1", "1", "002".
                 if (count <= 2 && (pos.index - start) == 2
                     && Character.isDigit(text.charAt(start))
-                    && Character.isDigit(text.charAt(start+1)))
-                {
+                    && Character.isDigit(text.charAt(start+1))) {
                     // Assume for example that the defaultCenturyStart is 6/18/1903.
                     // This means that two-digit years will be forced into the range
                     // 6/18/1903 to 6/17/2003.  As a result, years 00, 01, and 02
@@ -1691,16 +1800,16 @@
                     value += (defaultCenturyStartYear/100)*100 +
                         (value < ambiguousTwoDigitYear ? 100 : 0);
                 }
-                calendar.set(Calendar.YEAR, value);
+                calb.set(field, value);
                 return pos.index;
 
-            case 2: // 'M' - MONTH
+            case PATTERN_MONTH: // 'M'
                 if (count <= 2) // i.e., M or MM.
                 {
                     // Don't want to parse the month if it is a string
                     // while pattern uses numeric style: M or MM.
                     // [We computed 'value' above.]
-                    calendar.set(Calendar.MONTH, value - 1);
+                    calb.set(Calendar.MONTH, value - 1);
                     return pos.index;
                 }
 
@@ -1710,50 +1819,50 @@
                     // Try count == 4 first:
                     int newStart = 0;
                     if ((newStart = matchString(text, start, Calendar.MONTH,
-                                                formatData.getMonths())) > 0) {
+                                                formatData.getMonths(), calb)) > 0) {
                         return newStart;
                     }
                     // count == 4 failed, now try count == 3
                     if ((index = matchString(text, start, Calendar.MONTH,
-                                             formatData.getShortMonths())) > 0) {
+                                             formatData.getShortMonths(), calb)) > 0) {
                         return index;
                     }
                 } else {
                     Map<String, Integer> map = calendar.getDisplayNames(field,
                                                                         Calendar.ALL_STYLES,
                                                                         locale);
-                    if ((index = matchString(text, start, field, map)) > 0) {
+                    if ((index = matchString(text, start, field, map, calb)) > 0) {
                         return index;
                     }
                 }
                 break parsing;
 
-            case 4: // 'k' - HOUR_OF_DAY: 1-based.  eg, 23:59 + 1 hour =>> 24:59
+            case PATTERN_HOUR_OF_DAY1: // 'k' 1-based.  eg, 23:59 + 1 hour =>> 24:59
                 // [We computed 'value' above.]
                 if (value == calendar.getMaximum(Calendar.HOUR_OF_DAY)+1) value = 0;
-                calendar.set(Calendar.HOUR_OF_DAY, value);
+                calb.set(Calendar.HOUR_OF_DAY, value);
                 return pos.index;
 
-            case 9:
-                { // 'E' - DAY_OF_WEEK
+            case PATTERN_DAY_OF_WEEK:  // 'E'
+                {
                     if (useDateFormatSymbols) {
                         // Want to be able to parse both short and long forms.
                         // Try count == 4 (DDDD) first:
                         int newStart = 0;
                         if ((newStart=matchString(text, start, Calendar.DAY_OF_WEEK,
-                                                  formatData.getWeekdays())) > 0) {
+                                                  formatData.getWeekdays(), calb)) > 0) {
                             return newStart;
                         }
                         // DDDD failed, now try DDD
                         if ((index = matchString(text, start, Calendar.DAY_OF_WEEK,
-                                                 formatData.getShortWeekdays())) > 0) {
+                                                 formatData.getShortWeekdays(), calb)) > 0) {
                             return index;
                         }
                     } else {
                         int[] styles = { Calendar.LONG, Calendar.SHORT };
                         for (int style : styles) {
                             Map<String,Integer> map = calendar.getDisplayNames(field, style, locale);
-                            if ((index = matchString(text, start, field, map)) > 0) {
+                            if ((index = matchString(text, start, field, map, calb)) > 0) {
                                 return index;
                             }
                         }
@@ -1761,27 +1870,28 @@
                 }
                 break parsing;
 
-            case 14:    // 'a' - AM_PM
+            case PATTERN_AM_PM:    // 'a'
                 if (useDateFormatSymbols) {
-                    if ((index = matchString(text, start, Calendar.AM_PM, formatData.getAmPmStrings())) > 0) {
+                    if ((index = matchString(text, start, Calendar.AM_PM,
+                                             formatData.getAmPmStrings(), calb)) > 0) {
                         return index;
                     }
                 } else {
                     Map<String,Integer> map = calendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
-                    if ((index = matchString(text, start, field, map)) > 0) {
+                    if ((index = matchString(text, start, field, map, calb)) > 0) {
                         return index;
                     }
                 }
                 break parsing;
 
-            case 15: // 'h' - HOUR:1-based.  eg, 11PM + 1 hour =>> 12 AM
+            case PATTERN_HOUR1: // 'h' 1-based.  eg, 11PM + 1 hour =>> 12 AM
                 // [We computed 'value' above.]
                 if (value == calendar.getLeastMaximum(Calendar.HOUR)+1) value = 0;
-                calendar.set(Calendar.HOUR, value);
+                calb.set(Calendar.HOUR, value);
                 return pos.index;
 
-            case 17: // 'z' - ZONE_OFFSET
-            case 18: // 'Z' - ZONE_OFFSET
+            case PATTERN_ZONE_NAME:  // 'z'
+            case PATTERN_ZONE_VALUE: // 'Z'
                 // First try to parse generic forms such as GMT-07:00. Do this first
                 // in case localized TimeZoneNames contains the string "GMT"
                 // for a zone; in that case, we don't want to match the first three
@@ -1797,7 +1907,7 @@
                     if ((text.length() - start) >= GMT.length() &&
                         text.regionMatches(true, start, GMT, 0, GMT.length())) {
                         int num;
-                        calendar.set(Calendar.DST_OFFSET, 0);
+                        calb.set(Calendar.DST_OFFSET, 0);
                         pos.index = start + GMT.length();
 
                         try { // try-catch for "GMT" only time zone string
@@ -1810,8 +1920,8 @@
                         }
                         catch(StringIndexOutOfBoundsException e) {}
 
-                        if (sign == 0) {        /* "GMT" without offset */
-                            calendar.set(Calendar.ZONE_OFFSET, 0);
+                        if (sign == 0) {    /* "GMT" without offset */
+                            calb.set(Calendar.ZONE_OFFSET, 0);
                             return pos.index;
                         }
 
@@ -1875,7 +1985,7 @@
                                 sign = -1;
                             } else {
                                 // Try parsing the text as a time zone name (abbr).
-                                int i = subParseZoneString(text, pos.index);
+                                int i = subParseZoneString(text, pos.index, calb);
                                 if (i != 0) {
                                     return i;
                                 }
@@ -1933,24 +2043,112 @@
                     // arrive here if the form GMT+/-... or an RFC 822 form was seen.
                     if (sign != 0) {
                         offset *= MILLIS_PER_MINUTE * sign;
-                        calendar.set(Calendar.ZONE_OFFSET, offset);
-                        calendar.set(Calendar.DST_OFFSET, 0);
+                        calb.set(Calendar.ZONE_OFFSET, offset).set(Calendar.DST_OFFSET, 0);
+                        return ++pos.index;
+                    }
+                }
+                break parsing;
+
+            case PATTERN_ISO_ZONE:   // 'X'
+                {
+                    int sign = 0;
+                    int offset = 0;
+
+                    iso8601: {
+                        try {
+                            char c = text.charAt(pos.index);
+                            if (c == 'Z') {
+                                calb.set(Calendar.ZONE_OFFSET, 0).set(Calendar.DST_OFFSET, 0);
+                                return ++pos.index;
+                            }
+
+                            // parse text as "+/-hh[[:]mm]" based on count
+                            if (c == '+') {
+                                sign = 1;
+                            } else if (c == '-') {
+                                sign = -1;
+                            }
+                            // Look for hh.
+                            int hours = 0;
+                            c = text.charAt(++pos.index);
+                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
+                                break parsing;
+                            }
+                            hours = c - '0';
+                            c = text.charAt(++pos.index);
+                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
+                                break parsing;
+                            }
+                            hours *= 10;
+                            hours += c - '0';
+                            if (hours > 23) {
+                                break parsing;
+                            }
+
+                            if (count == 1) { // "X"
+                                offset = hours * 60;
+                                break iso8601;
+                            }
+
+                            c = text.charAt(++pos.index);
+                            // Skip ':' if "XXX"
+                            if (c == ':') {
+                                if (count == 2) {
+                                    break parsing;
+                                }
+                                c = text.charAt(++pos.index);
+                            } else {
+                                if (count == 3) {
+                                    // missing ':'
+                                    break parsing;
+                                }
+                            }
+
+                            // Look for mm.
+                            int minutes = 0;
+                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
+                                break parsing;
+                            }
+                            minutes = c - '0';
+                            c = text.charAt(++pos.index);
+                            if (c < '0' || c > '9') { /* must be from '0' to '9'. */
+                                break parsing;
+                            }
+                            minutes *= 10;
+                            minutes += c - '0';
+
+                            if (minutes > 59) {
+                                break parsing;
+                            }
+
+                            offset = hours * 60 + minutes;
+                        } catch (StringIndexOutOfBoundsException e) {
+                            break parsing;
+                        }
+                    }
+
+                    // Do the final processing for both of the above cases.  We only
+                    // arrive here if the form GMT+/-... or an RFC 822 form was seen.
+                    if (sign != 0) {
+                        offset *= MILLIS_PER_MINUTE * sign;
+                        calb.set(Calendar.ZONE_OFFSET, offset).set(Calendar.DST_OFFSET, 0);
                         return ++pos.index;
                     }
                 }
                 break parsing;
 
             default:
-                // case 3: // 'd' - DATE
-                // case 5: // 'H' - HOUR_OF_DAY:0-based.  eg, 23:59 + 1 hour =>> 00:59
-                // case 6: // 'm' - MINUTE
-                // case 7: // 's' - SECOND
-                // case 8: // 'S' - MILLISECOND
-                // case 10: // 'D' - DAY_OF_YEAR
-                // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
-                // case 12: // 'w' - WEEK_OF_YEAR
-                // case 13: // 'W' - WEEK_OF_MONTH
-                // case 16: // 'K' - HOUR: 0-based.  eg, 11PM + 1 hour =>> 0 AM
+         // case PATTERN_DAY_OF_MONTH:         // 'd'
+         // case PATTERN_HOUR_OF_DAY0:         // 'H' 0-based.  eg, 23:59 + 1 hour =>> 00:59
+         // case PATTERN_MINUTE:               // 'm'
+         // case PATTERN_SECOND:               // 's'
+         // case PATTERN_MILLISECOND:          // 'S'
+         // case PATTERN_DAY_OF_YEAR:          // 'D'
+         // case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
+         // case PATTERN_WEEK_OF_YEAR:         // 'w'
+         // case PATTERN_WEEK_OF_MONTH:        // 'W'
+         // case PATTERN_HOUR0:                // 'K' 0-based.  eg, 11PM + 1 hour =>> 0 AM
+         // case PATTERN_ISO_DAY_OF_WEEK:      // 'u' (pseudo field);
 
                 // Handle "generic" fields
                 if (obeyCount) {
@@ -1973,7 +2171,7 @@
                         pos.index--;
                     }
 
-                    calendar.set(field, value);
+                    calb.set(field, value);
                     return pos.index;
                 }
                 break parsing;
@@ -2020,11 +2218,18 @@
                     inQuote = true;
                 else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                     int ci = from.indexOf(c);
-                    if (ci == -1)
+                    if (ci >= 0) {
+                        // patternChars is longer than localPatternChars due
+                        // to serialization compatibility. The pattern letters
+                        // unsupported by localPatternChars pass through.
+                        if (ci < to.length()) {
+                            c = to.charAt(ci);
+                        }
+                    } else {
                         throw new IllegalArgumentException("Illegal pattern " +
                                                            " character '" +
                                                            c + "'");
-                    c = to.charAt(ci);
+                    }
                 }
             }
             result.append(c);
@@ -2061,7 +2266,7 @@
      * @exception NullPointerException if the given pattern is null
      * @exception IllegalArgumentException if the given pattern is invalid
      */
-    public void applyPattern (String pattern)
+    public void applyPattern(String pattern)
     {
         compiledPattern = compile(pattern);
         this.pattern = pattern;
--- a/src/share/classes/java/util/Calendar.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/Calendar.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -119,7 +119,7 @@
  * calculating its time or calendar field values if any out-of-range field
  * value has been set.
  *
- * <h4>First Week</h4>
+ * <h4><a name="first_week">First Week</a></h4>
  *
  * <code>Calendar</code> defines a locale-specific seven day week using two
  * parameters: the first day of the week and the minimal days in first week
@@ -933,7 +933,7 @@
      */
     protected Calendar()
     {
-        this(TimeZone.getDefaultRef(), Locale.getDefault());
+        this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
         sharedZone = true;
     }
 
@@ -962,7 +962,7 @@
      */
     public static Calendar getInstance()
     {
-        Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault());
+        Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
         cal.sharedZone = true;
         return cal;
     }
@@ -977,7 +977,7 @@
      */
     public static Calendar getInstance(TimeZone zone)
     {
-        return createCalendar(zone, Locale.getDefault());
+        return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1013,19 +1013,30 @@
     private static Calendar createCalendar(TimeZone zone,
                                            Locale aLocale)
     {
-        // If the specified locale is a Thai locale, returns a BuddhistCalendar
-        // instance.
-        if ("th".equals(aLocale.getLanguage())
-            && ("TH".equals(aLocale.getCountry()))) {
-            return new sun.util.BuddhistCalendar(zone, aLocale);
-        } else if ("JP".equals(aLocale.getVariant())
-                   && "JP".equals(aLocale.getCountry())
-                   && "ja".equals(aLocale.getLanguage())) {
-            return new JapaneseImperialCalendar(zone, aLocale);
+        Calendar cal = null;
+
+        String caltype = aLocale.getUnicodeLocaleType("ca");
+        if (caltype == null) {
+            // Calendar type is not specified.
+            // If the specified locale is a Thai locale,
+            // returns a BuddhistCalendar instance.
+            if ("th".equals(aLocale.getLanguage())
+                    && ("TH".equals(aLocale.getCountry()))) {
+                    cal = new BuddhistCalendar(zone, aLocale);
+            } else {
+                cal = new GregorianCalendar(zone, aLocale);
+            }
+        } else if (caltype.equals("japanese")) {
+            cal = new JapaneseImperialCalendar(zone, aLocale);
+        } else if (caltype.equals("buddhist")) {
+            cal = new BuddhistCalendar(zone, aLocale);
+        } else {
+            // Unsupported calendar type.
+            // Use Gregorian calendar as a fallback.
+            cal = new GregorianCalendar(zone, aLocale);
         }
 
-        // else create the default calendar
-        return new GregorianCalendar(zone, aLocale);
+        return cal;
     }
 
     /**
@@ -2196,6 +2207,101 @@
     }
 
     /**
+     * Returns whether this {@code Calendar} supports week dates.
+     *
+     * <p>The default implementation of this method returns {@code false}.
+     *
+     * @return {@code true} if this {@code Calendar} supports week dates;
+     *         {@code false} otherwise.
+     * @see #getWeekYear()
+     * @see #setWeekDate(int,int,int)
+     * @see #getWeeksInWeekYear()
+     * @since 1.7
+     */
+    public boolean isWeekDateSupported() {
+        return false;
+    }
+
+    /**
+     * Returns the week year represented by this {@code Calendar}. The
+     * week year is in sync with the week cycle. The {@linkplain
+     * #getFirstDayOfWeek() first day of the first week} is the first
+     * day of the week year.
+     *
+     * <p>The default implementation of this method throws an
+     * {@link UnsupportedOperationException}.
+     *
+     * @return the week year of this {@code Calendar}
+     * @exception UnsupportedOperationException
+     *            if any week year numbering isn't supported
+     *            in this {@code Calendar}.
+     * @see #isWeekDateSupported()
+     * @see #getFirstDayOfWeek()
+     * @see #getMinimalDaysInFirstWeek()
+     * @since 1.7
+     */
+    public int getWeekYear() {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Sets the date of this {@code Calendar} with the the given date
+     * specifiers - week year, week of year, and day of week.
+     *
+     * <p>Unlike the {@code set} method, all of the calendar fields
+     * and {@code time} values are calculated upon return.
+     *
+     * <p>If {@code weekOfYear} is out of the valid week-of-year range
+     * in {@code weekYear}, the {@code weekYear} and {@code
+     * weekOfYear} values are adjusted in lenient mode, or an {@code
+     * IllegalArgumentException} is thrown in non-lenient mode.
+     *
+     * <p>The default implementation of this method throws an
+     * {@code UnsupportedOperationException}.
+     *
+     * @param weekYear   the week year
+     * @param weekOfYear the week number based on {@code weekYear}
+     * @param dayOfWeek  the day of week value: one of the constants
+     *                   for the {@link #DAY_OF_WEEK} field: {@link
+     *                   #SUNDAY}, ..., {@link #SATURDAY}.
+     * @exception IllegalArgumentException
+     *            if any of the given date specifiers is invalid
+     *            or any of the calendar fields are inconsistent
+     *            with the given date specifiers in non-lenient mode
+     * @exception UnsupportedOperationException
+     *            if any week year numbering isn't supported in this
+     *            {@code Calendar}.
+     * @see #isWeekDateSupported()
+     * @see #getFirstDayOfWeek()
+     * @see #getMinimalDaysInFirstWeek()
+     * @since 1.7
+     */
+    public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Returns the number of weeks in the week year represented by this
+     * {@code Calendar}.
+     *
+     * <p>The default implementation of this method throws an
+     * {@code UnsupportedOperationException}.
+     *
+     * @return the number of weeks in the week year.
+     * @exception UnsupportedOperationException
+     *            if any week year numbering isn't supported in this
+     *            {@code Calendar}.
+     * @see #WEEK_OF_YEAR
+     * @see #isWeekDateSupported()
+     * @see #getWeekYear()
+     * @see #getActualMaximum(int)
+     * @since 1.7
+     */
+    public int getWeeksInWeekYear() {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
      * Returns the minimum value for the given calendar field of this
      * <code>Calendar</code> instance. The minimum value is defined as
      * the smallest value returned by the {@link #get(int) get} method
--- a/src/share/classes/java/util/ConcurrentModificationException.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/ConcurrentModificationException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -49,9 +49,9 @@
  * <p>Note that fail-fast behavior cannot be guaranteed as it is, generally
  * speaking, impossible to make any hard guarantees in the presence of
  * unsynchronized concurrent modification.  Fail-fast operations
- * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
+ * throw {@code ConcurrentModificationException} on a best-effort basis.
  * Therefore, it would be wrong to write a program that depended on this
- * exception for its correctness: <i><tt>ConcurrentModificationException</tt>
+ * exception for its correctness: <i>{@code ConcurrentModificationException}
  * should be used only to detect bugs.</i>
  *
  * @author  Josh Bloch
@@ -77,7 +77,7 @@
     }
 
     /**
-     * Constructs a <tt>ConcurrentModificationException</tt> with the
+     * Constructs a {@code ConcurrentModificationException} with the
      * specified detail message.
      *
      * @param message the detail message pertaining to this exception.
@@ -85,4 +85,39 @@
     public ConcurrentModificationException(String message) {
         super(message);
     }
+
+    /**
+     * Constructs a new exception with the specified cause and a detail
+     * message of {@code (cause==null ? null : cause.toString())} (which
+     * typically contains the class and detail message of {@code cause}.
+     *
+     * @param  cause the cause (which is saved for later retrieval by the
+     *         {@link Throwable#getCause()} method).  (A {@code null} value is
+     *         permitted, and indicates that the cause is nonexistent or
+     *         unknown.)
+     * @since  1.7
+     */
+    public ConcurrentModificationException(Throwable cause) {
+        super(cause);
+    }
+
+    /**
+     * Constructs a new exception with the specified detail message and
+     * cause.
+     *
+     * <p>Note that the detail message associated with <code>cause</code> is
+     * <i>not</i> automatically incorporated in this exception's detail
+     * message.
+     *
+     * @param  message the detail message (which is saved for later retrieval
+     *         by the {@link Throwable#getMessage()} method).
+     * @param  cause the cause (which is saved for later retrieval by the
+     *         {@link Throwable#getCause()} method).  (A {@code null} value
+     *         is permitted, and indicates that the cause is nonexistent or
+     *         unknown.)
+     * @since 1.7
+     */
+    public ConcurrentModificationException(String message, Throwable cause) {
+        super(message, cause);
+    }
 }
--- a/src/share/classes/java/util/Currency.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/Currency.java	Fri Sep 24 16:41:32 2010 -0700
@@ -452,7 +452,7 @@
      * @return the symbol of this currency for the default locale
      */
     public String getSymbol() {
-        return getSymbol(Locale.getDefault());
+        return getSymbol(Locale.getDefault(Locale.Category.DISPLAY));
     }
 
     /**
@@ -528,7 +528,7 @@
      * @since 1.7
      */
     public String getDisplayName() {
-        return getDisplayName(Locale.getDefault());
+        return getDisplayName(Locale.getDefault(Locale.Category.DISPLAY));
     }
 
     /**
--- a/src/share/classes/java/util/Formatter.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/Formatter.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1866,7 +1866,7 @@
      * virtual machine.
      */
     public Formatter() {
-        init(new StringBuilder(), Locale.getDefault());
+        init(new StringBuilder(), Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1882,7 +1882,7 @@
     public Formatter(Appendable a) {
         if (a == null)
             a = new StringBuilder();
-        init(a, Locale.getDefault());
+        init(a, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1949,7 +1949,7 @@
      */
     public Formatter(String fileName) throws FileNotFoundException {
         init(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
-             Locale.getDefault());
+             Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1985,7 +1985,7 @@
     public Formatter(String fileName, String csn)
         throws FileNotFoundException, UnsupportedEncodingException
     {
-        this(fileName, csn, Locale.getDefault());
+        this(fileName, csn, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2057,7 +2057,7 @@
      */
     public Formatter(File file) throws FileNotFoundException {
         init(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
-             Locale.getDefault());
+             Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2093,7 +2093,7 @@
     public Formatter(File file, String csn)
         throws FileNotFoundException, UnsupportedEncodingException
     {
-        this(file, csn, Locale.getDefault());
+        this(file, csn, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2152,7 +2152,7 @@
     public Formatter(PrintStream ps) {
         if (ps == null)
             throw new NullPointerException();
-        init((Appendable)ps, Locale.getDefault());
+        init((Appendable)ps, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2171,7 +2171,7 @@
      */
     public Formatter(OutputStream os) {
         init(new BufferedWriter(new OutputStreamWriter(os)),
-             Locale.getDefault());
+             Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2195,7 +2195,7 @@
     public Formatter(OutputStream os, String csn)
         throws UnsupportedEncodingException
     {
-        this(os, csn, Locale.getDefault());
+        this(os, csn, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
--- a/src/share/classes/java/util/GregorianCalendar.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/GregorianCalendar.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -88,23 +88,49 @@
  * adjustment may be made if desired for dates that are prior to the Gregorian
  * changeover and which fall between January 1 and March 24.
  *
- * <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to
- * 53.  Week 1 for a year is the earliest seven day period starting on
- * <code>getFirstDayOfWeek()</code> that contains at least
- * <code>getMinimalDaysInFirstWeek()</code> days from that year.  It thus
- * depends on the values of <code>getMinimalDaysInFirstWeek()</code>,
- * <code>getFirstDayOfWeek()</code>, and the day of the week of January 1.
- * Weeks between week 1 of one year and week 1 of the following year are
- * numbered sequentially from 2 to 52 or 53 (as needed).
-
- * <p>For example, January 1, 1998 was a Thursday.  If
- * <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and
- * <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values
- * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts
- * on December 29, 1997, and ends on January 4, 1998.  If, however,
- * <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998
- * starts on January 4, 1998, and ends on January 10, 1998; the first three days
- * of 1998 then are part of week 53 of 1997.
+ * <h4><a name="week_and_year">Week Of Year and Week Year</a></h4>
+ *
+ * <p>Values calculated for the {@link Calendar#WEEK_OF_YEAR
+ * WEEK_OF_YEAR} field range from 1 to 53. The first week of a
+ * calendar year is the earliest seven day period starting on {@link
+ * Calendar#getFirstDayOfWeek() getFirstDayOfWeek()} that contains at
+ * least {@link Calendar#getMinimalDaysInFirstWeek()
+ * getMinimalDaysInFirstWeek()} days from that year. It thus depends
+ * on the values of {@code getMinimalDaysInFirstWeek()}, {@code
+ * getFirstDayOfWeek()}, and the day of the week of January 1. Weeks
+ * between week 1 of one year and week 1 of the following year
+ * (exclusive) are numbered sequentially from 2 to 52 or 53 (except
+ * for year(s) involved in the Julian-Gregorian transition).
+ *
+ * <p>The {@code getFirstDayOfWeek()} and {@code
+ * getMinimalDaysInFirstWeek()} values are initialized using
+ * locale-dependent resources when constructing a {@code
+ * GregorianCalendar}. <a name="iso8601_compatible_setting">The week
+ * determination is compatible</a> with the ISO 8601 standard when {@code
+ * getFirstDayOfWeek()} is {@code MONDAY} and {@code
+ * getMinimalDaysInFirstWeek()} is 4, which values are used in locales
+ * where the standard is preferred. These values can explicitly be set by
+ * calling {@link Calendar#setFirstDayOfWeek(int) setFirstDayOfWeek()} and
+ * {@link Calendar#setMinimalDaysInFirstWeek(int)
+ * setMinimalDaysInFirstWeek()}.
+ *
+ * <p>A <a name="week_year"><em>week year</em></a> is in sync with a
+ * {@code WEEK_OF_YEAR} cycle. All weeks between the first and last
+ * weeks (inclusive) have the same <em>week year</em> value.
+ * Therefore, the first and last days of a week year may have
+ * different calendar year values.
+ *
+ * <p>For example, January 1, 1998 is a Thursday. If {@code
+ * getFirstDayOfWeek()} is {@code MONDAY} and {@code
+ * getMinimalDaysInFirstWeek()} is 4 (ISO 8601 standard compatible
+ * setting), then week 1 of 1998 starts on December 29, 1997, and ends
+ * on January 4, 1998. The week year is 1998 for the last three days
+ * of calendar year 1997. If, however, {@code getFirstDayOfWeek()} is
+ * {@code SUNDAY}, then week 1 of 1998 starts on January 4, 1998, and
+ * ends on January 10, 1998; the first three days of 1998 then are
+ * part of week 53 of 1997 and their week year is 1997.
+ *
+ * <h4>Week Of Month</h4>
  *
  * <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0
  * to 6.  Week 1 of a month (the days with <code>WEEK_OF_MONTH =
@@ -124,7 +150,9 @@
  * <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1
  * through January 3 have a <code>WEEK_OF_MONTH</code> of 1.
  *
- * <p>The <code>clear</code> methods set calendar field(s)
+ * <h4>Default Fields Values</h4>
+ *
+ * <p>The <code>clear</code> method sets calendar field(s)
  * undefined. <code>GregorianCalendar</code> uses the following
  * default value for each calendar field if its value is undefined.
  *
@@ -555,7 +583,7 @@
      * in the default time zone with the default locale.
      */
     public GregorianCalendar() {
-        this(TimeZone.getDefaultRef(), Locale.getDefault());
+        this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
         setZoneShared(true);
     }
 
@@ -566,7 +594,7 @@
      * @param zone the given time zone.
      */
     public GregorianCalendar(TimeZone zone) {
-        this(zone, Locale.getDefault());
+        this(zone, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -1625,6 +1653,13 @@
      * is 29 because 2004 is a leap year, and if the date of this
      * instance is February 1, 2005, it's 28.
      *
+     * <p>This method calculates the maximum value of {@link
+     * Calendar#WEEK_OF_YEAR WEEK_OF_YEAR} based on the {@link
+     * Calendar#YEAR YEAR} (calendar year) value, not the <a
+     * href="#week_year">week year</a>. Call {@link
+     * #getWeeksInWeekYear()} to get the maximum value of {@code
+     * WEEK_OF_YEAR} in the week year of this {@code GregorianCalendar}.
+     *
      * @param field the calendar field
      * @return the maximum of the given field for the time value of
      * this <code>GregorianCalendar</code>
@@ -1742,8 +1777,13 @@
                 if (gc == this) {
                     gc = (GregorianCalendar) gc.clone();
                 }
-                gc.set(DAY_OF_YEAR, getActualMaximum(DAY_OF_YEAR));
+                int maxDayOfYear = getActualMaximum(DAY_OF_YEAR);
+                gc.set(DAY_OF_YEAR, maxDayOfYear);
                 value = gc.get(WEEK_OF_YEAR);
+                if (internalGet(YEAR) != gc.getWeekYear()) {
+                    gc.set(DAY_OF_YEAR, maxDayOfYear - 7);
+                    value = gc.get(WEEK_OF_YEAR);
+                }
             }
             break;
 
@@ -1934,46 +1974,241 @@
         }
     }
 
-//////////////////////
-// Proposed public API
-//////////////////////
+    /**
+     * Returns {@code true} indicating this {@code GregorianCalendar}
+     * supports week dates.
+     *
+     * @return {@code true} (always)
+     * @see #getWeekYear()
+     * @see #setWeekDate(int,int,int)
+     * @see #getWeeksInWeekYear()
+     * @since 1.7
+     */
+    @Override
+    public final boolean isWeekDateSupported() {
+        return true;
+    }
 
     /**
-     * Returns the year that corresponds to the <code>WEEK_OF_YEAR</code> field.
-     * This may be one year before or after the Gregorian or Julian year stored
-     * in the <code>YEAR</code> field.  For example, January 1, 1999 is considered
-     * Friday of week 53 of 1998 (if minimal days in first week is
-     * 2 or less, and the first day of the week is Sunday).  Given
-     * these same settings, the ISO year of January 1, 1999 is
-     * 1998.
+     * Returns the <a href="#week_year">week year</a> represented by this
+     * {@code GregorianCalendar}. The dates in the weeks between 1 and the
+     * maximum week number of the week year have the same week year value
+     * that may be one year before or after the {@link Calendar#YEAR YEAR}
+     * (calendar year) value.
      *
-     * <p>This method calls {@link Calendar#complete} before
-     * calculating the week-based year.
+     * <p>This method calls {@link Calendar#complete()} before
+     * calculating the week year.
      *
-     * @return the year corresponding to the <code>WEEK_OF_YEAR</code> field, which
-     * may be one year before or after the <code>YEAR</code> field.
-     * @see #YEAR
-     * @see #WEEK_OF_YEAR
+     * @return the week year represented by this {@code GregorianCalendar}.
+     *         If the {@link Calendar#ERA ERA} value is {@link #BC}, the year is
+     *         represented by 0 or a negative number: BC 1 is 0, BC 2
+     *         is -1, BC 3 is -2, and so on.
+     * @throws IllegalArgumentException
+     *         if any of the calendar fields is invalid in non-lenient mode.
+     * @see #isWeekDateSupported()
+     * @see #getWeeksInWeekYear()
+     * @see Calendar#getFirstDayOfWeek()
+     * @see Calendar#getMinimalDaysInFirstWeek()
+     * @since 1.7
      */
-    /*
-    public int getWeekBasedYear() {
-        complete();
-        // TODO: Below doesn't work for gregorian cutover...
-        int weekOfYear = internalGet(WEEK_OF_YEAR);
-        int year = internalGet(YEAR);
-        if (internalGet(MONTH) == Calendar.JANUARY) {
-            if (weekOfYear >= 52) {
+    @Override
+    public int getWeekYear() {
+        int year = get(YEAR); // implicitly calls complete()
+        if (internalGetEra() == BCE) {
+            year = 1 - year;
+        }
+
+        // Fast path for the Gregorian calendar years that are never
+        // affected by the Julian-Gregorian transition
+        if (year > gregorianCutoverYear + 1) {
+            int weekOfYear = internalGet(WEEK_OF_YEAR);
+            if (internalGet(MONTH) == JANUARY) {
+                if (weekOfYear >= 52) {
+                    --year;
+                }
+            } else {
+                if (weekOfYear == 1) {
+                    ++year;
+                }
+            }
+            return year;
+        }
+
+        // General (slow) path
+        int dayOfYear = internalGet(DAY_OF_YEAR);
+        int maxDayOfYear = getActualMaximum(DAY_OF_YEAR);
+        int minimalDays = getMinimalDaysInFirstWeek();
+
+        // Quickly check the possibility of year adjustments before
+        // cloning this GregorianCalendar.
+        if (dayOfYear > minimalDays && dayOfYear < (maxDayOfYear - 6)) {
+            return year;
+        }
+
+        // Create a clone to work on the calculation
+        GregorianCalendar cal = (GregorianCalendar) clone();
+        cal.setLenient(true);
+        // Use GMT so that intermediate date calculations won't
+        // affect the time of day fields.
+        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
+        // Go to the first day of the year, which is usually January 1.
+        cal.set(DAY_OF_YEAR, 1);
+        cal.complete();
+
+        // Get the first day of the first day-of-week in the year.
+        int delta = getFirstDayOfWeek() - cal.get(DAY_OF_WEEK);
+        if (delta != 0) {
+            if (delta < 0) {
+                delta += 7;
+            }
+            cal.add(DAY_OF_YEAR, delta);
+        }
+        int minDayOfYear = cal.get(DAY_OF_YEAR);
+        if (dayOfYear < minDayOfYear) {
+            if (minDayOfYear <= minimalDays) {
                 --year;
             }
         } else {
-            if (weekOfYear == 1) {
-                ++year;
+            cal.set(YEAR, year + 1);
+            cal.set(DAY_OF_YEAR, 1);
+            cal.complete();
+            int del = getFirstDayOfWeek() - cal.get(DAY_OF_WEEK);
+            if (del != 0) {
+                if (del < 0) {
+                    del += 7;
+                }
+                cal.add(DAY_OF_YEAR, del);
+            }
+            minDayOfYear = cal.get(DAY_OF_YEAR) - 1;
+            if (minDayOfYear == 0) {
+                minDayOfYear = 7;
+            }
+            if (minDayOfYear >= minimalDays) {
+                int days = maxDayOfYear - dayOfYear + 1;
+                if (days <= (7 - minDayOfYear)) {
+                    ++year;
+                }
             }
         }
         return year;
     }
-    */
+
+    /**
+     * Sets this {@code GregorianCalendar} to the date given by the
+     * date specifiers - <a href="#week_year">{@code weekYear}</a>,
+     * {@code weekOfYear}, and {@code dayOfWeek}. {@code weekOfYear}
+     * follows the <a href="#week_and_year">{@code WEEK_OF_YEAR}
+     * numbering</a>.  The {@code dayOfWeek} value must be one of the
+     * {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} values: {@link
+     * Calendar#SUNDAY SUNDAY} to {@link Calendar#SATURDAY SATURDAY}.
+     *
+     * <p>Note that the numeric day-of-week representation differs from
+     * the ISO 8601 standard, and that the {@code weekOfYear}
+     * numbering is compatible with the standard when {@code
+     * getFirstDayOfWeek()} is {@code MONDAY} and {@code
+     * getMinimalDaysInFirstWeek()} is 4.
+     *
+     * <p>Unlike the {@code set} method, all of the calendar fields
+     * and the instant of time value are calculated upon return.
+     *
+     * <p>If {@code weekOfYear} is out of the valid week-of-year
+     * range in {@code weekYear}, the {@code weekYear}
+     * and {@code weekOfYear} values are adjusted in lenient
+     * mode, or an {@code IllegalArgumentException} is thrown in
+     * non-lenient mode.
+     *
+     * @param weekYear    the week year
+     * @param weekOfYear  the week number based on {@code weekYear}
+     * @param dayOfWeek   the day of week value: one of the constants
+     *                    for the {@link #DAY_OF_WEEK DAY_OF_WEEK} field:
+     *                    {@link Calendar#SUNDAY SUNDAY}, ...,
+     *                    {@link Calendar#SATURDAY SATURDAY}.
+     * @exception IllegalArgumentException
+     *            if any of the given date specifiers is invalid,
+     *            or if any of the calendar fields are inconsistent
+     *            with the given date specifiers in non-lenient mode
+     * @see GregorianCalendar#isWeekDateSupported()
+     * @see Calendar#getFirstDayOfWeek()
+     * @see Calendar#getMinimalDaysInFirstWeek()
+     * @since 1.7
+     */
+    @Override
+    public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
+        if (dayOfWeek < SUNDAY || dayOfWeek > SATURDAY) {
+            throw new IllegalArgumentException("invalid dayOfWeek: " + dayOfWeek);
+        }
 
+        // To avoid changing the time of day fields by date
+        // calculations, use a clone with the GMT time zone.
+        GregorianCalendar gc = (GregorianCalendar) clone();
+        gc.setLenient(true);
+        int era = gc.get(ERA);
+        gc.clear();
+        gc.setTimeZone(TimeZone.getTimeZone("GMT"));
+        gc.set(ERA, era);
+        gc.set(YEAR, weekYear);
+        gc.set(WEEK_OF_YEAR, 1);
+        gc.set(DAY_OF_WEEK, getFirstDayOfWeek());
+        int days = dayOfWeek - getFirstDayOfWeek();
+        if (days < 0) {
+            days += 7;
+        }
+        days += 7 * (weekOfYear - 1);
+        if (days != 0) {
+            gc.add(DAY_OF_YEAR, days);
+        } else {
+            gc.complete();
+        }
+
+        if (!isLenient() &&
+            (gc.getWeekYear() != weekYear
+             || gc.internalGet(WEEK_OF_YEAR) != weekOfYear
+             || gc.internalGet(DAY_OF_WEEK) != dayOfWeek)) {
+            throw new IllegalArgumentException();
+        }
+
+        set(ERA, gc.internalGet(ERA));
+        set(YEAR, gc.internalGet(YEAR));
+        set(MONTH, gc.internalGet(MONTH));
+        set(DAY_OF_MONTH, gc.internalGet(DAY_OF_MONTH));
+
+        // to avoid throwing an IllegalArgumentException in
+        // non-lenient, set WEEK_OF_YEAR internally
+        internalSet(WEEK_OF_YEAR, weekOfYear);
+        complete();
+    }
+
+    /**
+     * Returns the number of weeks in the <a href="#week_year">week year</a>
+     * represented by this {@code GregorianCalendar}.
+     *
+     * <p>For example, if this {@code GregorianCalendar}'s date is
+     * December 31, 2008 with <a href="#iso8601_compatible_setting">the ISO
+     * 8601 compatible setting</a>, this method will return 53 for the
+     * period: December 29, 2008 to January 3, 2010 while {@link
+     * #getActualMaximum(int) getActualMaximum(WEEK_OF_YEAR)} will return
+     * 52 for the period: December 31, 2007 to December 28, 2008.
+     *
+     * @return the number of weeks in the week year.
+     * @see Calendar#WEEK_OF_YEAR
+     * @see #getWeekYear()
+     * @see #getActualMaximum(int)
+     * @since 1.7
+     */
+    public int getWeeksInWeekYear() {
+        GregorianCalendar gc = getNormalizedCalendar();
+        int weekYear = gc.getWeekYear();
+        if (weekYear == gc.internalGet(YEAR)) {
+            return gc.getActualMaximum(WEEK_OF_YEAR);
+        }
+
+        // Use the 2nd week for calculating the max of WEEK_OF_YEAR
+        if (gc == this) {
+            gc = (GregorianCalendar) gc.clone();
+        }
+        gc.setWeekDate(weekYear, 2, internalGet(DAY_OF_WEEK));
+        return gc.getActualMaximum(WEEK_OF_YEAR);
+    }
 
 /////////////////////////////
 // Time => Fields computation
@@ -2178,7 +2413,7 @@
             // If we are in the cutover year, we need some special handling.
             if (normalizedYear == cutoverYear) {
                 // Need to take care of the "missing" days.
-                if (getCutoverCalendarSystem() == jcal) {
+                if (gregorianCutoverYearJulian <= gregorianCutoverYear) {
                     // We need to find out where we are. The cutover
                     // gap could even be more than one year.  (One
                     // year difference in ~48667 years.)
@@ -2208,27 +2443,36 @@
                 // December 31, which is not always true in
                 // GregorianCalendar.
                 long fixedDec31 = fixedDateJan1 - 1;
-                long prevJan1;
+                long prevJan1  = fixedDateJan1 - 365;
                 if (normalizedYear > (cutoverYear + 1)) {
-                    prevJan1 = fixedDateJan1 - 365;
                     if (CalendarUtils.isGregorianLeapYear(normalizedYear - 1)) {
                         --prevJan1;
                     }
+                } else if (normalizedYear <= gregorianCutoverYearJulian) {
+                    if (CalendarUtils.isJulianLeapYear(normalizedYear - 1)) {
+                        --prevJan1;
+                    }
                 } else {
                     BaseCalendar calForJan1 = calsys;
-                    int prevYear = normalizedYear - 1;
-                    if (prevYear == cutoverYear) {
+                    //int prevYear = normalizedYear - 1;
+                    int prevYear = getCalendarDate(fixedDec31).getNormalizedYear();
+                    if (prevYear == gregorianCutoverYear) {
                         calForJan1 = getCutoverCalendarSystem();
-                    }
-                    prevJan1 = calForJan1.getFixedDate(prevYear,
-                                                       BaseCalendar.JANUARY,
-                                                       1,
-                                                       null);
-                    while (prevJan1 > fixedDec31) {
-                        prevJan1 = getJulianCalendarSystem().getFixedDate(--prevYear,
-                                                                    BaseCalendar.JANUARY,
-                                                                    1,
-                                                                    null);
+                        if (calForJan1 == jcal) {
+                            prevJan1 = calForJan1.getFixedDate(prevYear,
+                                                               BaseCalendar.JANUARY,
+                                                               1,
+                                                               null);
+                        } else {
+                            prevJan1 = gregorianCutoverDate;
+                            calForJan1 = gcal;
+                        }
+                    } else if (prevYear <= gregorianCutoverYearJulian) {
+                        calForJan1 = getJulianCalendarSystem();
+                        prevJan1 = calForJan1.getFixedDate(prevYear,
+                                                           BaseCalendar.JANUARY,
+                                                           1,
+                                                           null);
                     }
                 }
                 weekOfYear = getWeekNumber(prevJan1, fixedDec31);
@@ -2260,14 +2504,20 @@
                     if (nextYear == gregorianCutoverYear) {
                         calForJan1 = getCutoverCalendarSystem();
                     }
-                    long nextJan1 = calForJan1.getFixedDate(nextYear,
-                                                            BaseCalendar.JANUARY,
-                                                            1,
-                                                            null);
-                    if (nextJan1 < fixedDate) {
+
+                    long nextJan1;
+                    if (nextYear > gregorianCutoverYear
+                        || gregorianCutoverYearJulian == gregorianCutoverYear
+                        || nextYear == gregorianCutoverYearJulian) {
+                        nextJan1 = calForJan1.getFixedDate(nextYear,
+                                                           BaseCalendar.JANUARY,
+                                                           1,
+                                                           null);
+                    } else {
                         nextJan1 = gregorianCutoverDate;
                         calForJan1 = gcal;
                     }
+
                     long nextJan1st = calForJan1.getDayOfWeekDateOnOrBefore(nextJan1 + 6,
                                                                             getFirstDayOfWeek());
                     int ndays = (int)(nextJan1st - nextJan1);
@@ -2409,10 +2659,24 @@
                 }
                 gfd = jfd;
             } else {
+                jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask);
                 gfd = fixedDate + getFixedDate(gcal, year, fieldMask);
-                jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask);
             }
+
             // Now we have to determine which calendar date it is.
+
+            // If the date is relative from the beginning of the year
+            // in the Julian calendar, then use jfd;
+            if (isFieldSet(fieldMask, DAY_OF_YEAR) || isFieldSet(fieldMask, WEEK_OF_YEAR)) {
+                if (gregorianCutoverYear == gregorianCutoverYearJulian) {
+                    fixedDate = jfd;
+                    break calculateFixedDate;
+                } else if (year == gregorianCutoverYear) {
+                    fixedDate = gfd;
+                    break calculateFixedDate;
+                }
+            }
+
             if (gfd >= gregorianCutoverDate) {
                 if (jfd >= gregorianCutoverDate) {
                     fixedDate = gfd;
@@ -2494,9 +2758,10 @@
                     continue;
                 }
                 if (originalFields[field] != internalGet(field)) {
+                    String s = originalFields[field] + " -> " + internalGet(field);
                     // Restore the original field values
                     System.arraycopy(originalFields, 0, fields, 0, fields.length);
-                    throw new IllegalArgumentException(getFieldName(field));
+                    throw new IllegalArgumentException(getFieldName(field) + ": " + s);
                 }
             }
         }
@@ -2669,9 +2934,7 @@
      * method returns Gregorian. Otherwise, Julian.
      */
     private BaseCalendar getCutoverCalendarSystem() {
-        CalendarDate date = getGregorianCutoverDate();
-        if (date.getMonth() == BaseCalendar.JANUARY
-            && date.getDayOfMonth() == 1) {
+        if (gregorianCutoverYearJulian < gregorianCutoverYear) {
             return gcal;
         }
         return getJulianCalendarSystem();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/util/IllformedLocaleException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009-2010, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+
+package java.util;
+
+/**
+ * Thrown by methods in {@link Locale} and {@link Locale.Builder} to
+ * indicate that an argument is not a well-formed BCP 47 tag.
+ *
+ * @see Locale
+ * @since 1.7
+ */
+public class IllformedLocaleException extends RuntimeException {
+
+    private static final long serialVersionUID = -5245986824925681401L;
+
+    private int _errIdx = -1;
+
+    /**
+     * Constructs a new <code>IllformedLocaleException</code> with no
+     * detail message and -1 as the error index.
+     */
+    public IllformedLocaleException() {
+        super();
+    }
+
+    /**
+     * Constructs a new <code>IllformedLocaleException</code> with the
+     * given message and -1 as the error index.
+     *
+     * @param message the message
+     */
+    public IllformedLocaleException(String message) {
+        super(message);
+    }
+
+    /**
+     * Constructs a new <code>IllformedLocaleException</code> with the
+     * given message and the error index.  The error index is the approximate
+     * offset from the start of the ill-formed value to the point where the
+     * parse first detected an error.  A negative error index value indicates
+     * either the error index is not applicable or unknown.
+     *
+     * @param message the message
+     * @param errorIndex the index
+     */
+    public IllformedLocaleException(String message, int errorIndex) {
+        super(message + ((errorIndex < 0) ? "" : " [at index " + errorIndex + "]"));
+        _errIdx = errorIndex;
+    }
+
+    /**
+     * Returns the index where the error was found. A negative value indicates
+     * either the error index is not applicable or unknown.
+     *
+     * @return the error index
+     */
+    public int getErrorIndex() {
+        return _errIdx;
+    }
+}
--- a/src/share/classes/java/util/Locale.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/Locale.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -40,86 +40,240 @@
 
 package java.util;
 
-import java.io.*;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamField;
+import java.io.Serializable;
 import java.security.AccessController;
 import java.text.MessageFormat;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.spi.LocaleNameProvider;
-import java.util.spi.LocaleServiceProvider;
+
 import sun.security.action.GetPropertyAction;
 import sun.util.LocaleServiceProviderPool;
+import sun.util.locale.AsciiUtil;
+import sun.util.locale.BaseLocale;
+import sun.util.locale.InternalLocaleBuilder;
+import sun.util.locale.LanguageTag;
+import sun.util.locale.LocaleExtensions;
+import sun.util.locale.LocaleObjectCache;
+import sun.util.locale.LocaleSyntaxException;
+import sun.util.locale.ParseStatus;
+import sun.util.locale.UnicodeLocaleExtension;
 import sun.util.resources.LocaleData;
 import sun.util.resources.OpenListResourceBundle;
 
 /**
- *
  * A <code>Locale</code> object represents a specific geographical, political,
  * or cultural region. An operation that requires a <code>Locale</code> to perform
  * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code>
  * to tailor information for the user. For example, displaying a number
- * is a locale-sensitive operation--the number should be formatted
- * according to the customs/conventions of the user's native country,
+ * is a locale-sensitive operation&mdash; the number should be formatted
+ * according to the customs and conventions of the user's native country,
  * region, or culture.
  *
- * <P>
- * Create a <code>Locale</code> object using the constructors in this class:
+ * <p> The <code>Locale</code> class implements identifiers
+ * interchangeable with BCP 47 (IETF BCP 47, "Tags for Identifying
+ * Languages"), with support for the LDML (UTS#35, "Unicode Locale
+ * Data Markup Language") BCP 47-compatible extensions for locale data
+ * exchange.
+ *
+ * <p> A <code>Locale</code> object logically consists of the fields
+ * described below.
+ *
+ * <dl>
+ *   <dt><a name="def_language"/><b>language</b></dt>
+ *
+ *   <dd>ISO 639 alpha-2 or alpha-3 language code, or registered
+ *   language subtags up to 8 alpha letters (for future enhancements).
+ *   When a language has both an alpha-2 code and an alpha-3 code, the
+ *   alpha-2 code must be used.  You can find a full list of valid
+ *   language codes in the IANA Language Subtag Registry (search for
+ *   "Type: language").  The language field is case insensitive, but
+ *   <code>Locale</code> always canonicalizes to lower case.</dd><br>
+ *
+ *   <dd>Well-formed language values have the form
+ *   <code>[a-zA-Z]{2,8}</code>.  Note that this is not the the full
+ *   BCP47 language production, since it excludes extlang.  They are
+ *   not needed since modern three-letter language codes replace
+ *   them.</dd><br>
+ *
+ *   <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd><br>
+ *
+ *   <dt><a name="def_script"/><b>script</b></dt>
+ *
+ *   <dd>ISO 15924 alpha-4 script code.  You can find a full list of
+ *   valid script codes in the IANA Language Subtag Registry (search
+ *   for "Type: script").  The script field is case insensitive, but
+ *   <code>Locale</code> always canonicalizes to title case (the first
+ *   letter is upper case and the rest of the letters are lower
+ *   case).</dd><br>
+ *
+ *   <dd>Well-formed script values have the form
+ *   <code>[a-zA-Z]{4}</code></dd><br>
+ *
+ *   <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd><br>
+ *
+ *   <dt><a name="def_region"/><b>country (region)</b></dt>
+ *
+ *   <dd>ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code.
+ *   You can find a full list of valid country and region codes in the
+ *   IANA Language Subtag Registry (search for "Type: region").  The
+ *   country (region) field is case insensitive, but
+ *   <code>Locale</code> always canonicalizes to upper case.</dd><br>
+ *
+ *   <dd>Well-formed country/region values have
+ *   the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd><br>
+ *
+ *   <dd>Example: "US" (United States), "FR" (France), "029"
+ *   (Caribbean)</dd><br>
+ *
+ *   <dt><a name="def_variant"/><b>variant</b></dt>
+ *
+ *   <dd>Any arbitrary value used to indicate a variation of a
+ *   <code>Locale</code>.  Where there are two or more variant values
+ *   each indicating its own semantics, these values should be ordered
+ *   by importance, with most important first, separated by
+ *   underscore('_').  The variant field is case sensitive.</dd><br>
+ *
+ *   <dd>Note: IETF BCP 47 places syntactic restrictions on variant
+ *   subtags.  Also BCP 47 subtags are strictly used to indicate
+ *   additional variations that define a language or its dialects that
+ *   are not covered by any combinations of language, script and
+ *   region subtags.  You can find a full list of valid variant codes
+ *   in the IANA Language Subtag Registry (search for "Type: variant").
+ *
+ *   <p>However, the variant field in <code>Locale</code> has
+ *   historically been used for any kind of variation, not just
+ *   language variations.  For example, some supported variants
+ *   available in Java SE Runtime Environments indicate alternative
+ *   cultural behaviors such as calendar type or number script.  In
+ *   BCP 47 this kind of information, which does not identify the
+ *   language, is supported by extension subtags or private use
+ *   subtags.</dd><br>
+ *
+ *   <dd>Well-formed variant values have the form <code>SUBTAG
+ *   (('_'|'-') SUBTAG)*</code> where <code>SUBTAG =
+ *   [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}</code>. (Note: BCP 47 only
+ *   uses hyphen ('-') as a delimiter, this is more lenient).</dd><br>
+ *
+ *   <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd><br>
+ *
+ *   <dt><a name="def_extensions"/><b>extensions</b></dt>
+ *
+ *   <dd>A map from single character keys to string values, indicating
+ *   extensions apart from language identification.  The extensions in
+ *   <code>Locale</code> implement the semantics and syntax of BCP 47
+ *   extension subtags and private use subtags. The extensions are
+ *   case insensitive, but <code>Locale</code> canonicalizes all
+ *   extension keys and values to lower case. Note that extensions
+ *   cannot have empty values.</dd><br>
+ *
+ *   <dd>Well-formed keys are single characters from the set
+ *   <code>[0-9a-zA-Z]</code>.  Well-formed values have the form
+ *   <code>SUBTAG ('-' SUBTAG)*</code> where for the key 'x'
+ *   <code>SUBTAG = [0-9a-zA-Z]{1,8}</code> and for other keys
+ *   <code>SUBTAG = [0-9a-zA-Z]{2,8}</code> (that is, 'x' allows
+ *   single-character subtags).</dd><br>
+ *
+ *   <dd>Example: key="u"/value="ca-japanese" (Japanese Calendar),
+ *   key="x"/value="java-1-7"</dd>
+ * </dl>
+ *
+ * <b>Note:</b> Although BCP 47 requires field values to be registered
+ * in the IANA Language Subtag Registry, the <code>Locale</code> class
+ * does not provide any validation features.  The <code>Builder</code>
+ * only checks if an individual field satisfies the syntactic
+ * requirement (is well-formed), but does not validate the value
+ * itself.  See {@link Builder} for details.
+ *
+ * <h4><a name="def_locale_extension">Unicode locale/language extension</h4>
+ *
+ * <p>UTS#35, "Unicode Locale Data Markup Language" defines optional
+ * attributes and keywords to override or refine the default behavior
+ * associated with a locale.  A keyword is represented by a pair of
+ * key and type.  For example, "nu-thai" indicates that Thai local
+ * digits (value:"thai") should be used for formatting numbers
+ * (key:"nu").
+ *
+ * <p>The keywords are mapped to a BCP 47 extension value using the
+ * extension key 'u' ({@link #UNICODE_LOCALE_EXTENSION}).  The above
+ * example, "nu-thai", becomes the extension "u-nu-thai".code
+ *
+ * <p>Thus, when a <code>Locale</code> object contains Unicode locale
+ * attributes and keywords,
+ * <code>getExtension(UNICODE_LOCALE_EXTENSION)</code> will return a
+ * String representing this information, for example, "nu-thai".  The
+ * <code>Locale</code> class also provides {@link
+ * #getUnicodeLocaleAttributes}, {@link #getUnicodeLocaleKeys}, and
+ * {@link #getUnicodeLocaleType} which allow you to access Unicode
+ * locale attributes and key/type pairs directly.  When represented as
+ * a string, the Unicode Locale Extension lists attributes
+ * alphabetically, followed by key/type sequences with keys listed
+ * alphabetically (the order of subtags comprising a key's type is
+ * fixed when the type is defined)
+ *
+ * <p>A well-formed locale key has the form
+ * <code>[0-9a-zA-Z]{2}</code>.  A well-formed locale type has the
+ * form <code>"" | [0-9a-zA-Z]{3,8} ('-' [0-9a-zA-Z]{3,8})*</code> (it
+ * can be empty, or a series of subtags 3-8 alphanums in length).  A
+ * well-formed locale attribute has the form
+ * <code>[0-9a-zA-Z]{3,8}</code> (it is a single subtag with the same
+ * form as a locale type subtag).
+ *
+ * <p>The Unicode locale extension specifies optional behavior in
+ * locale-sensitive services.  Although the LDML specification defines
+ * various keys and values, actual locale-sensitive service
+ * implementations in a Java Runtime Environment might not support any
+ * particular Unicode locale attributes or key/type pairs.
+ *
+ * <h4>Creating a Locale</h4>
+ *
+ * <p>There are several different ways to create a <code>Locale</code>
+ * object.
+ *
+ * <h5>Builder</h5>
+ *
+ * <p>Using {@link Builder} you can construct a <code>Locale</code> object
+ * that conforms to BCP 47 syntax.
+ *
+ * <h5>Constructors</h5>
+ *
+ * <p>The <code>Locale</code> class provides three constructors:
  * <blockquote>
  * <pre>
- * Locale(String language)
- * Locale(String language, String country)
- * Locale(String language, String country, String variant)
+ *     {@link #Locale(String language)}
+ *     {@link #Locale(String language, String country)}
+ *     {@link #Locale(String language, String country, String variant)}
  * </pre>
  * </blockquote>
- * The language argument is a valid <STRONG>ISO Language Code.</STRONG>
- * These codes are the lower-case, two-letter codes as defined by ISO-639.
- * You can find a full list of these codes at a number of sites, such as:
- * <BR><a href ="http://www.loc.gov/standards/iso639-2/php/English_list.php">
- * <code>http://www.loc.gov/standards/iso639-2/php/English_list.php</code></a>
+ * These constructors allow you to create a <code>Locale</code> object
+ * with language, country and variant, but you cannot specify
+ * script or extensions.
  *
- * <P>
- * The country argument is a valid <STRONG>ISO Country Code.</STRONG> These
- * codes are the upper-case, two-letter codes as defined by ISO-3166.
- * You can find a full list of these codes at a number of sites, such as:
- * <BR><a href="http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html">
- * <code>http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html</code></a>
+ * <h5>Factory Methods</h5>
  *
- * <P>
- * The variant argument is a vendor or browser-specific code.
- * For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX.
- * Where there are two variants, separate them with an underscore, and
- * put the most important one first. For example, a Traditional Spanish collation
- * might construct a locale with parameters for language, country and variant as:
- * "es", "ES", "Traditional_WIN".
+ * <p>The method {@link #forLanguageTag} creates a <code>Locale</code>
+ * object for a well-formed BCP 47 language tag.
  *
- * <P>
- * Because a <code>Locale</code> object is just an identifier for a region,
- * no validity check is performed when you construct a <code>Locale</code>.
- * If you want to see whether particular resources are available for the
- * <code>Locale</code> you construct, you must query those resources. For
- * example, ask the <code>NumberFormat</code> for the locales it supports
- * using its <code>getAvailableLocales</code> method.
- * <BR><STRONG>Note:</STRONG> When you ask for a resource for a particular
- * locale, you get back the best available match, not necessarily
- * precisely what you asked for. For more information, look at
- * {@link ResourceBundle}.
+ * <h5>Locale Constants</h5>
  *
- * <P>
- * The <code>Locale</code> class provides a number of convenient constants
+ * <p>The <code>Locale</code> class provides a number of convenient constants
  * that you can use to create <code>Locale</code> objects for commonly used
  * locales. For example, the following creates a <code>Locale</code> object
  * for the United States:
  * <blockquote>
  * <pre>
- * Locale.US
+ *     Locale.US
  * </pre>
  * </blockquote>
  *
- * <P>
- * Once you've created a <code>Locale</code> you can query it for information about
- * itself. Use <code>getCountry</code> to get the ISO Country Code and
- * <code>getLanguage</code> to get the ISO Language Code. You can
- * use <code>getDisplayCountry</code> to get the
+ * <h4>Use of Locale</h4>
+ *
+ * <p>Once you've created a <code>Locale</code> you can query it for information
+ * about itself. Use <code>getCountry</code> to get the country (or region)
+ * code and <code>getLanguage</code> to get the language code.
+ * You can use <code>getDisplayCountry</code> to get the
  * name of the country suitable for displaying to the user. Similarly,
  * you can use <code>getDisplayLanguage</code> to get the name of
  * the language suitable for displaying to the user. Interestingly,
@@ -127,28 +281,27 @@
  * and have two versions: one that uses the default locale and one
  * that uses the locale specified as an argument.
  *
- * <P>
- * The Java Platform provides a number of classes that perform locale-sensitive
+ * <p>The Java Platform provides a number of classes that perform locale-sensitive
  * operations. For example, the <code>NumberFormat</code> class formats
- * numbers, currency, or percentages in a locale-sensitive manner. Classes
- * such as <code>NumberFormat</code> have a number of convenience methods
+ * numbers, currency, and percentages in a locale-sensitive manner. Classes
+ * such as <code>NumberFormat</code> have several convenience methods
  * for creating a default object of that type. For example, the
  * <code>NumberFormat</code> class provides these three convenience methods
  * for creating a default <code>NumberFormat</code> object:
  * <blockquote>
  * <pre>
- * NumberFormat.getInstance()
- * NumberFormat.getCurrencyInstance()
- * NumberFormat.getPercentInstance()
+ *     NumberFormat.getInstance()
+ *     NumberFormat.getCurrencyInstance()
+ *     NumberFormat.getPercentInstance()
  * </pre>
  * </blockquote>
- * These methods have two variants; one with an explicit locale
- * and one without; the latter using the default locale.
+ * Each of these methods has two variants; one with an explicit locale
+ * and one without; the latter uses the default locale:
  * <blockquote>
  * <pre>
- * NumberFormat.getInstance(myLocale)
- * NumberFormat.getCurrencyInstance(myLocale)
- * NumberFormat.getPercentInstance(myLocale)
+ *     NumberFormat.getInstance(myLocale)
+ *     NumberFormat.getCurrencyInstance(myLocale)
+ *     NumberFormat.getPercentInstance(myLocale)
  * </pre>
  * </blockquote>
  * A <code>Locale</code> is the mechanism for identifying the kind of object
@@ -156,75 +309,162 @@
  * <STRONG>just</STRONG> a mechanism for identifying objects,
  * <STRONG>not</STRONG> a container for the objects themselves.
  *
- * @see         ResourceBundle
- * @see         java.text.Format
- * @see         java.text.NumberFormat
- * @see         java.text.Collator
- * @author      Mark Davis
- * @since       1.1
+ * <h4>Compatibility</h4>
+ *
+ * <p>In order to maintain compatibility with existing usage, Locale's
+ * constructors retain their behavior prior to the Java Runtime
+ * Environment version 1.7.  The same is largely true for the
+ * <code>toString</code> method. Thus Locale objects can continue to
+ * be used as they were. In particular, clients who parse the output
+ * of toString into language, country, and variant fields can continue
+ * to do so (although this is strongly discouraged), although the
+ * variant field will have additional information in it if script or
+ * extensions are present.
+ *
+ * <p>In addition, BCP 47 imposes syntax restrictions that are not
+ * imposed by Locale's constructors. This means that conversions
+ * between some Locales and BCP 47 language tags cannot be made without
+ * losing information. Thus <code>toLanguageTag</code> cannot
+ * represent the state of locales whose language, country, or variant
+ * do not conform to BCP 47.
+ *
+ * <p>Because of these issues, it is recommended that clients migrate
+ * away from constructing non-conforming locales and use the
+ * <code>forLanguageTag</code> and <code>Locale.Builder</code> APIs instead.
+ * Clients desiring a string representation of the complete locale can
+ * then always rely on <code>toLanguageTag</code> for this purpose.
+ *
+ * <h5><a name="special_cases_constructor"/>Special cases</h5>
+ *
+ * <p>For compatibility reasons, two
+ * non-conforming locales are treated as special cases.  These are
+ * <b><tt>ja_JP_JP</tt></b> and <b><tt>th_TH_TH</tt></b>. These are ill-formed
+ * in BCP 47 since the variants are too short. To ease migration to BCP 47,
+ * these are treated specially during construction.  These two cases (and only
+ * these) cause a constructor to generate an extension, all other values behave
+ * exactly as they did prior to Java 7.
+ *
+ * <p>Java has used <tt>ja_JP_JP</tt> to represent Japanese as used in
+ * Japan together with the Japanese Imperial calendar. This is now
+ * representable using a Unicode locale extension, by specifying the
+ * Unicode locale key <tt>ca</tt> (for "calendar") and type
+ * <tt>japanese</tt>. When the Locale constructor is called with the
+ * arguments "ja", "JP", "JP", the extension "u-ca-japanese" is
+ * automatically added.
+ *
+ * <p>Java has used <tt>th_TH_TH</tt> to represent Thai as used in
+ * Thailand together with Thai digits. This is also now representable using
+ * a Unicode locale extension, by specifying the Unicode locale key
+ * <tt>nu</tt> (for "number") and value <tt>thai</tt>. When the Locale
+ * constructor is called with the arguments "th", "TH", "TH", the
+ * extension "u-nu-thai" is automatically added.
+ *
+ * <h5>Serialization</h5>
+ *
+ * <p>During serialization, writeObject writes all fields to the output
+ * stream, including extensions.
+ *
+ * <p>During deserialization, readResolve adds extensions as described
+ * in <a href="#special_cases_constructor">Special Cases</a>, only
+ * for the two cases th_TH_TH and ja_JP_JP.
+ *
+ * <h5>Legacy language codes</h5>
+ *
+ * <p>Locale's constructor has always converted three language codes to
+ * their earlier, obsoleted forms: <tt>he</tt> maps to <tt>iw</tt>,
+ * <tt>yi</tt> maps to <tt>ji</tt>, and <tt>id</tt> maps to
+ * <tt>in</tt>.  This continues to be the case, in order to not break
+ * backwards compatibility.
+ *
+ * <p>The APIs added in 1.7 map between the old and new language codes,
+ * maintaining the old codes internal to Locale (so that
+ * <code>getLanguage</code> and <code>toString</code> reflect the old
+ * code), but using the new codes in the BCP 47 language tag APIs (so
+ * that <code>toLanguageTag</code> reflects the new one). This
+ * preserves the equivalence between Locales no matter which code or
+ * API is used to construct them. Java's default resource bundle
+ * lookup mechanism also implements this mapping, so that resources
+ * can be named using either convention, see {@link ResourceBundle.Control}.
+ *
+ * <h5>Three-letter language/country(region) codes</h5>
+ *
+ * <p>The Locale constructors have always specified that the language
+ * and the country param be two characters in length, although in
+ * practice they have accepted any length.  The specification has now
+ * been relaxed to allow language codes of two to eight characters and
+ * country (region) codes of two to three characters, and in
+ * particular, three-letter language codes and three-digit region
+ * codes as specified in the IANA Language Subtag Registry.  For
+ * compatibility, the implementation still does not impose a length
+ * constraint.
+ *
+ * @see Builder
+ * @see ResourceBundle
+ * @see java.text.Format
+ * @see java.text.NumberFormat
+ * @see java.text.Collator
+ * @author Mark Davis
+ * @since 1.1
  */
-
 public final class Locale implements Cloneable, Serializable {
 
-    // cache to store singleton Locales
-    private final static ConcurrentHashMap<String, Locale> cache =
-        new ConcurrentHashMap<String, Locale>(32);
-
-    /** Useful constant for language.
-     */
-    static public final Locale ENGLISH = createSingleton("en__", "en", "");
-
-    /** Useful constant for language.
-     */
-    static public final Locale FRENCH = createSingleton("fr__", "fr", "");
-
-    /** Useful constant for language.
-     */
-    static public final Locale GERMAN = createSingleton("de__", "de", "");
-
-    /** Useful constant for language.
-     */
-    static public final Locale ITALIAN = createSingleton("it__", "it", "");
+    static private final  Cache LOCALECACHE = new Cache();
 
     /** Useful constant for language.
      */
-    static public final Locale JAPANESE = createSingleton("ja__", "ja", "");
+    static public final Locale ENGLISH = getInstance("en", "", "");
+
+    /** Useful constant for language.
+     */
+    static public final Locale FRENCH = getInstance("fr", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale KOREAN = createSingleton("ko__", "ko", "");
+    static public final Locale GERMAN = getInstance("de", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale CHINESE = createSingleton("zh__", "zh", "");
+    static public final Locale ITALIAN = getInstance("it", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale SIMPLIFIED_CHINESE = createSingleton("zh_CN_", "zh", "CN");
+    static public final Locale JAPANESE = getInstance("ja", "", "");
+
+    /** Useful constant for language.
+     */
+    static public final Locale KOREAN = getInstance("ko", "", "");
 
     /** Useful constant for language.
      */
-    static public final Locale TRADITIONAL_CHINESE = createSingleton("zh_TW_", "zh", "TW");
+    static public final Locale CHINESE = getInstance("zh", "", "");
 
-    /** Useful constant for country.
+    /** Useful constant for language.
      */
-    static public final Locale FRANCE = createSingleton("fr_FR_", "fr", "FR");
+    static public final Locale SIMPLIFIED_CHINESE = getInstance("zh", "CN", "");
+
+    /** Useful constant for language.
+     */
+    static public final Locale TRADITIONAL_CHINESE = getInstance("zh", "TW", "");
 
     /** Useful constant for country.
      */
-    static public final Locale GERMANY = createSingleton("de_DE_", "de", "DE");
+    static public final Locale FRANCE = getInstance("fr", "FR", "");
+
+    /** Useful constant for country.
+     */
+    static public final Locale GERMANY = getInstance("de", "DE", "");
 
     /** Useful constant for country.
      */
-    static public final Locale ITALY = createSingleton("it_IT_", "it", "IT");
+    static public final Locale ITALY = getInstance("it", "IT", "");
 
     /** Useful constant for country.
      */
-    static public final Locale JAPAN = createSingleton("ja_JP_", "ja", "JP");
+    static public final Locale JAPAN = getInstance("ja", "JP", "");
 
     /** Useful constant for country.
      */
-    static public final Locale KOREA = createSingleton("ko_KR_", "ko", "KR");
+    static public final Locale KOREA = getInstance("ko", "KR", "");
 
     /** Useful constant for country.
      */
@@ -240,19 +480,19 @@
 
     /** Useful constant for country.
      */
-    static public final Locale UK = createSingleton("en_GB_", "en", "GB");
+    static public final Locale UK = getInstance("en", "GB", "");
 
     /** Useful constant for country.
      */
-    static public final Locale US = createSingleton("en_US_", "en", "US");
+    static public final Locale US = getInstance("en", "US", "");
 
     /** Useful constant for country.
      */
-    static public final Locale CANADA = createSingleton("en_CA_", "en", "CA");
+    static public final Locale CANADA = getInstance("en", "CA", "");
 
     /** Useful constant for country.
      */
-    static public final Locale CANADA_FRENCH = createSingleton("fr_CA_", "fr", "CA");
+    static public final Locale CANADA_FRENCH = getInstance("fr", "CA", "");
 
     /**
      * Useful constant for the root locale.  The root locale is the locale whose
@@ -262,7 +502,25 @@
      *
      * @since 1.6
      */
-    static public final Locale ROOT = createSingleton("__", "", "");
+    static public final Locale ROOT = getInstance("", "", "");
+
+    /**
+     * The key for the private use extension ('x').
+     *
+     * @see #getExtension(char)
+     * @see Builder#setExtension(char, String)
+     * @since 1.7
+     */
+    static public final char PRIVATE_USE_EXTENSION = 'x';
+
+    /**
+     * The key for Unicode locale extension ('u').
+     *
+     * @see #getExtension(char)
+     * @see Builder#setExtension(char, String)
+     * @since 1.7
+     */
+    static public final char UNICODE_LOCALE_EXTENSION = 'u';
 
     /** serialization ID
      */
@@ -274,32 +532,67 @@
     private static final int DISPLAY_LANGUAGE = 0;
     private static final int DISPLAY_COUNTRY  = 1;
     private static final int DISPLAY_VARIANT  = 2;
+    private static final int DISPLAY_SCRIPT = 3;
+
+    /**
+     * Private constructor used by getInstance method
+     */
+    private Locale(BaseLocale baseLocale, LocaleExtensions extensions) {
+        _baseLocale = baseLocale;
+        _extensions = extensions;
+    }
 
     /**
-     * Construct a locale from language, country, variant.
-     * NOTE:  ISO 639 is not a stable standard; some of the language codes it defines
-     * (specifically iw, ji, and in) have changed.  This constructor accepts both the
-     * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other
+     * Construct a locale from language, country and variant.
+     * This constructor normalizes the language value to lowercase and
+     * the country value to uppercase.
+     * <p>
+     * <b>Note:</b>
+     * <ul>
+     * <li>ISO 639 is not a stable standard; some of the language codes it defines
+     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
+     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
      * API on Locale will return only the OLD codes.
-     * @param language lowercase two-letter ISO-639 code.
-     * @param country uppercase two-letter ISO-3166 code.
-     * @param variant vendor and browser specific code. See class description.
+     * <li>For backward compatibility reasons, this constructor does not make
+     * any syntactic checks on the input.
+     * <li>The two cases ("ja", "JP", "JP") and ("th", "TH", "TH") are handled specially,
+     * see <a href="#special_cases_constructor">Special Cases</a> for more information.
+     * </ul>
+     *
+     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
+     * up to 8 characters in length.  See the <code>Locale</code> class description about
+     * valid language values.
+     * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
+     * See the <code>Locale</code> class description about valid country values.
+     * @param variant Any arbitrary value used to indicate a variation of a <code>Locale</code>.
+     * See the <code>Locale</code> class description for the details.
      * @exception NullPointerException thrown if any argument is null.
      */
     public Locale(String language, String country, String variant) {
-        this.language = convertOldISOCodes(language);
-        this.country = toUpperCase(country).intern();
-        this.variant = variant.intern();
+        _baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant);
+        _extensions = getCompatibilityExtensions(language, "", country, variant);
     }
 
     /**
-     * Construct a locale from language, country.
-     * NOTE:  ISO 639 is not a stable standard; some of the language codes it defines
-     * (specifically iw, ji, and in) have changed.  This constructor accepts both the
-     * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other
+     * Construct a locale from language and country.
+     * This constructor normalizes the language value to lowercase and
+     * the country value to uppercase.
+     * <p>
+     * <b>Note:</b>
+     * <ul>
+     * <li>ISO 639 is not a stable standard; some of the language codes it defines
+     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
+     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
      * API on Locale will return only the OLD codes.
-     * @param language lowercase two-letter ISO-639 code.
-     * @param country uppercase two-letter ISO-3166 code.
+     * <li>For backward compatibility reasons, this constructor does not make
+     * any syntactic checks on the input.
+     * </ul>
+     *
+     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
+     * up to 8 characters in length.  See the <code>Locale</code> class description about
+     * valid language values.
+     * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
+     * See the <code>Locale</code> class description about valid country values.
      * @exception NullPointerException thrown if either argument is null.
      */
     public Locale(String language, String country) {
@@ -308,11 +601,21 @@
 
     /**
      * Construct a locale from a language code.
-     * NOTE:  ISO 639 is not a stable standard; some of the language codes it defines
-     * (specifically iw, ji, and in) have changed.  This constructor accepts both the
-     * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other
+     * This constructor normalizes the language value to lowercase.
+     * <p>
+     * <b>Note:</b>
+     * <ul>
+     * <li>ISO 639 is not a stable standard; some of the language codes it defines
+     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
+     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
      * API on Locale will return only the OLD codes.
-     * @param language lowercase two-letter ISO-639 code.
+     * <li>For backward compatibility reasons, this constructor does not make
+     * any syntactic checks on the input.
+     * </ul>
+     *
+     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
+     * up to 8 characters in length.  See the <code>Locale</code> class description about
+     * valid language values.
      * @exception NullPointerException thrown if argument is null.
      * @since 1.4
      */
@@ -321,32 +624,6 @@
     }
 
     /**
-     * Constructs a <code>Locale</code> using <code>language</code>
-     * and <code>country</code>.  This constructor assumes that
-     * <code>language</code> and <code>contry</code> are interned and
-     * it is invoked by createSingleton only. (flag is just for
-     * avoiding the conflict with the public constructors.
-     */
-    private Locale(String language, String country, boolean flag) {
-        this.language = language;
-        this.country = country;
-        this.variant = "";
-    }
-
-    /**
-     * Creates a <code>Locale</code> instance with the given
-     * <code>language</code> and <code>counry</code> and puts the
-     * instance under the given <code>key</code> in the cache. This
-     * method must be called only when initializing the Locale
-     * constants.
-     */
-    private static Locale createSingleton(String key, String language, String country) {
-        Locale locale = new Locale(language, country, false);
-        cache.put(key, locale);
-        return locale;
-    }
-
-    /**
      * Returns a <code>Locale</code> constructed from the given
      * <code>language</code>, <code>country</code> and
      * <code>variant</code>. If the same <code>Locale</code> instance
@@ -354,29 +631,70 @@
      * returned. Otherwise, a new <code>Locale</code> instance is
      * created and cached.
      *
-     * @param language lowercase two-letter ISO-639 code.
-     * @param country uppercase two-letter ISO-3166 code.
+     * @param language lowercase 2 to 8 language code.
+     * @param country uppercase two-letter ISO-3166 code and numric-3 UN M.49 area code.
      * @param variant vendor and browser specific code. See class description.
      * @return the <code>Locale</code> instance requested
      * @exception NullPointerException if any argument is null.
      */
     static Locale getInstance(String language, String country, String variant) {
-        if (language== null || country == null || variant == null) {
+        return getInstance(language, "", country, variant, LocaleExtensions.EMPTY_EXTENSIONS);
+    }
+
+    static Locale getInstance(String language, String script, String country,
+                                      String variant, LocaleExtensions extensions) {
+        if (language== null || script == null || country == null || variant == null) {
             throw new NullPointerException();
         }
 
-        StringBuilder sb = new StringBuilder();
-        sb.append(language).append('_').append(country).append('_').append(variant);
-        String key = sb.toString();
-        Locale locale = cache.get(key);
-        if (locale == null) {
-            locale = new Locale(language, country, variant);
-            Locale l = cache.putIfAbsent(key, locale);
-            if (l != null) {
-                locale = l;
+        if (extensions == null) {
+            extensions = LocaleExtensions.EMPTY_EXTENSIONS;
+        }
+
+        if (extensions.equals(LocaleExtensions.EMPTY_EXTENSIONS)) {
+            extensions = getCompatibilityExtensions(language, script, country, variant);
+        }
+
+        BaseLocale baseloc = BaseLocale.getInstance(language, script, country, variant);
+        return getInstance(baseloc, extensions);
+    }
+
+    static Locale getInstance(BaseLocale baseloc, LocaleExtensions extensions) {
+        LocaleKey key = new LocaleKey(baseloc, extensions);
+        return LOCALECACHE.get(key);
+    }
+
+    private static class Cache extends LocaleObjectCache<LocaleKey, Locale> {
+        public Cache() {
+        }
+        protected Locale createObject(LocaleKey key) {
+            return new Locale(key._base, key._exts);
+        }
+    }
+
+    private static class LocaleKey {
+        private BaseLocale _base;
+        private LocaleExtensions _exts;
+
+        private LocaleKey(BaseLocale baseLocale, LocaleExtensions extensions) {
+            _base = baseLocale;
+            _exts = extensions;
+        }
+
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
             }
+            if (!(obj instanceof LocaleKey)) {
+                return false;
+            }
+            LocaleKey other = (LocaleKey)obj;
+            return _base.equals(other._base) && _exts.equals(other._exts);
         }
-        return locale;
+
+        public int hashCode() {
+            return _base.hashCode() ^ _exts.hashCode();
+        }
     }
 
     /**
@@ -395,31 +713,103 @@
         // do not synchronize this method - see 4071298
         // it's OK if more than one default locale happens to be created
         if (defaultLocale == null) {
-            String language, region, country, variant;
+            initDefault();
+        }
+        return defaultLocale;
+    }
+
+    /**
+     * Gets the current value of the default locale for the specified Category
+     * for this instance of the Java Virtual Machine.
+     * <p>
+     * The Java Virtual Machine sets the default locale during startup based
+     * on the host environment. It is used by many locale-sensitive methods
+     * if no locale is explicitly specified. It can be changed using the
+     * setDefault(Locale.Category, Locale) method.
+     *
+     * @param category - the specified category to get the default locale
+     * @throws NullPointerException - if category is null
+     * @return the default locale for the specified Category for this instance
+     *     of the Java Virtual Machine
+     * @see #setDefault(Locale.Category, Locale)
+     * @since 1.7
+     */
+    public static Locale getDefault(Locale.Category category) {
+        // do not synchronize this method - see 4071298
+        // it's OK if more than one default locale happens to be created
+        switch (category) {
+        case DISPLAY:
+            if (defaultDisplayLocale == null) {
+                initDefault(category);
+            }
+            return defaultDisplayLocale;
+        case FORMAT:
+            if (defaultFormatLocale == null) {
+                initDefault(category);
+            }
+            return defaultFormatLocale;
+        default:
+            assert false: "Unknown Category";
+        }
+        return getDefault();
+    }
+
+    private static void initDefault() {
+        String language, region, country, variant;
+        language = AccessController.doPrivileged(
+            new GetPropertyAction("user.language", "en"));
+        // for compatibility, check for old user.region property
+        region = AccessController.doPrivileged(
+            new GetPropertyAction("user.region"));
+        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 = AccessController.doPrivileged(
+                new GetPropertyAction("user.country", ""));
+            variant = AccessController.doPrivileged(
+                new GetPropertyAction("user.variant", ""));
+        }
+        defaultLocale = getInstance(language, country, variant);
+    }
+
+    private static void initDefault(Locale.Category category) {
+        String language, region, country, variant;
+        switch (category) {
+        case DISPLAY:
             language = AccessController.doPrivileged(
-                new GetPropertyAction("user.language", "en"));
-            // for compatibility, check for old user.region property
-            region = AccessController.doPrivileged(
-                new GetPropertyAction("user.region"));
-            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 = "";
-                }
+                new GetPropertyAction("user.language.display", ""));
+            if ("".equals(language)) {
+                defaultDisplayLocale = getDefault();
             } else {
                 country = AccessController.doPrivileged(
-                    new GetPropertyAction("user.country", ""));
+                    new GetPropertyAction("user.country.display", ""));
                 variant = AccessController.doPrivileged(
-                    new GetPropertyAction("user.variant", ""));
+                    new GetPropertyAction("user.variant.display", ""));
+                defaultDisplayLocale = getInstance(language, country, variant);
             }
-            defaultLocale = getInstance(language, country, variant);
+            break;
+        case FORMAT:
+            language = AccessController.doPrivileged(
+                new GetPropertyAction("user.language.format", ""));
+            if ("".equals(language)) {
+                defaultFormatLocale = getDefault();
+            } else {
+                country = AccessController.doPrivileged(
+                    new GetPropertyAction("user.country.format", ""));
+                variant = AccessController.doPrivileged(
+                    new GetPropertyAction("user.variant.format", ""));
+                defaultFormatLocale = getInstance(language, country, variant);
+            }
+            break;
         }
-        return defaultLocale;
     }
 
     /**
@@ -438,6 +828,9 @@
      * of functionality, this method should only be used if the caller
      * is prepared to reinitialize locale-sensitive code running
      * within the same Java Virtual Machine.
+     * <p>
+     * By setting the default locale with this method, all of the default
+     * locales for each Category are also set to the specified default locale.
      *
      * @throws SecurityException
      *        if a security manager exists and its
@@ -448,13 +841,59 @@
      * @see java.util.PropertyPermission
      */
     public static synchronized void setDefault(Locale newLocale) {
+        setDefault(Category.DISPLAY, newLocale);
+        setDefault(Category.FORMAT, newLocale);
+        defaultLocale = newLocale;
+    }
+
+    /**
+     * Sets the default locale for the specified Category for this instance
+     * of the Java Virtual Machine. This does not affect the host locale.
+     * <p>
+     * If there is a security manager, its checkPermission method is called
+     * with a PropertyPermission("user.language", "write") permission before
+     * the default locale is changed.
+     * <p>
+     * The Java Virtual Machine sets the default locale during startup based
+     * on the host environment. It is used by many locale-sensitive methods
+     * if no locale is explicitly specified.
+     * <p>
+     * Since changing the default locale may affect many different areas of
+     * functionality, this method should only be used if the caller is
+     * prepared to reinitialize locale-sensitive code running within the
+     * same Java Virtual Machine.
+     * <p>
+     *
+     * @param category - the specified category to set the default locale
+     * @param newLocale - the new default locale
+     * @throws SecurityException - if a security manager exists and its
+     *     checkPermission method doesn't allow the operation.
+     * @throws NullPointerException - if category and/or newLocale is null
+     * @see SecurityManager.checkPermission(java.security.Permission)
+     * @see PropertyPermission
+     * @see #getDefault(Locale.Category)
+     * @since 1.7
+     */
+    public static synchronized void setDefault(Locale.Category category,
+        Locale newLocale) {
+        if (category == null)
+            throw new NullPointerException("Category cannot be NULL");
         if (newLocale == null)
             throw new NullPointerException("Can't set default locale to NULL");
 
         SecurityManager sm = System.getSecurityManager();
         if (sm != null) sm.checkPermission(new PropertyPermission
                         ("user.language", "write"));
-            defaultLocale = newLocale;
+        switch (category) {
+        case DISPLAY:
+            defaultDisplayLocale = newLocale;
+            break;
+        case FORMAT:
+            defaultFormatLocale = newLocale;
+            break;
+        default:
+            assert false: "Unknown Category";
+        }
     }
 
     /**
@@ -474,6 +913,11 @@
     /**
      * Returns a list of all 2-letter country codes defined in ISO 3166.
      * Can be used to create Locales.
+     * <p>
+     * <b>Note:</b> The <code>Locale</code> class also supports other codes for
+     * country (region), such as 3-letter numeric UN M.49 area codes.
+     * Therefore, the list returned by this method does not contain ALL valid
+     * codes that can be used to create Locales.
      */
     public static String[] getISOCountries() {
         if (isoCountries == null) {
@@ -487,9 +931,16 @@
     /**
      * Returns a list of all 2-letter language codes defined in ISO 639.
      * Can be used to create Locales.
-     * [NOTE:  ISO 639 is not a stable standard-- some languages' codes have changed.
+     * <p>
+     * <b>Note:</b>
+     * <ul>
+     * <li>ISO 639 is not a stable standard&mdash; some languages' codes have changed.
      * The list this function returns includes both the new and the old codes for the
-     * languages whose codes have changed.]
+     * languages whose codes have changed.
+     * <li>The <code>Locale</code> class also supports language codes up to
+     * 8 characters in length.  Therefore, the list returned by this method does
+     * not contain ALL valid codes that can be used to create Locales.
+     * </ul>
      */
     public static String[] getISOLanguages() {
         if (isoLanguages == null) {
@@ -510,100 +961,516 @@
     }
 
     /**
-     * Returns the language code for this locale, which will either be the empty string
-     * or a lowercase ISO 639 code.
-     * <p>NOTE:  ISO 639 is not a stable standard-- some languages' codes have changed.
+     * Returns the language code of this Locale.
+     *
+     * <p><b>Note:</b> ISO 639 is not a stable standard&mdash; some languages' codes have changed.
      * Locale's constructor recognizes both the new and the old codes for the languages
      * whose codes have changed, but this function always returns the old code.  If you
-     * want to check for a specific language whose code has changed, don't do <pre>
-     * if (locale.getLanguage().equals("he"))
+     * want to check for a specific language whose code has changed, don't do
+     * <pre>
+     * if (locale.getLanguage().equals("he")) // BAD!
      *    ...
-     * </pre>Instead, do<pre>
-     * if (locale.getLanguage().equals(new Locale("he", "", "").getLanguage()))
-     *    ...</pre>
+     * </pre>
+     * Instead, do
+     * <pre>
+     * if (locale.getLanguage().equals(new Locale("he").getLanguage()))
+     *    ...
+     * </pre>
+     * @return The language code, or the empty string if none is defined.
      * @see #getDisplayLanguage
      */
     public String getLanguage() {
-        return language;
+        return _baseLocale.getLanguage();
     }
 
     /**
-     * Returns the country/region code for this locale, which will
-     * either be the empty string or an uppercase ISO 3166 2-letter code.
+     * Returns the script for this locale, which should
+     * either be the empty string or an ISO 15924 4-letter script
+     * code. The first letter is uppercase and the rest are
+     * lowercase, for example, 'Latn', 'Cyrl'.
+     *
+     * @return The script code, or the empty string if none is defined.
+     * @see #getDisplayScript
+     * @since 1.7
+     */
+    public String getScript() {
+        return _baseLocale.getScript();
+    }
+
+    /**
+     * Returns the country/region code for this locale, which should
+     * either be the empty string, an uppercase ISO 3166 2-letter code,
+     * or a UN M.49 3-digit code.
+     *
+     * @return The country/region code, or the empty string if none is defined.
      * @see #getDisplayCountry
      */
     public String getCountry() {
-        return country;
+        return _baseLocale.getRegion();
     }
 
     /**
      * Returns the variant code for this locale.
+     *
+     * @return The variant code, or the empty string if none is defined.
      * @see #getDisplayVariant
      */
     public String getVariant() {
-        return variant;
+        return _baseLocale.getVariant();
+    }
+
+    /**
+     * Returns the extension (or private use) value associated with
+     * the specified key, or null if there is no extension
+     * associated with the key. To be well-formed, the key must be one
+     * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so
+     * for example 'z' and 'Z' represent the same extension.
+     *
+     * @param key the extension key
+     * @return The extension, or null if this locale defines no
+     * extension for the specified key.
+     * @throws IllegalArgumentException if key is not well-formed
+     * @see #PRIVATE_USE_EXTENSION
+     * @see #UNICODE_LOCALE_EXTENSION
+     * @since 1.7
+     */
+    public String getExtension(char key) {
+        if (!LocaleExtensions.isValidKey(key)) {
+            throw new IllegalArgumentException("Ill-formed extension key: " + key);
+        }
+        return _extensions.getExtensionValue(key);
+    }
+
+    /**
+     * Returns the set of extension keys associated with this locale, or the
+     * empty set if it has no extensions. The returned set is unmodifiable.
+     * The keys will all be lower-case.
+     *
+     * @return The set of extension keys, or the empty set if this locale has
+     * no extensions.
+     * @since 1.7
+     */
+    public Set<Character> getExtensionKeys() {
+        return _extensions.getKeys();
+    }
+
+    /**
+     * Returns the set of unicode locale attributes associated with
+     * this locale, or the empty set if it has no attributes. The
+     * returned set is unmodifiable.
+     *
+     * @return The set of attributes.
+     * @since 1.7
+     */
+    public Set<String> getUnicodeLocaleAttributes() {
+        return _extensions.getUnicodeLocaleAttributes();
+    }
+
+    /**
+     * Returns the Unicode locale type associated with the specified Unicode locale key
+     * for this locale. Returns the empty string for keys that are defined with no type.
+     * Returns null if the key is not defined. Keys are case-insensitive. The key must
+     * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is
+     * thrown.
+     *
+     * @param key the Unicode locale key
+     * @return The Unicode locale type associated with the key, or null if the
+     * locale does not define the key.
+     * @throws IllegalArgumentException if the key is not well-formed
+     * @throws NullPointerException if <code>key</code> is null
+     * @since 1.7
+     */
+    public String getUnicodeLocaleType(String key) {
+        if (!UnicodeLocaleExtension.isKey(key)) {
+            throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key);
+        }
+        return _extensions.getUnicodeLocaleType(key);
+    }
+
+    /**
+     * Returns the set of Unicode locale keys defined by this locale, or the empty set if
+     * this locale has none.  The returned set is immutable.  Keys are all lower case.
+     *
+     * @return The set of Unicode locale keys, or the empty set if this locale has
+     * no Unicode locale keywords.
+     * @since 1.7
+     */
+    public Set<String> getUnicodeLocaleKeys() {
+        return _extensions.getUnicodeLocaleKeys();
     }
 
     /**
-     * Getter for the programmatic name of the entire locale,
-     * with the language, country and variant separated by underbars.
-     * Language is always lower case, and country is always upper case.
-     * If the language is missing, the string will begin with an underbar.
-     * If both the language and country fields are missing, this function
-     * will return the empty string, even if the variant field is filled in
-     * (you can't have a locale with just a variant-- the variant must accompany
-     * a valid language or country code).
-     * Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC"
+     * Package locale method returning the Locale's BaseLocale,
+     * used by ResourceBundle
+     * @return base locale of this Locale
+     */
+    BaseLocale getBaseLocale() {
+        return _baseLocale;
+    }
+
+    /**
+     * Package local method returning the Locale's LocaleExtensions,
+     * used by ResourceBundle
+     * @return locale exnteions of this Locale
+     */
+     LocaleExtensions getLocaleExtensions() {
+         return _extensions;
+     }
+
+    /**
+     * Returns a string representation of this <code>Locale</code>
+     * object, consisting of language, country, variant, script,
+     * and extensions as below:
+     * <p><blockquote>
+     * language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions
+     * </blockquote>
+     *
+     * Language is always lower case, country is always upper case, script is always title
+     * case, and extensions are always lower case.  Extensions and private use subtags
+     * will be in canonical order as explained in {@link #toLanguageTag}.
+     *
+     * <p>When the locale has neither script nor extensions, the result is the same as in
+     * Java 6 and prior.
+     *
+     * <p>If both the language and country fields are missing, this function will return
+     * the empty string, even if the variant, script, or extensions field is present (you
+     * can't have a locale with just a variant, the variant must accompany a well-formed
+     * language or country code).
+     *
+     * <p>If script or extensions are present and variant is missing, no underscore is
+     * added before the "#".
+     *
+     * <p>This behavior is designed to support debugging and to be compatible with
+     * previous uses of <code>toString</code> that expected language, country, and variant
+     * fields only.  To represent a Locale as a String for interchange purposes, use
+     * {@link #toLanguageTag}.
+     *
+     * <p>Examples: <ul><tt>
+     * <li>en
+     * <li>de_DE
+     * <li>_GB
+     * <li>en_US_WIN
+     * <li>de__POSIX
+     * <li>zh_CN_#Hans
+     * <li>zh_TW_#Hant-x-java
+     * <li>th_TH_TH_#u-nu-thai</tt></ul>
+     *
+     * @return A string representation of the Locale, for debugging.
      * @see #getDisplayName
+     * @see #toLanguageTag
      */
     public final String toString() {
-        boolean l = language.length() != 0;
-        boolean c = country.length() != 0;
-        boolean v = variant.length() != 0;
-        StringBuilder result = new StringBuilder(language);
-        if (c||(l&&v)) {
-            result.append('_').append(country); // This may just append '_'
+        boolean l = (_baseLocale.getLanguage().length() != 0);
+        boolean s = (_baseLocale.getScript().length() != 0);
+        boolean r = (_baseLocale.getRegion().length() != 0);
+        boolean v = (_baseLocale.getVariant().length() != 0);
+        boolean e = (_extensions.getID().length() != 0);
+
+        StringBuilder result = new StringBuilder(_baseLocale.getLanguage());
+        if (r || (l && v)) {
+            result.append('_')
+                .append(_baseLocale.getRegion()); // This may just append '_'
+        }
+        if (v && (l || r)) {
+            result.append('_')
+                .append(_baseLocale.getVariant());
         }
-        if (v&&(l||c)) {
-            result.append('_').append(variant);
+
+        if (s && (l || r)) {
+            result.append("_#")
+                .append(_baseLocale.getScript());
         }
+
+        if (e && (l || r)) {
+            result.append('_');
+            if (!s) {
+                result.append('#');
+            }
+            result.append(_extensions.getID());
+        }
+
         return result.toString();
     }
 
     /**
-     * Returns a three-letter abbreviation for this locale's language.  If the locale
-     * doesn't specify a language, this will be the empty string.  Otherwise, this will
-     * be a lowercase ISO 639-2/T language code.
-     * The ISO 639-2 language codes can be found on-line at
-     * <a href="http://www.loc.gov/standards/iso639-2/englangn.html">
-     * <code>http://www.loc.gov/standards/iso639-2/englangn.html</code>.</a>
-     * @exception MissingResourceException Throws MissingResourceException if the
+     * Returns a well-formed IETF BCP 47 language tag representing
+     * this locale.
+     *
+     * <p>If this <code>Locale</code> has a language, country, or
+     * variant that does not satisfy the IETF BCP 47 language tag
+     * syntax requirements, this method handles these fields as
+     * described below:
+     *
+     * <p><b>Language:</b> If language is empty, or not <a
+     * href="#def_language" >well-formed</a> (for example "a" or
+     * "e2"), it will be emitted as "und" (Undetermined).
+     *
+     * <p><b>Country:</b> If country is not <a
+     * href="#def_region">well-formed</a> (for example "12" or "USA"),
+     * it will be omitted.
+     *
+     * <p><b>Variant:</b> If variant <b>is</b> <a
+     * href="#def_variant">well-formed</a>, each sub-segment
+     * (delimited by '-' or '_') is emitted as a subtag.  Otherwise:
+     * <ul>
+     *
+     * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code>
+     * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first
+     * ill-formed sub-segment and all following will be appended to
+     * the private use subtag.  The first appended subtag will be
+     * "lvariant", followed by the sub-segments in order, separated by
+     * hyphen. For example, "x-lvariant-WIN",
+     * "Oracle-x-lvariant-JDK-Standard-Edition".
+     *
+     * <li>if any sub-segment does not match
+     * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated
+     * and the problematic sub-segment and all following sub-segments
+     * will be omitted.  If the remainder is non-empty, it will be
+     * emitted as a private use subtag as above (even if the remainder
+     * turns out to be well-formed).  For example,
+     * "Solaris_isjustthecoolestthing" is emitted as
+     * "x-lvariant-Solaris", not as "solaris".</li></ul>
+     *
+     * <p><b>Compatibility special cases:</b><ul>
+     *
+     * <li>The language codes "iw", "ji", and "in" are handled
+     * specially. Java uses these deprecated codes for compatibility
+     * reasons. The <code>toLanguageTag</code> method converts these
+     * three codes (and only these three) to "he", "yi", and "id"
+     * respectively.
+     *
+     * <li>A locale with language "no", country "NO", and variant
+     * "NY", representing Norwegian Nynorsk, will be represented as
+     * having language "nn", country "NO", and empty variant. This is
+     * because some JVMs used the deprecated form to represent the
+     * user's default locale, and for compatibility reasons that Take a has
+     * not been changed.</ul>
+     *
+     * <p><b>Note:</b> Although the language tag created by this
+     * method is well-formed (satisfies the syntax requirements
+     * defined by the IETF BCP 47 specification), it is not
+     * necessarily a valid BCP 47 language tag.  For example,
+     * <pre>
+     *   new Locale("xx", "YY").toLanguageTag();</pre>
+     *
+     * will return "xx-YY", but the language subtag "xx" and the
+     * region subtag "YY" are invalid because they are not registered
+     * in the IANA Language Subtag Registry.
+     *
+     * @return a BCP47 language tag representing the locale
+     * @see #forLanguageTag(String)
+     * @since 1.7
+     */
+    public String toLanguageTag() {
+        LanguageTag tag = LanguageTag.parseLocale(_baseLocale, _extensions);
+        StringBuilder buf = new StringBuilder();
+
+        String subtag = tag.getLanguage();
+        buf.append(LanguageTag.canonicalizeLanguage(subtag));
+
+        subtag = tag.getScript();
+        if (subtag.length() > 0) {
+            buf.append(LanguageTag.SEP);
+            buf.append(LanguageTag.canonicalizeScript(subtag));
+        }
+
+        subtag = tag.getRegion();
+        if (subtag.length() > 0) {
+            buf.append(LanguageTag.SEP);
+            buf.append(LanguageTag.canonicalizeRegion(subtag));
+        }
+
+        List<String>subtags = tag.getVariants();
+        for (String s : subtags) {
+            buf.append(LanguageTag.SEP);
+            // preserve casing
+            buf.append(s);
+        }
+
+        subtags = tag.getExtensions();
+        for (String s : subtags) {
+            buf.append(LanguageTag.SEP);
+            buf.append(LanguageTag.canonicalizeExtension(s));
+        }
+
+        subtag = tag.getPrivateuse();
+        if (subtag.length() > 0) {
+            buf.append(LanguageTag.SEP).append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP);
+            // preserve casing
+            buf.append(subtag);
+        }
+
+        return buf.toString();
+    }
+
+    /**
+     * Returns a locale for the specified IETF BCP 47 language tag string.
+     *
+     * <p>If the specified language tag contains any ill-formed subtags,
+     * the first such subtag and all following subtags are ignored.  Compare
+     * to {@link Locale.Builder#setLanguageTag} which throws an exception
+     * in this case.
+     *
+     * <p>The following <b>conversions</b> are performed:<ul>
+     *
+     * <li>The language code "und" is mapped to language "".
+     *
+     * <li>The language codes "he", "yi", and "id" are mapped to "iw",
+     * "ji", and "in" respectively. (This is the same canonicalization
+     * that's done in Locale's constructors.)
+     *
+     * <li>The portion of a private use subtag prefixed by "lvariant",
+     * if any, is removed and appended to the variant field in the
+     * result locale (without case normalization).  If it is then
+     * empty, the private use subtag is discarded:
+     *
+     * <pre>
+     *     Locale loc;
+     *     loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX);
+     *     loc.getVariant(); // returns "POSIX"
+     *     loc.getExtension('x'); // returns null
+     *
+     *     loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def");
+     *     loc.getVariant(); // returns "POSIX_Abc_Def"
+     *     loc.getExtension('x'); // returns "urp"
+     * </pre>
+     *
+     * <li>When the languageTag argument contains an extlang subtag,
+     * the first such subtag is used as the language, and the primary
+     * language subtag and other extlang subtags are ignored:
+     *
+     * <pre>
+     *     Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao"
+     *     Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US"
+     * </pre>
+     *
+     * <li>Case is normalized except for variant tags, which are left
+     * unchanged.  Language is normalized to lower case, script to
+     * title case, country to upper case, and extensions to lower
+     * case.
+     *
+     * <li>If, after processing, the locale would exactly match either
+     * ja_JP_JP or th_TH_TH with no extensions, the appropriate
+     * extensions are added as though the constructor had been called:
+     *
+     * <pre>
+     *    Locale.forLanguageTag("ja-JP-x-lvariant-JP).toLanguageTag();
+     *    // returns ja-JP-u-ca-japanese-x-lvariant-JP
+     *    Locale.forLanguageTag("th-TH-x-lvariant-TH).toLanguageTag();
+     *    // returns th-TH-u-nu-thai-x-lvariant-TH
+     * <pre></ul>
+     *
+     * <p>This implements the 'Language-Tag' production of BCP47, and
+     * so supports grandfathered (regular and irregular) as well as
+     * private use language tags.  Stand alone private use tags are
+     * represented as empty language and extension 'x-whatever',
+     * and grandfathered tags are converted to their canonical replacements
+     * where they exist.
+     *
+     * <p>Grandfathered tags with canonical replacements are as follows:
+     *
+     * <table>
+     * <tbody align="center">
+     * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>modern replacement</th></tr>
+     * <tr><td>art-lojban</td><td>&nbsp;</td><td>jbo</td></tr>
+     * <tr><td>i-ami</td><td>&nbsp;</td><td>ami</td></tr>
+     * <tr><td>i-bnn</td><td>&nbsp;</td><td>bnn</td></tr>
+     * <tr><td>i-hak</td><td>&nbsp;</td><td>hak</td></tr>
+     * <tr><td>i-klingon</td><td>&nbsp;</td><td>tlh</td></tr>
+     * <tr><td>i-lux</td><td>&nbsp;</td><td>lb</td></tr>
+     * <tr><td>i-navajo</td><td>&nbsp;</td><td>nv</td></tr>
+     * <tr><td>i-pwn</td><td>&nbsp;</td><td>pwn</td></tr>
+     * <tr><td>i-tao</td><td>&nbsp;</td><td>tao</td></tr>
+     * <tr><td>i-tay</td><td>&nbsp;</td><td>tay</td></tr>
+     * <tr><td>i-tsu</td><td>&nbsp;</td><td>tsu</td></tr>
+     * <tr><td>no-bok</td><td>&nbsp;</td><td>nb</td></tr>
+     * <tr><td>no-nyn</td><td>&nbsp;</td><td>nn</td></tr>
+     * <tr><td>sgn-BE-FR</td><td>&nbsp;</td><td>sfb</td></tr>
+     * <tr><td>sgn-BE-NL</td><td>&nbsp;</td><td>vgt</td></tr>
+     * <tr><td>sgn-CH-DE</td><td>&nbsp;</td><td>sgg</td></tr>
+     * <tr><td>zh-guoyu</td><td>&nbsp;</td><td>cmn</td></tr>
+     * <tr><td>zh-hakka</td><td>&nbsp;</td><td>hak</td></tr>
+     * <tr><td>zh-min-nan</td><td>&nbsp;</td><td>nan</td></tr>
+     * <tr><td>zh-xiang</td><td>&nbsp;</td><td>hsn</td></tr>
+     * </tbody>
+     * </table>
+     *
+     * <p>Grandfathered tags with no modern replacement will be
+     * converted as follows:
+     *
+     * <table>
+     * <tbody align="center">
+     * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>converts to</th></tr>
+     * <tr><td>cel-gaulish</td><td>&nbsp;</td><td>xtg-x-cel-gaulish</td></tr>
+     * <tr><td>en-GB-oed</td><td>&nbsp;</td><td>en-GB-x-oed</td></tr>
+     * <tr><td>i-default</td><td>&nbsp;</td><td>en-x-i-default</td></tr>
+     * <tr><td>i-enochian</td><td>&nbsp;</td><td>und-x-i-enochian</td></tr>
+     * <tr><td>i-mingo</td><td>&nbsp;</td><td>see-x-i-mingo</td></tr>
+     * <tr><td>zh-min</td><td>&nbsp;</td><td>nan-x-zh-min</td></tr>
+     * </tbody>
+     * </table>
+     *
+     * <p>For a list of all grandfathered tags, see the
+     * IANA Language Subtag Registry (search for "Type: grandfathered").
+     *
+     * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code>
+     * and <code>forLanguageTag</code> will round-trip.
+     *
+     * @param languageTag the language tag
+     * @return The locale that best represents the language tag.
+     * @throws NullPointerException if <code>languageTag</code> is <code>null</code>
+     * @see #toLanguageTag()
+     * @see java.util.Locale.Builder#setLanguageTag(String)
+     * @since 1.7
+     */
+    public static Locale forLanguageTag(String languageTag) {
+        LanguageTag tag = LanguageTag.parse(languageTag, null);
+        InternalLocaleBuilder bldr = new InternalLocaleBuilder();
+        bldr.setLanguageTag(tag);
+        return getInstance(bldr.getBaseLocale(), bldr.getLocaleExtensions());
+    }
+
+    /**
+     * Returns a three-letter abbreviation of this locale's language.
+     * If the language matches an ISO 639-1 two-letter code, the
+     * corresponding ISO 639-2/T three-letter lowercase code is
+     * returned.  The ISO 639-2 language codes can be found on-line,
+     * see "Codes for the Representation of Names of Languages Part 2:
+     * Alpha-3 Code".  If the locale specifies a three-letter
+     * language, the language is returned as is.  If the locale does
+     * not specify a language the empty string is returned.
+     *
+     * @return A three-letter abbreviation of this locale's language.
+     * @exception MissingResourceException Throws MissingResourceException if
      * three-letter language abbreviation is not available for this locale.
      */
     public String getISO3Language() throws MissingResourceException {
-        String language3 = getISO3Code(language, LocaleISOData.isoLanguageTable);
+        String language3 = getISO3Code(_baseLocale.getLanguage(), LocaleISOData.isoLanguageTable);
         if (language3 == null) {
             throw new MissingResourceException("Couldn't find 3-letter language code for "
-                    + language, "FormatData_" + toString(), "ShortLanguage");
+                    + _baseLocale.getLanguage(), "FormatData_" + toString(), "ShortLanguage");
         }
         return language3;
     }
 
     /**
-     * Returns a three-letter abbreviation for this locale's country.  If the locale
-     * doesn't specify a country, this will be the empty string.  Otherwise, this will
-     * be an uppercase ISO 3166 3-letter country code.
-     * The ISO 3166-2 country codes can be found on-line at
-     * <a href="http://www.davros.org/misc/iso3166.txt">
-     * <code>http://www.davros.org/misc/iso3166.txt</code>.</a>
+     * Returns a three-letter abbreviation for this locale's country.
+     * If the country matches an ISO 3166-1 alpha-2 code, the
+     * corresponding ISO 3166-1 alpha-3 uppercase code is returned.
+     * If the locale doesn't specify a country, this will be the empty
+     * string.
+     *
+     * <p>The ISO 3166-1 codes can be found on-line.
+     *
+     * @return A three-letter abbreviation of this locale's country.
      * @exception MissingResourceException Throws MissingResourceException if the
      * three-letter country abbreviation is not available for this locale.
      */
     public String getISO3Country() throws MissingResourceException {
-        String country3 = getISO3Code(country, LocaleISOData.isoCountryTable);
+        String country3 = getISO3Code(_baseLocale.getRegion(), LocaleISOData.isoCountryTable);
         if (country3 == null) {
             throw new MissingResourceException("Couldn't find 3-letter country code for "
-                    + country, "FormatData_" + toString(), "ShortCountry");
+                    + _baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry");
         }
         return country3;
     }
@@ -642,7 +1509,7 @@
      * value.  If the locale doesn't specify a language, this function returns the empty string.
      */
     public final String getDisplayLanguage() {
-        return getDisplayLanguage(getDefault());
+        return getDisplayLanguage(getDefault(Category.DISPLAY));
     }
 
     /**
@@ -661,7 +1528,33 @@
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayLanguage(Locale inLocale) {
-        return getDisplayString(language, inLocale, DISPLAY_LANGUAGE);
+        return getDisplayString(_baseLocale.getLanguage(), inLocale, DISPLAY_LANGUAGE);
+    }
+
+    /**
+     * Returns a name for the the locale's script that is appropriate for display to
+     * the user. If possible, the name will be localized for the default locale.  Returns
+     * the empty string if this locale doesn't specify a script code.
+     *
+     * @return the display name of the script code for the current default locale
+     * @since 1.7
+     */
+    public String getDisplayScript() {
+        return getDisplayScript(getDefault());
+    }
+
+    /**
+     * Returns a name for the locale's script that is appropriate
+     * for display to the user. If possible, the name will be
+     * localized for the given locale. Returns the empty string if
+     * this locale doesn't specify a script code.
+     *
+     * @return the display name of the script code for the current default locale
+     * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
+     * @since 1.7
+     */
+    public String getDisplayScript(Locale inLocale) {
+        return getDisplayString(_baseLocale.getScript(), inLocale, DISPLAY_SCRIPT);
     }
 
     /**
@@ -677,7 +1570,7 @@
      * value.  If the locale doesn't specify a country, this function returns the empty string.
      */
     public final String getDisplayCountry() {
-        return getDisplayCountry(getDefault());
+        return getDisplayCountry(getDefault(Category.DISPLAY));
     }
 
     /**
@@ -696,7 +1589,7 @@
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayCountry(Locale inLocale) {
-        return getDisplayString(country, inLocale, DISPLAY_COUNTRY);
+        return getDisplayString(_baseLocale.getRegion(), inLocale, DISPLAY_COUNTRY);
     }
 
     private String getDisplayString(String code, Locale inLocale, int type) {
@@ -744,7 +1637,7 @@
      * doesn't specify a variant code, this function returns the empty string.
      */
     public final String getDisplayVariant() {
-        return getDisplayVariant(getDefault());
+        return getDisplayVariant(getDefault(Category.DISPLAY));
     }
 
     /**
@@ -755,7 +1648,7 @@
      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayVariant(Locale inLocale) {
-        if (variant.length() == 0)
+        if (_baseLocale.getVariant().length() == 0)
             return "";
 
         OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
@@ -776,39 +1669,44 @@
 
     /**
      * Returns a name for the locale that is appropriate for display to the
-     * user.  This will be the values returned by getDisplayLanguage(), getDisplayCountry(),
-     * and getDisplayVariant() assembled into a single string.  The display name will have
-     * one of the following forms:<p><blockquote>
-     * language (country, variant)<p>
-     * language (country)<p>
-     * language (variant)<p>
-     * country (variant)<p>
-     * language<p>
-     * country<p>
-     * variant<p></blockquote>
-     * depending on which fields are specified in the locale.  If the language, country,
-     * and variant fields are all empty, this function returns the empty string.
+     * user. This will be the values returned by getDisplayLanguage(),
+     * getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled
+     * into a single string. The the non-empty values are used in order,
+     * with the second and subsequent names in parentheses.  For example:
+     * <blockquote>
+     * language (script, country, variant)<br>
+     * language (country)<br>
+     * language (variant)<br>
+     * script (country)<br>
+     * country<br>
+     * </blockquote>
+     * depending on which fields are specified in the locale.  If the
+     * language, sacript, country, and variant fields are all empty,
+     * this function returns the empty string.
      */
     public final String getDisplayName() {
-        return getDisplayName(getDefault());
+        return getDisplayName(getDefault(Category.DISPLAY));
     }
 
     /**
-     * Returns a name for the locale that is appropriate for display to the
-     * user.  This will be the values returned by getDisplayLanguage(), getDisplayCountry(),
-     * and getDisplayVariant() assembled into a single string.  The display name will have
-     * one of the following forms:<p><blockquote>
-     * language (country, variant)<p>
-     * language (country)<p>
-     * language (variant)<p>
-     * country (variant)<p>
-     * language<p>
-     * country<p>
-     * variant<p></blockquote>
-     * depending on which fields are specified in the locale.  If the language, country,
-     * and variant fields are all empty, this function returns the empty string.
+     * Returns a name for the locale that is appropriate for display
+     * to the user.  This will be the values returned by
+     * getDisplayLanguage(), getDisplayScript(),getDisplayCountry(),
+     * and getDisplayVariant() assembled into a single string.
+     * The non-empty values are used in order,
+     * with the second and subsequent names in parentheses.  For example:
+     * <blockquote>
+     * language (script, country, variant)<br>
+     * language (country)<br>
+     * language (variant)<br>
+     * script (country)<br>
+     * country<br>
+     * </blockquote>
+     * depending on which fields are specified in the locale.  If the
+     * language, script, country, and variant fields are all empty,
+     * this function returns the empty string.
      *
-     * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
+     * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
      */
     public String getDisplayName(Locale inLocale) {
         OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
@@ -888,7 +1786,7 @@
     }
 
     /**
-     * Overrides Cloneable
+     * Overrides Cloneable.
      */
     public Object clone()
     {
@@ -908,7 +1806,7 @@
     public int hashCode() {
         int hc = hashCodeValue;
         if (hc == 0) {
-            hc = (language.hashCode() << 8) ^ country.hashCode() ^ (variant.hashCode() << 4);
+            hc = _baseLocale.hashCode() ^ _extensions.hashCode();
             hashCodeValue = hc;
         }
         return hc;
@@ -918,8 +1816,8 @@
 
     /**
      * Returns true if this Locale is equal to another object.  A Locale is
-     * deemed equal to another Locale with identical language, country,
-     * and variant, and unequal to all other objects.
+     * deemed equal to another Locale with identical language, script, country,
+     * variant and extensions, and unequal to all other objects.
      *
      * @return true if this Locale is equal to the specified object.
      */
@@ -929,47 +1827,24 @@
             return true;
         if (!(obj instanceof Locale))
             return false;
-        Locale other = (Locale) obj;
-        return language == other.language
-            && country == other.country
-            && variant == other.variant;
+        BaseLocale otherBase = ((Locale)obj)._baseLocale;
+        LocaleExtensions otherExt = ((Locale)obj)._extensions;
+        return _baseLocale.equals(otherBase) && _extensions.equals(otherExt);
     }
 
     // ================= privates =====================================
 
-    // XXX instance and class variables. For now keep these separate, since it is
-    // faster to match. Later, make into single string.
-
-    /**
-     * @serial
-     * @see #getLanguage
-     */
-    private final String language;
+    private transient BaseLocale _baseLocale;
+    private transient LocaleExtensions _extensions;
 
     /**
-     * @serial
-     * @see #getCountry
-     */
-    private final String country;
-
-    /**
-     * @serial
-     * @see #getVariant
-     */
-    private final String variant;
-
-    /**
-     * Placeholder for the object's hash code.  Always -1.
-     * @serial
-     */
-    private volatile int hashcode = -1;        // lazy evaluate
-
-    /**
-     * Calculated hashcode to fix 4518797.
+     * Calculated hashcode
      */
     private transient volatile int hashCodeValue = 0;
 
     private static Locale defaultLocale = null;
+    private static Locale defaultDisplayLocale = null;
+    private static Locale defaultFormatLocale = null;
 
     /**
      * Return an array of the display names of the variant.
@@ -978,7 +1853,7 @@
      */
     private String[] getDisplayVariantArray(OpenListResourceBundle bundle, Locale inLocale) {
         // Split the variant name into tokens separated by '_'.
-        StringTokenizer tokenizer = new StringTokenizer(variant, "_");
+        StringTokenizer tokenizer = new StringTokenizer(_baseLocale.getVariant(), "_");
         String[] names = new String[tokenizer.countTokens()];
 
         // For each variant token, lookup the display name.  If
@@ -1056,49 +1931,102 @@
     }
 
     /**
-     * Replace the deserialized Locale object with a newly
-     * created object. Newer language codes are replaced with older ISO
-     * codes. The country and variant codes are replaced with internalized
-     * String copies.
+     * @serialField language    String
+     *      language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage()</a>)
+     * @serialField country     String
+     *      country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry()</a>)
+     * @serialField variant     String
+     *      variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant()</a>)
+     * @serialField hashcode    int
+     *      deprectated, for forward compatibility only
+     * @serialField script      String
+     *      script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript()</a>)
+     * @serialField extensions  String
+     *      canonical representation of extensions, that is,
+     *      BCP47 extensions in alphabetical order followed by
+     *      BCP47 private use subtags, all in lower case letters
+     *      separated by HYPHEN-MINUS characters.
+     *      (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>,
+     *      <a href="java/util/Locale.html#getExtension(char)">getExtension(char)</a>)
+     */
+    private static final ObjectStreamField[] serialPersistentFields = {
+        new ObjectStreamField("language", String.class),
+        new ObjectStreamField("country", String.class),
+        new ObjectStreamField("variant", String.class),
+        new ObjectStreamField("hashcode", int.class),
+        new ObjectStreamField("script", String.class),
+        new ObjectStreamField("extensions", String.class),
+    };
+
+    /**
+     * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>.
+     * @param out the <code>ObjectOutputStream</code> to write
+     * @throws IOException
+     * @since 1.7
+     */
+    private void writeObject(ObjectOutputStream out) throws IOException {
+        ObjectOutputStream.PutField fields = out.putFields();
+        fields.put("language", _baseLocale.getLanguage());
+        fields.put("script", _baseLocale.getScript());
+        fields.put("country", _baseLocale.getRegion());
+        fields.put("variant", _baseLocale.getVariant());
+        fields.put("extensions", _extensions.getID());
+        fields.put("hashcode", -1); // place holder just for backward support
+        out.writeFields();
+    }
+
+    /**
+     * Deserialize this <code>Locale</code>.
+     * @param in the <code>ObjectInputStream</code> to read
+     * @throws IOException
+     * @throws ClassNotFoundException
+     * @throws IllformdLocaleException
+     * @since 1.7
+     */
+    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+        ObjectInputStream.GetField fields = in.readFields();
+        String language = (String)fields.get("language", "");
+        String script = (String)fields.get("script", "");
+        String country = (String)fields.get("country", "");
+        String variant = (String)fields.get("variant", "");
+        String extStr = (String)fields.get("extensions", "");
+        _baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant);
+        try {
+            InternalLocaleBuilder bldr = new InternalLocaleBuilder();
+            bldr.setExtensions(extStr);
+            _extensions = bldr.getLocaleExtensions();
+        } catch (LocaleSyntaxException e) {
+            throw new IllformedLocaleException(e.getMessage());
+        }
+    }
+
+    /**
+     * Returns a cached <code>Locale</code> instance equivalent to
+     * the deserialized <code>Locale</code>. When serialized
+     * language, country and variant fields read from the object data stream
+     * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions
+     * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code>
+     * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script
+     * type is "thai"). See <a href="Locale.html#special_cases_constructor"/>Special Cases</a>
+     * for more information.
+     *
+     * @return an instance of <code>Locale</code> equivalent to
+     * the deserialized <code>Locale</code>.
+     * @throws java.io.ObjectStreamException
      */
     private Object readResolve() throws java.io.ObjectStreamException {
-        return getInstance(language, country, variant);
+        return getInstance(_baseLocale.getLanguage(), _baseLocale.getScript(),
+                _baseLocale.getRegion(), _baseLocale.getVariant(), _extensions);
     }
 
     private static volatile String[] isoLanguages = null;
 
     private static volatile String[] isoCountries = null;
 
-    /*
-     * Locale needs its own, locale insensitive version of toLowerCase to
-     * avoid circularity problems between Locale and String.
-     * The most straightforward algorithm is used. Look at optimizations later.
-     */
-    private String toLowerCase(String str) {
-        char[] buf = new char[str.length()];
-        for (int i = 0; i < buf.length; i++) {
-            buf[i] = Character.toLowerCase(str.charAt(i));
-        }
-        return new String( buf );
-    }
-
-    /*
-     * Locale needs its own, locale insensitive version of toUpperCase to
-     * avoid circularity problems between Locale and String.
-     * The most straightforward algorithm is used. Look at optimizations later.
-     */
-    private String toUpperCase(String str) {
-        char[] buf = new char[str.length()];
-        for (int i = 0; i < buf.length; i++) {
-            buf[i] = Character.toUpperCase(str.charAt(i));
-        }
-        return new String( buf );
-    }
-
-    private String convertOldISOCodes(String language) {
+    private static String convertOldISOCodes(String language) {
         // we accept both the old and the new ISO codes for the languages whose ISO
         // codes have changed, but we always store the OLD code, for backward compatibility
-        language = toLowerCase(language).intern();
+        language = AsciiUtil.toLowerString(language).intern();
         if (language == "he") {
             return "iw";
         } else if (language == "yi") {
@@ -1110,6 +2038,25 @@
         }
     }
 
+    private static LocaleExtensions getCompatibilityExtensions(String language, String script, String country, String variant) {
+        LocaleExtensions extensions = LocaleExtensions.EMPTY_EXTENSIONS;
+        // Special cases for backward compatibility support
+        if (AsciiUtil.caseIgnoreMatch(language, "ja")
+                && script.length() == 0
+                && AsciiUtil.caseIgnoreMatch(country, "JP")
+                && AsciiUtil.caseIgnoreMatch(variant, "JP")) {
+            // ja_JP_JP -> u-ca-japanese (calendar = japanese)
+            extensions = LocaleExtensions.CALENDAR_JAPANESE;
+        } else if (AsciiUtil.caseIgnoreMatch(language, "th")
+                && script.length() == 0
+                && AsciiUtil.caseIgnoreMatch(country, "TH")
+                && AsciiUtil.caseIgnoreMatch(variant, "TH")) {
+            // th_TH_TH -> u-nu-thai (numbersystem = thai)
+            extensions = LocaleExtensions.NUMBER_THAI;
+        }
+        return extensions;
+    }
+
     /**
      * Obtains a localized locale names from a LocaleNameProvider
      * implementation.
@@ -1133,6 +2080,8 @@
                 return localeNameProvider.getDisplayCountry(code, locale);
             case DISPLAY_VARIANT:
                 return localeNameProvider.getDisplayVariant(code, locale);
+            case DISPLAY_SCRIPT:
+                return localeNameProvider.getDisplayScript(code, locale);
             default:
                 assert false; // shouldn't happen
             }
@@ -1140,4 +2089,370 @@
             return null;
         }
     }
+
+    /**
+     * Enum for locale categories.  These locale categories are used to get/set
+     * the default locale for the specific functionality represented by the
+     * category.
+     *
+     * @see #getDefault(Locale.Category)
+     * @see #setDefault(Locale.Category, Locale)
+     * @since 1.7
+     */
+    public enum Category {
+
+        /**
+         * Category used to represent the default locale for
+         * displaying user interfaces.
+         */
+        DISPLAY,
+
+        /**
+         * Category used to represent the default locale for
+         * formatting dates, numbers, and/or currencies.
+         */
+        FORMAT,
+    }
+
+    /**
+     * <code>Builder</code> is used to build instances of <code>Locale</code>
+     * from values configured by the setters.  Unlike the <code>Locale</code>
+     * constructors, the <code>Builder</code> checks if a value configured by a
+     * setter satisfies the syntax requirements defined by the <code>Locale</code>
+     * class.  A <code>Locale</code> object created by a <code>Builder</code> is
+     * well-formed and can be transformed to a well-formed IETF BCP 47 language tag
+     * without losing information.
+     *
+     * <p><b>Note:</b> The <code>Locale</code> class does not provide any
+     * syntactic restrictions on variant, while BCP 47 requires each variant
+     * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3
+     * alphanumerics.  The method <code>setVariant</code> throws
+     * <code>IllformedLocaleException</code> for a variant that does not satisfy
+     * this restriction. If it is necessary to support such a variant, use a
+     * Locale constructor.  However, keep in mind that a <code>Locale</code>
+     * object created this way might lose the variant information when
+     * transformed to a BCP 47 language tag.
+     *
+     * <p>The following example shows how to create a <code>Locale</code> object
+     * with the <code>Builder</code>.
+     * <blockquote>
+     * <pre>
+     *     Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();
+     * </pre>
+     * </blockquote>
+     *
+     * <p>Builders can be reused; <code>clear()</code> resets all
+     * fields to their default values.
+     *
+     * @see Locale#forLanguageTag
+     * @since 1.7
+     */
+    public static final class Builder {
+        private InternalLocaleBuilder _locbld;
+
+        /**
+         * Constructs an empty Builder. The default value of all
+         * fields, extensions, and private use information is the
+         * empty string.
+         */
+        public Builder() {
+            _locbld = new InternalLocaleBuilder();
+        }
+
+        /**
+         * Resets the <code>Builder</code> to match the provided
+         * <code>locale</code>.  Existing state is discarded.
+         *
+         * <p>All fields of the locale must be well-formed, see {@link Locale}.
+         *
+         * <p>Locales with any ill-formed fields cause
+         * <code>IllformedLocaleException</code> to be thrown, except for the
+         * following three cases which are accepted for compatibility
+         * reasons:<ul>
+         * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese"
+         * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai"
+         * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul>
+         *
+         * @param locale the locale
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>locale</code> has
+         * any ill-formed fields.
+         * @throws NullPointerException if <code>locale</code> is null.
+         */
+        public Builder setLocale(Locale locale) {
+            try {
+                _locbld.setLocale(locale._baseLocale, locale._extensions);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Resets the Builder to match the provided IETF BCP 47
+         * language tag.  Discards the existing state.  Null and the
+         * empty string cause the builder to be reset, like {@link
+         * #clear}.  Grandfathered tags (see {@link
+         * Locale#forLanguageTag}) are converted to their canonical
+         * form before being processed.  Otherwise, the language tag
+         * must be well-formed (see {@link Locale}) or an exception is
+         * thrown (unlike <code>Locale.forLanguageTag</code>, which
+         * just discards ill-formed and following portions of the
+         * tag).
+         *
+         * @param languageTag the language tag
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed
+         * @see Locale#forLanguageTag(String)
+         */
+        public Builder setLanguageTag(String languageTag) {
+            ParseStatus sts = new ParseStatus();
+            LanguageTag tag = LanguageTag.parse(languageTag, sts);
+            if (sts.isError()) {
+                throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex());
+            }
+            _locbld.setLanguageTag(tag);
+
+            return this;
+        }
+
+        /**
+         * Sets the language.  If <code>language</code> is the empty string or
+         * null, the language in this <code>Builder</code> is removed.  Otherwise,
+         * the language must be <a href="./Locale.html#def_language">well-formed</a>
+         * or an exception is thrown.
+         *
+         * <p>The typical language value is a two or three-letter language
+         * code as defined in ISO639.
+         *
+         * @param language the language
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>language</code> is ill-formed
+         */
+        public Builder setLanguage(String language) {
+            try {
+                _locbld.setLanguage(language);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the script. If <code>script</code> is null or the empty string,
+         * the script in this <code>Builder</code> is removed.
+         * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an
+         * exception is thrown.
+         *
+         * <p>The typical script value is a four-letter script code as defined by ISO 15924.
+         *
+         * @param script the script
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>script</code> is ill-formed
+         */
+        public Builder setScript(String script) {
+            try {
+                _locbld.setScript(script);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the region.  If region is null or the empty string, the region
+         * in this <code>Builder</code> is removed.  Otherwise,
+         * the region must be <a href="./Locale.html#def_region">well-formed</a> or an
+         * exception is thrown.
+         *
+         * <p>The typical region value is a two-letter ISO 3166 code or a
+         * three-digit UN M.49 area code.
+         *
+         * <p>The country value in the <code>Locale</code> created by the
+         * <code>Builder</code> is always normalized to upper case.
+         *
+         * @param region the region
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>region</code> is ill-formed
+         */
+        public Builder setRegion(String region) {
+            try {
+                _locbld.setRegion(region);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the variant.  If variant is null or the empty string, the
+         * variant in this <code>Builder</code> is removed.  Otherwise, it
+         * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a>
+         * subtags, or an exception is thrown.
+         *
+         * <p><b>Note:</b> This method checks if <code>variant</code>
+         * satisfies the IETF BCP 47 variant subtag's syntax requirements,
+         * and normalizes the value to lowercase letters.  However,
+         * the <code>Locale</code> class does not impose any syntactic
+         * restriction on variant, and the variant value in
+         * <code>Locale</code> is case sensitive.  To set such a variant,
+         * use a Locale constructor.
+         *
+         * @param variant the variant
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>variant</code> is ill-formed
+         */
+        public Builder setVariant(String variant) {
+            try {
+                _locbld.setVariant(variant);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the extension for the given key. If the value is null or the
+         * empty string, the extension is removed.  Otherwise, the extension
+         * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception
+         * is thrown.
+         *
+         * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION
+         * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension.
+         * Setting a value for this key replaces any existing Unicode locale key/type
+         * pairs with those defined in the extension.
+         *
+         * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION
+         * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be
+         * well-formed, the value for this key needs only to have subtags of one to
+         * eight alphanumeric characters, not two to eight as in the general case.
+         *
+         * @param key the extension key
+         * @param value the extension value
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>key</code> is illegal
+         * or <code>value</code> is ill-formed
+         * @see #setUnicodeLocaleKeyword(String, String)
+         */
+        public Builder setExtension(char key, String value) {
+            try {
+                _locbld.setExtension(key, value);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Sets the Unicode locale keyword type for the given key.  If the type
+         * is null, the Unicode keyword is removed.  Otherwise, the key must be
+         * non-null and both key and type must be <a
+         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
+         * is thrown.
+         *
+         * <p>Keys and types are converted to lower case.
+         *
+         * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension}
+         * replaces all Unicode locale keywords with those defined in the
+         * extension.
+         *
+         * @param key the Unicode locale key
+         * @param type the Unicode locale type
+         * @return This builder.
+         * @throws IllformedLocaleException if <code>key</code> or <code>type</code>
+         * is ill-formed
+         * @throws NullPointerException if <code>key</code> is null
+         * @see #setExtension(char, String)
+         */
+        public Builder setUnicodeLocaleKeyword(String key, String type) {
+            try {
+                _locbld.setUnicodeLocaleKeyword(key, type);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Adds a unicode locale attribute, if not already present, otherwise
+         * has no effect.  The attribute must not be null and must be <a
+         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
+         * is thrown.
+         *
+         * @param attribute the attribute
+         * @return This builder.
+         * @throws NullPointerException if <code>attribute</code> is null
+         * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
+         * @see #setExtension(char, String)
+         */
+        public Builder addUnicodeLocaleAttribute(String attribute) {
+            try {
+                _locbld.addUnicodeLocaleAttribute(attribute);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Removes a unicode locale attribute, if present, otherwise has no
+         * effect.  The attribute must not be null and must be <a
+         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
+         * is thrown.
+         *
+         * <p>Attribute comparision for removal is case-insensitive.
+         *
+         * @param attribute the attribute
+         * @return This builder.
+         * @throws NullPointerException if <code>attribute</code> is null
+         * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
+         * @see #setExtension(char, String)
+         */
+        public Builder removeUnicodeLocaleAttribute(String attribute) {
+            try {
+                _locbld.removeUnicodeLocaleAttribute(attribute);
+            } catch (LocaleSyntaxException e) {
+                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
+            }
+            return this;
+        }
+
+        /**
+         * Resets the builder to its initial, empty state.
+         *
+         * @return This builder.
+         */
+        public Builder clear() {
+            _locbld.clear();
+            return this;
+        }
+
+        /**
+         * Resets the extensions to their initial, empty state.
+         * Language, script, region and variant are unchanged.
+         *
+         * @return This builder.
+         * @see #setExtension(char, String)
+         */
+        public Builder clearExtensions() {
+            _locbld.clearExtensions();
+            return this;
+        }
+
+        /**
+         * Returns an instance of <code>Locale</code> created from the fields set
+         * on this builder.
+         *
+         * <p>This applies the conversions listed in {@link Locale#forLanguageTag}
+         * when constructing a Locale. (Grandfathered tags are handled in
+         * {@link #setLanguageTag}.)
+         *
+         * @return A Locale.
+         */
+        public Locale build() {
+            BaseLocale baseloc = _locbld.getBaseLocale();
+            LocaleExtensions extensions = _locbld.getLocaleExtensions();
+            return Locale.getInstance(baseloc, extensions);
+        }
+    }
 }
--- a/src/share/classes/java/util/Properties.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/Properties.java	Fri Sep 24 16:41:32 2010 -0700
@@ -912,9 +912,13 @@
      *
      * <p>The specified stream remains open after this method returns.
      *
-     * @param os the output stream on which to emit the XML document.
-     * @param comment a description of the property list, or <code>null</code>
-     *        if no comment is desired.
+     * @param os        the output stream on which to emit the XML document.
+     * @param comment   a description of the property list, or <code>null</code>
+     *                  if no comment is desired.
+     * @param  encoding the name of a supported
+     *                  <a href="../lang/package-summary.html#charenc">
+     *                  character encoding</a>
+     *
      * @throws IOException if writing to the specified output stream
      *         results in an <tt>IOException</tt>.
      * @throws NullPointerException if <code>os</code> is <code>null</code>,
--- a/src/share/classes/java/util/ResourceBundle.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/ResourceBundle.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -56,16 +56,18 @@
 import java.util.concurrent.ConcurrentMap;
 import java.util.jar.JarEntry;
 
+import sun.util.locale.BaseLocale;
+import sun.util.locale.LocaleExtensions;
+import sun.util.locale.LocaleObjectCache;
+
 
 /**
  *
- * Resource bundles contain locale-specific objects.
- * When your program needs a locale-specific resource,
- * a <code>String</code> for example, your program can load it
- * from the resource bundle that is appropriate for the
- * current user's locale. In this way, you can write
- * program code that is largely independent of the user's
- * locale isolating most, if not all, of the locale-specific
+ * Resource bundles contain locale-specific objects.  When your program needs a
+ * locale-specific resource, a <code>String</code> for example, your program can
+ * load it from the resource bundle that is appropriate for the current user's
+ * locale. In this way, you can write program code that is largely independent
+ * of the user's locale isolating most, if not all, of the locale-specific
  * information in resource bundles.
  *
  * <p>
@@ -854,87 +856,140 @@
     }
 
     /**
-     * Gets a resource bundle using the specified base name, locale, and class loader.
+     * Gets a resource bundle using the specified base name, locale, and class
+     * loader.
+     *
+     * <p><a name="default_behavior"/>This method behaves the same as calling
+     * {@link #getBundle(String, Locale, ClassLoader, Control)} passing a
+     * default instance of {@link Control}. The following describes this behavior.
+     *
+     * <p><code>getBundle</code> uses the base name, the specified locale, and
+     * the default locale (obtained from {@link java.util.Locale#getDefault()
+     * Locale.getDefault}) to generate a sequence of <a
+     * name="candidates"><em>candidate bundle names</em></a>.  If the specified
+     * locale's language, script, country, and variant are all empty strings,
+     * then the base name is the only candidate bundle name.  Otherwise, a list
+     * of candidate locales is generated from the attribute values of the
+     * specified locale (language, script, country and variant) and appended to
+     * the base name.  Typically, this will look like the following:
+     *
+     * <pre>
+     *     baseName + "_" + language + "_" + script + "_" + country + "_" + variant
+     *     baseName + "_" + language + "_" + script + "_" + country
+     *     baseName + "_" + language + "_" + script
+     *     baseName + "_" + language + "_" + country + "_" + variant
+     *     baseName + "_" + language + "_" + country
+     *     baseName + "_" + language
+     * </pre>
      *
-     * <p><a name="default_behavior"/>
-     * Conceptually, <code>getBundle</code> uses the following strategy for locating and instantiating
-     * resource bundles:
-     * <p>
-     * <code>getBundle</code> uses the base name, the specified locale, and the default
-     * locale (obtained from {@link java.util.Locale#getDefault() Locale.getDefault})
-     * to generate a sequence of <a name="candidates"><em>candidate bundle names</em></a>.
-     * If the specified locale's language, country, and variant are all empty
-     * strings, then the base name is the only candidate bundle name.
-     * Otherwise, the following sequence is generated from the attribute
-     * values of the specified locale (language1, country1, and variant1)
-     * and of the default locale (language2, country2, and variant2):
-     * <ul>
-     * <li> baseName + "_" + language1 + "_" + country1 + "_" + variant1
-     * <li> baseName + "_" + language1 + "_" + country1
-     * <li> baseName + "_" + language1
-     * <li> baseName + "_" + language2 + "_" + country2 + "_" + variant2
-     * <li> baseName + "_" + language2 + "_" + country2
-     * <li> baseName + "_" + language2
-     * <li> baseName
-     * </ul>
-     * <p>
-     * Candidate bundle names where the final component is an empty string are omitted.
-     * For example, if country1 is an empty string, the second candidate bundle name is omitted.
+     * <p>Candidate bundle names where the final component is an empty string
+     * are omitted, along with the underscore.  For example, if country is an
+     * empty string, the second and the fifth candidate bundle names above
+     * would be omitted.  Also, if script is an empty string, the candidate names
+     * including script are omitted.  For example, a locale with language "de"
+     * and variant "JAVA" will produce candidate names with base name
+     * "MyResource" below.
+     *
+     * <pre>
+     *     MyResource_de__JAVA
+     *     MyResource_de
+     * </pre>
+     *
+     * In the case that the variant contains one or more underscores ('_'), a
+     * sequence of bundle names generated by truncating the last underscore and
+     * the part following it is inserted after a candidate bundle name with the
+     * original variant.  For example, for a locale with language "en", script
+     * "Latn, country "US" and variant "WINDOWS_VISTA", and bundle base name
+     * "MyResource", the list of candidate bundle names below is generated:
+     *
+     * <pre>
+     * MyResource_en_Latn_US_WINDOWS_VISTA
+     * MyResource_en_Latn_US_WINDOWS
+     * MyResource_en_Latn_US
+     * MyResource_en_Latn
+     * MyResource_en_US_WINDOWS_VISTA
+     * MyResource_en_US_WINDOWS
+     * MyResource_en_US
+     * MyResource_en
+     * </pre>
+     *
+     * <blockquote><b>Note:</b> For some <code>Locale</code>s, the list of
+     * candidate bundle names contains extra names, or the order of bundle names
+     * is slightly modified.  See the description of the default implementation
+     * of {@link Control#getCandidateLocales(String, Locale)
+     * getCandidateLocales} for details.</blockquote>
      *
-     * <p>
-     * <code>getBundle</code> then iterates over the candidate bundle names to find the first
-     * one for which it can <em>instantiate</em> an actual resource bundle. For each candidate
-     * bundle name, it attempts to create a resource bundle:
-     * <ul>
-     * <li>
-     * First, it attempts to load a class using the candidate bundle name.
-     * If such a class can be found and loaded using the specified class loader, is assignment
-     * compatible with ResourceBundle, is accessible from ResourceBundle, and can be instantiated,
-     * <code>getBundle</code> creates a new instance of this class and uses it as the <em>result
-     * resource bundle</em>.
-     * <li>
-     * Otherwise, <code>getBundle</code> attempts to locate a property resource file.
-     * It generates a path name from the candidate bundle name by replacing all "." characters
-     * with "/" and appending the string ".properties".
-     * It attempts to find a "resource" with this name using
-     * {@link java.lang.ClassLoader#getResource(java.lang.String) ClassLoader.getResource}.
-     * (Note that a "resource" in the sense of <code>getResource</code> has nothing to do with
-     * the contents of a resource bundle, it is just a container of data, such as a file.)
-     * If it finds a "resource", it attempts to create a new
-     * {@link PropertyResourceBundle} instance from its contents.
-     * If successful, this instance becomes the <em>result resource bundle</em>.
-     * </ul>
+     * <p><code>getBundle</code> then iterates over the candidate bundle names
+     * to find the first one for which it can <em>instantiate</em> an actual
+     * resource bundle. It uses the default controls' {@link Control#getFormats
+     * getFormats} method, which generates two bundle names for each generated
+     * name, the first a class name and the second a properties file name. For
+     * each candidate bundle name, it attempts to create a resource bundle:
+     *
+     * <ul><li>First, it attempts to load a class using the generated class name.
+     * If such a class can be found and loaded using the specified class
+     * loader, is assignment compatible with ResourceBundle, is accessible from
+     * ResourceBundle, and can be instantiated, <code>getBundle</code> creates a
+     * new instance of this class and uses it as the <em>result resource
+     * bundle</em>.
+     *
+     * <li>Otherwise, <code>getBundle</code> attempts to locate a property
+     * resource file using the generated properties file name.  It generates a
+     * path name from the candidate bundle name by replacing all "." characters
+     * with "/" and appending the string ".properties".  It attempts to find a
+     * "resource" with this name using {@link
+     * java.lang.ClassLoader#getResource(java.lang.String)
+     * ClassLoader.getResource}.  (Note that a "resource" in the sense of
+     * <code>getResource</code> has nothing to do with the contents of a
+     * resource bundle, it is just a container of data, such as a file.)  If it
+     * finds a "resource", it attempts to create a new {@link
+     * PropertyResourceBundle} instance from its contents.  If successful, this
+     * instance becomes the <em>result resource bundle</em>.  </ul>
      *
-     * <p>
-     * If no result resource bundle has been found, a <code>MissingResourceException</code>
-     * is thrown.
+     * <p>This continues until a result resource bundle is instantiated or the
+     * list of candidate bundle names is exhausted.  If no matching resource
+     * bundle is found, the default control's {@link Control#getFallbackLocale
+     * getFallbackLocale} method is called, which returns the current default
+     * locale.  A new sequence of candidate locale names is generated using this
+     * locale and and searched again, as above.
+     *
+     * <p>If still no result bundle is found, the base name alone is looked up. If
+     * this still fails, a <code>MissingResourceException</code> is thrown.
      *
-     * <p><a name="parent_chain"/>
-     * Once a result resource bundle has been found, its <em>parent chain</em> is instantiated.
-     * <code>getBundle</code> iterates over the candidate bundle names that can be
-     * obtained by successively removing variant, country, and language
-     * (each time with the preceding "_") from the bundle name of the result resource bundle.
-     * As above, candidate bundle names where the final component is an empty string are omitted.
-     * With each of the candidate bundle names it attempts to instantiate a resource bundle, as
-     * described above.
-     * Whenever it succeeds, it calls the previously instantiated resource
+     * <p><a name="parent_chain"/> Once a result resource bundle has been found,
+     * its <em>parent chain</em> is instantiated.  If the result bundle already
+     * has a parent (perhaps because it was returned from a cache) the chain is
+     * complete.
+     *
+     * <p>Otherwise, <code>getBundle</code> examines the remainder of the
+     * candidate locale list that was used during the pass that generated the
+     * result resource bundle.  (As before, candidate bundle names where the
+     * final component is an empty string are omitted.)  When it comes to the
+     * end of the candidate list, it tries the plain bundle name.  With each of the
+     * candidate bundle names it attempts to instantiate a resource bundle (first
+     * looking for a class and then a properties file, as described above).
+     *
+     * <p>Whenever it succeeds, it calls the previously instantiated resource
      * bundle's {@link #setParent(java.util.ResourceBundle) setParent} method
-     * with the new resource bundle, unless the previously instantiated resource
-     * bundle already has a non-null parent.
+     * with the new resource bundle.  This continues until the list of names
+     * is exhausted or the current bundle already has a non-null parent.
+     *
+     * <p>Once the parent chain is complete, the bundle is returned.
      *
-     * <p>
-     * <code>getBundle</code> caches instantiated resource bundles and
-     * may return the same resource bundle instance multiple
-     * times.
+     * <p><b>Note:</b> <code>getBundle</code> caches instantiated resource
+     * bundles and might return the same resource bundle instance multiple times.
      *
-     * <p>
-     * The <code>baseName</code> argument should be a fully qualified class name. However, for
-     * compatibility with earlier versions, Sun's Java SE Runtime Environments do not verify this,
-     * and so it is possible to access <code>PropertyResourceBundle</code>s by specifying a
-     * path name (using "/") instead of a fully qualified class name (using ".").
+     * <p><b>Note:</b>The <code>baseName</code> argument should be a fully
+     * qualified class name. However, for compatibility with earlier versions,
+     * Sun's Java SE Runtime Environments do not verify this, and so it is
+     * possible to access <code>PropertyResourceBundle</code>s by specifying a
+     * path name (using "/") instead of a fully qualified class name (using
+     * ".").
      *
      * <p><a name="default_behavior_example"/>
-     * <strong>Example:</strong><br>The following class and property files are provided:
+     * <strong>Example:</strong>
+     * <p>
+     * The following class and property files are provided:
      * <pre>
      *     MyResources.class
      *     MyResources.properties
@@ -944,22 +999,26 @@
      *     MyResources_en.properties
      *     MyResources_es_ES.class
      * </pre>
-     * The contents of all files are valid (that is, public non-abstract subclasses of <code>ResourceBundle</code> for
-     * the ".class" files, syntactically correct ".properties" files).
-     * The default locale is <code>Locale("en", "GB")</code>.
-     * <p>
-     * Calling <code>getBundle</code> with the shown locale argument values instantiates
-     * resource bundles from the following sources:
-     * <ul>
-     * <li>Locale("fr", "CH"): result MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class
-     * <li>Locale("fr", "FR"): result MyResources_fr.properties, parent MyResources.class
-     * <li>Locale("de", "DE"): result MyResources_en.properties, parent MyResources.class
-     * <li>Locale("en", "US"): result MyResources_en.properties, parent MyResources.class
-     * <li>Locale("es", "ES"): result MyResources_es_ES.class, parent MyResources.class
-     * </ul>
-     * <p>The file MyResources_fr_CH.properties is never used because it is hidden by
-     * MyResources_fr_CH.class. Likewise, MyResources.properties is also hidden by
-     * MyResources.class.
+     *
+     * The contents of all files are valid (that is, public non-abstract
+     * subclasses of <code>ResourceBundle</code> for the ".class" files,
+     * syntactically correct ".properties" files).  The default locale is
+     * <code>Locale("en", "GB")</code>.
+     *
+     * <p>Calling <code>getBundle</code> with the locale arguments below will
+     * instantiate resource bundles as follows:
+     *
+     * <table>
+     * <tr><td>Locale("fr", "CH")</td><td>MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class</td></tr>
+     * <tr><td>Locale("fr", "FR")</td><td>MyResources_fr.properties, parent MyResources.class</td></tr>
+     * <tr><td>Locale("de", "DE")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
+     * <tr><td>Locale("en", "US")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
+     * <tr><td>Locale("es", "ES")</td><td>MyResources_es_ES.class, parent MyResources.class</td></tr>
+     * </table>
+     *
+     * <p>The file MyResources_fr_CH.properties is never used because it is
+     * hidden by the MyResources_fr_CH.class. Likewise, MyResources.properties
+     * is also hidden by MyResources.class.
      *
      * @param baseName the base name of the resource bundle, a fully qualified class name
      * @param locale the locale for which a resource bundle is desired
@@ -1095,8 +1154,6 @@
      * href="./ResourceBundle.html#parent_chain">parent chain</a> is
      * instantiated based on the list of candidate locales from which it was
      * found. Finally, the bundle is returned to the caller.</li>
-     *
-     *
      * </ol>
      *
      * <p>During the resource bundle loading process above, this factory
@@ -1119,7 +1176,6 @@
      * {@link Control#getTimeToLive(String,Locale)
      * control.getTimeToLive} for details.
      *
-     *
      * <p>The following is an example of the bundle loading process with the
      * default <code>ResourceBundle.Control</code> implementation.
      *
@@ -1131,7 +1187,6 @@
      * <li>Available resource bundles:
      * <code>foo/bar/Messages_fr.properties</code> and
      * <code>foo/bar/Messages.properties</code></li>
-     *
      * </ul>
      *
      * <p>First, <code>getBundle</code> tries loading a resource bundle in
@@ -1811,8 +1866,8 @@
      * handleGetObject} method returns <code>null</code>. Once the
      * <code>Set</code> has been created, the value is kept in this
      * <code>ResourceBundle</code> in order to avoid producing the
-     * same <code>Set</code> in the next calls.  Override this method
-     * in subclass implementations for faster handling.
+     * same <code>Set</code> in subsequent calls. Subclasses can
+     * override this method for faster handling.
      *
      * @return a <code>Set</code> of the keys contained only in this
      *        <code>ResourceBundle</code>
@@ -2177,24 +2232,133 @@
          * <code>ResourceBundle.getBundle</code> factory method loads only
          * the base bundle as the resulting resource bundle.
          *
-         * <p>It is not a requirement to return an immutable
-         * (unmodifiable) <code>List</code>. However, the returned
-         * <code>List</code> must not be mutated after it has been
-         * returned by <code>getCandidateLocales</code>.
+         * <p>It is not a requirement to return an immutable (unmodifiable)
+         * <code>List</code>. However, the returned <code>List</code> must not
+         * be mutated after it has been returned by
+         * <code>getCandidateLocales</code>.
          *
          * <p>The default implementation returns a <code>List</code> containing
-         * <code>Locale</code>s in the following sequence:
-         * <pre>
-         *     Locale(language, country, variant)
-         *     Locale(language, country)
-         *     Locale(language)
-         *     Locale.ROOT
-         * </pre>
-         * where <code>language</code>, <code>country</code> and
-         * <code>variant</code> are the language, country and variant values
-         * of the given <code>locale</code>, respectively. Locales where the
+         * <code>Locale</code>s using the rules described below.  In the
+         * description below, <em>L</em>, <em>S</em>, <em>C</em> and <em>V</em>
+         * respectively represent non-empty language, script, country, and
+         * variant.  For example, [<em>L</em>, <em>C</em>] represents a
+         * <code>Locale</code> that has non-empty values only for language and
+         * country.  The form <em>L</em>("xx") represents the (non-empty)
+         * language value is "xx".  For all cases, <code>Locale</code>s whose
          * final component values are empty strings are omitted.
          *
+         * <ol><li>For an input <code>Locale</code> with an empty script value,
+         * append candidate <code>Locale</code>s by omitting the final component
+         * one by one as below:
+         *
+         * <ul>
+         * <li> [<em>L</em>, <em>C</em>, <em>V</em>]
+         * <li> [<em>L</em>, <em>C</em>]
+         * <li> [<em>L</em>]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <li>For an input <code>Locale</code> with a non-empty script value,
+         * append candidate <code>Locale</code>s by omitting the final component
+         * up to language, then append candidates generated from the
+         * <code>Locale</code> with country and variant restored:
+         *
+         * <ul>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V</em>]
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>]
+         * <li> [<em>L</em>, <em>S</em>]
+         * <li> [<em>L</em>, <em>C</em>, <em>V</em>]
+         * <li> [<em>L</em>, <em>C</em>]
+         * <li> [<em>L</em>]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <li>For an input <code>Locale</code> with a variant value consisting
+         * of multiple subtags separated by underscore, generate candidate
+         * <code>Locale</code>s by omitting the variant subtags one by one, then
+         * insert them after every occurence of <code> Locale</code>s with the
+         * full variant value in the original list.  For example, if the
+         * the variant consists of two subtags <em>V1</em> and <em>V2</em>:
+         *
+         * <ul>
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>]
+         * <li> [<em>L</em>, <em>S</em>, <em>C</em>]
+         * <li> [<em>L</em>, <em>S</em>]
+         * <li> [<em>L</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]
+         * <li> [<em>L</em>, <em>C</em>, <em>V1</em>]
+         * <li> [<em>L</em>, <em>C</em>]
+         * <li> [<em>L</em>]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <li>Special cases for Chinese.  When an input <code>Locale</code> has the
+         * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or
+         * "Hant" (Traditional) might be supplied, depending on the country.
+         * When the country is "CN" (China) or "SG" (Singapore), "Hans" is supplied.
+         * When the country is "HK" (Hong Kong SAR China), "MO" (Macau SAR China),
+         * or "TW" (Taiwan), "Hant" is supplied.  For all other countries or when the country
+         * is empty, no script is supplied.  For example, for <code>Locale("zh", "CN")
+         * </code>, the candidate list will be:
+         * <ul>
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hans"), <em>C</em>("CN")]
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hans")]
+         * <li> [<em>L</em>("zh"), <em>C</em>("CN")]
+         * <li> [<em>L</em>("zh")]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * For <code>Locale("zh", "TW")</code>, the candidate list will be:
+         * <ul>
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hant"), <em>C</em>("TW")]
+         * <li> [<em>L</em>("zh"), <em>S</em>("Hant")]
+         * <li> [<em>L</em>("zh"), <em>C</em>("TW")]
+         * <li> [<em>L</em>("zh")]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <li>Special cases for Norwegian.  Both <code>Locale("no", "NO",
+         * "NY")</code> and <code>Locale("nn", "NO")</code> represent Norwegian
+         * Nynorsk.  When a locale's language is "nn", the standard candidate
+         * list is generated up to [<em>L</em>("nn")], and then the following
+         * candidates are added:
+         *
+         * <ul><li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("NY")]
+         * <li> [<em>L</em>("no"), <em>C</em>("NO")]
+         * <li> [<em>L</em>("no")]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * If the locale is exactly <code>Locale("no", "NO", "NY")</code>, it is first
+         * converted to <code>Locale("nn", "NO")</code> and then the above procedure is
+         * followed.
+         *
+         * <p>Also, Java treats the language "no" as a synonym of Norwegian
+         * Bokm&#xE5;l "nb".  Except for the single case <code>Locale("no",
+         * "NO", "NY")</code> (handled above), when an input <code>Locale</code>
+         * has language "no" or "nb", candidate <code>Locale</code>s with
+         * language code "no" and "nb" are interleaved, first using the
+         * requested language, then using its synonym. For example,
+         * <code>Locale("nb", "NO", "POSIX")</code> generates the following
+         * candidate list:
+         *
+         * <ul>
+         * <li> [<em>L</em>("nb"), <em>C</em>("NO"), <em>V</em>("POSIX")]
+         * <li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("POSIX")]
+         * <li> [<em>L</em>("nb"), <em>C</em>("NO")]
+         * <li> [<em>L</em>("no"), <em>C</em>("NO")]
+         * <li> [<em>L</em>("nb")]
+         * <li> [<em>L</em>("no")]
+         * <li> <code>Locale.ROOT</code>
+         * </ul>
+         *
+         * <code>Locale("no", "NO", "POSIX")</code> would generate the same list
+         * except that locales with "no" would appear before the corresponding
+         * locales with "nb".</li>
+         *
+         * </li>
+         * </ol>
+         *
          * <p>The default implementation uses an {@link ArrayList} that
          * overriding implementations may modify before returning it to the
          * caller. However, a subclass must not modify it after it has
@@ -2231,24 +2395,119 @@
             if (baseName == null) {
                 throw new NullPointerException();
             }
-            String language = locale.getLanguage();
-            String country = locale.getCountry();
-            String variant = locale.getVariant();
+            return new ArrayList<Locale>(CANDIDATES_CACHE.get(locale.getBaseLocale()));
+        }
+
+        private static final CandidateListCache CANDIDATES_CACHE = new CandidateListCache();
+
+        private static class CandidateListCache extends LocaleObjectCache<BaseLocale, List<Locale>> {
+            protected List<Locale> createObject(BaseLocale base) {
+                String language = base.getLanguage();
+                String script = base.getScript();
+                String region = base.getRegion();
+                String variant = base.getVariant();
 
-            List<Locale> locales = new ArrayList<Locale>(4);
-            if (variant.length() > 0) {
-                locales.add(locale);
+                // Special handling for Norwegian
+                boolean isNorwegianBokmal = false;
+                boolean isNorwegianNynorsk = false;
+                if (language.equals("no")) {
+                    if (region.equals("NO") && variant.equals("NY")) {
+                        variant = "";
+                        isNorwegianNynorsk = true;
+                    } else {
+                        isNorwegianBokmal = true;
+                    }
+                }
+                if (language.equals("nb") || isNorwegianBokmal) {
+                    List<Locale> tmpList = getDefaultList("nb", script, region, variant);
+                    // Insert a locale replacing "nb" with "no" for every list entry
+                    List<Locale> bokmalList = new LinkedList<Locale>();
+                    for (Locale l : tmpList) {
+                        bokmalList.add(l);
+                        if (l.getLanguage().length() == 0) {
+                            break;
+                        }
+                        bokmalList.add(Locale.getInstance("no", l.getScript(), l.getCountry(),
+                                l.getVariant(), LocaleExtensions.EMPTY_EXTENSIONS));
+                    }
+                    return bokmalList;
+                } else if (language.equals("nn") || isNorwegianNynorsk) {
+                    // Insert no_NO_NY, no_NO, no after nn
+                    List<Locale> nynorskList = getDefaultList("nn", script, region, variant);
+                    int idx = nynorskList.size() - 1;
+                    nynorskList.add(idx++, Locale.getInstance("no", "NO", "NY"));
+                    nynorskList.add(idx++, Locale.getInstance("no", "NO", ""));
+                    nynorskList.add(idx++, Locale.getInstance("no", "", ""));
+                    return nynorskList;
+                }
+                // Special handling for Chinese
+                else if (language.equals("zh")) {
+                    if (script.length() == 0 && region.length() > 0) {
+                        // Supply script for users who want to use zh_Hans/zh_Hant
+                        // as bundle names (recommended for Java7+)
+                        if (region.equals("TW") || region.equals("HK") || region.equals("MO")) {
+                            script = "Hant";
+                        } else if (region.equals("CN") || region.equals("SG")) {
+                            script = "Hans";
+                        }
+                    } else if (script.length() > 0 && region.length() == 0) {
+                        // Supply region(country) for users who still package Chinese
+                        // bundles using old convension.
+                        if (script.equals("Hans")) {
+                            region = "CN";
+                        } else if (script.equals("Hant")) {
+                            region = "TW";
+                        }
+                    }
+                }
+
+                return getDefaultList(language, script, region, variant);
             }
-            if (country.length() > 0) {
-                locales.add((locales.size() == 0) ?
-                            locale : Locale.getInstance(language, country, ""));
+
+            private static List<Locale> getDefaultList(String language, String script, String region, String variant) {
+                List<String> variants = null;
+
+                if (variant.length() > 0) {
+                    variants = new LinkedList<String>();
+                    int idx = variant.length();
+                    while (idx != -1) {
+                        variants.add(variant.substring(0, idx));
+                        idx = variant.lastIndexOf('_', --idx);
+                    }
+                }
+
+                LinkedList<Locale> list = new LinkedList<Locale>();
+
+                if (variants != null) {
+                    for (String v : variants) {
+                        list.add(Locale.getInstance(language, script, region, v, LocaleExtensions.EMPTY_EXTENSIONS));
+                    }
+                }
+                if (region.length() > 0) {
+                    list.add(Locale.getInstance(language, script, region, "", LocaleExtensions.EMPTY_EXTENSIONS));
+                }
+                if (script.length() > 0) {
+                    list.add(Locale.getInstance(language, script, "", "", LocaleExtensions.EMPTY_EXTENSIONS));
+
+                    // With script, after truncating variant, region and script,
+                    // start over without script.
+                    if (variants != null) {
+                        for (String v : variants) {
+                            list.add(Locale.getInstance(language, "", region, v, LocaleExtensions.EMPTY_EXTENSIONS));
+                        }
+                    }
+                    if (region.length() > 0) {
+                        list.add(Locale.getInstance(language, "", region, "", LocaleExtensions.EMPTY_EXTENSIONS));
+                    }
+                }
+                if (language.length() > 0) {
+                    list.add(Locale.getInstance(language, "", "", "", LocaleExtensions.EMPTY_EXTENSIONS));
+                }
+                // Add root locale at the end
+                list.add(Locale.ROOT);
+
+                return list;
             }
-            if (language.length() > 0) {
-                locales.add((locales.size() == 0) ?
-                            locale : Locale.getInstance(language, "", ""));
-            }
-            locales.add(Locale.ROOT);
-            return locales;
         }
 
         /**
@@ -2606,13 +2865,14 @@
          *
          * <p>This implementation returns the following value:
          * <pre>
-         *     baseName + "_" + language + "_" + country + "_" + variant
+         *     baseName + "_" + language + "_" + script + "_" + country + "_" + variant
          * </pre>
-         * where <code>language</code>, <code>country</code> and
-         * <code>variant</code> are the language, country and variant values
-         * of <code>locale</code>, respectively. Final component values that
-         * are empty Strings are omitted along with the preceding '_'. If
-         * all of the values are empty strings, then <code>baseName</code>
+         * where <code>language</code>, <code>script</code>, <code>country</code>,
+         * and <code>variant</code> are the language, script, country, and variant
+         * values of <code>locale</code>, respectively. Final component values that
+         * are empty Strings are omitted along with the preceding '_'.  When the
+         * script is empty, the script value is ommitted along with the preceding '_'.
+         * If all of the values are empty strings, then <code>baseName</code>
          * is returned.
          *
          * <p>For example, if <code>baseName</code> is
@@ -2643,6 +2903,7 @@
             }
 
             String language = locale.getLanguage();
+            String script = locale.getScript();
             String country = locale.getCountry();
             String variant = locale.getVariant();
 
@@ -2652,12 +2913,22 @@
 
             StringBuilder sb = new StringBuilder(baseName);
             sb.append('_');
-            if (variant != "") {
-                sb.append(language).append('_').append(country).append('_').append(variant);
-            } else if (country != "") {
-                sb.append(language).append('_').append(country);
+            if (script != "") {
+                if (variant != "") {
+                    sb.append(language).append('_').append(script).append('_').append(country).append('_').append(variant);
+                } else if (country != "") {
+                    sb.append(language).append('_').append(script).append('_').append(country);
+                } else {
+                    sb.append(language).append('_').append(script);
+                }
             } else {
-                sb.append(language);
+                if (variant != "") {
+                    sb.append(language).append('_').append(country).append('_').append(variant);
+                } else if (country != "") {
+                    sb.append(language).append('_').append(country);
+                } else {
+                    sb.append(language);
+                }
             }
             return sb.toString();
 
--- a/src/share/classes/java/util/Scanner.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/Scanner.java	Fri Sep 24 16:41:32 2010 -0700
@@ -582,7 +582,7 @@
         matcher = delimPattern.matcher(buf);
         matcher.useTransparentBounds(true);
         matcher.useAnchoringBounds(false);
-        useLocale(Locale.getDefault());
+        useLocale(Locale.getDefault(Locale.Category.FORMAT));
     }
 
     /**
@@ -2642,7 +2642,7 @@
      */
     public Scanner reset() {
         delimPattern = WHITESPACE_PATTERN;
-        useLocale(Locale.getDefault());
+        useLocale(Locale.getDefault(Locale.Category.FORMAT));
         useRadix(10);
         clearCaches();
         return this;
--- a/src/share/classes/java/util/TimeZone.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/TimeZone.java	Fri Sep 24 16:41:32 2010 -0700
@@ -312,7 +312,7 @@
      * @since 1.2
      */
     public final String getDisplayName() {
-        return getDisplayName(false, LONG, Locale.getDefault());
+        return getDisplayName(false, LONG, Locale.getDefault(Locale.Category.DISPLAY));
     }
 
     /**
@@ -342,7 +342,7 @@
      * @since 1.2
      */
     public final String getDisplayName(boolean daylight, int style) {
-        return getDisplayName(daylight, style, Locale.getDefault());
+        return getDisplayName(daylight, style, Locale.getDefault(Locale.Category.DISPLAY));
     }
 
     /**
--- a/src/share/classes/java/util/concurrent/ForkJoinPool.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/concurrent/ForkJoinPool.java	Fri Sep 24 16:41:32 2010 -0700
@@ -40,16 +40,23 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
-import java.util.concurrent.locks.Condition;
+import java.util.concurrent.AbstractExecutorService;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.RunnableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.locks.LockSupport;
 import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
 
 /**
  * An {@link ExecutorService} for running {@link ForkJoinTask}s.
  * A {@code ForkJoinPool} provides the entry point for submissions
- * from non-{@code ForkJoinTask}s, as well as management and
+ * from non-{@code ForkJoinTask} clients, as well as management and
  * monitoring operations.
  *
  * <p>A {@code ForkJoinPool} differs from other kinds of {@link
@@ -58,29 +65,19 @@
  * execute subtasks created by other active tasks (eventually blocking
  * waiting for work if none exist). This enables efficient processing
  * when most tasks spawn other subtasks (as do most {@code
- * ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed
- * execution of some plain {@code Runnable}- or {@code Callable}-
- * based activities along with {@code ForkJoinTask}s. When setting
- * {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may
- * also be appropriate for use with fine-grained tasks of any form
- * that are never joined. Otherwise, other {@code ExecutorService}
- * implementations are typically more appropriate choices.
+ * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
+ * constructors, {@code ForkJoinPool}s may also be appropriate for use
+ * with event-style tasks that are never joined.
  *
  * <p>A {@code ForkJoinPool} is constructed with a given target
  * parallelism level; by default, equal to the number of available
- * processors. Unless configured otherwise via {@link
- * #setMaintainsParallelism}, the pool attempts to maintain this
- * number of active (or available) threads by dynamically adding,
- * suspending, or resuming internal worker threads, even if some tasks
- * are stalled waiting to join others. However, no such adjustments
- * are performed in the face of blocked IO or other unmanaged
- * synchronization. The nested {@link ManagedBlocker} interface
- * enables extension of the kinds of synchronization accommodated.
- * The target parallelism level may also be changed dynamically
- * ({@link #setParallelism}). The total number of threads may be
- * limited using method {@link #setMaximumPoolSize}, in which case it
- * may become possible for the activities of a pool to stall due to
- * the lack of available threads to process new tasks.
+ * processors. The pool attempts to maintain enough active (or
+ * available) threads by dynamically adding, suspending, or resuming
+ * internal worker threads, even if some tasks are stalled waiting to
+ * join others. However, no such adjustments are guaranteed in the
+ * face of blocked IO or other unmanaged synchronization. The nested
+ * {@link ManagedBlocker} interface enables extension of the kinds of
+ * synchronization accommodated.
  *
  * <p>In addition to execution and lifecycle control methods, this
  * class provides status check methods (for example
@@ -89,6 +86,40 @@
  * {@link #toString} returns indications of pool state in a
  * convenient form for informal monitoring.
  *
+ * <p> As is the case with other ExecutorServices, there are three
+ * main task execution methods summarized in the following
+ * table. These are designed to be used by clients not already engaged
+ * in fork/join computations in the current pool.  The main forms of
+ * these methods accept instances of {@code ForkJoinTask}, but
+ * overloaded forms also allow mixed execution of plain {@code
+ * Runnable}- or {@code Callable}- based activities as well.  However,
+ * tasks that are already executing in a pool should normally
+ * <em>NOT</em> use these pool execution methods, but instead use the
+ * within-computation forms listed in the table.
+ *
+ * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ *  <tr>
+ *    <td></td>
+ *    <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
+ *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
+ *  </tr>
+ *  <tr>
+ *    <td> <b>Arrange async execution</td>
+ *    <td> {@link #execute(ForkJoinTask)}</td>
+ *    <td> {@link ForkJoinTask#fork}</td>
+ *  </tr>
+ *  <tr>
+ *    <td> <b>Await and obtain result</td>
+ *    <td> {@link #invoke(ForkJoinTask)}</td>
+ *    <td> {@link ForkJoinTask#invoke}</td>
+ *  </tr>
+ *  <tr>
+ *    <td> <b>Arrange exec and obtain Future</td>
+ *    <td> {@link #submit(ForkJoinTask)}</td>
+ *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
+ *  </tr>
+ * </table>
+ *
  * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
  * used for all parallel task execution in a program or subsystem.
  * Otherwise, use would not usually outweigh the construction and
@@ -113,7 +144,8 @@
  * {@code IllegalArgumentException}.
  *
  * <p>This implementation rejects submitted tasks (that is, by throwing
- * {@link RejectedExecutionException}) only when the pool is shut down.
+ * {@link RejectedExecutionException}) only when the pool is shut down
+ * or internal resources have been exhausted.
  *
  * @since 1.7
  * @author Doug Lea
@@ -121,16 +153,247 @@
 public class ForkJoinPool extends AbstractExecutorService {
 
     /*
-     * See the extended comments interspersed below for design,
-     * rationale, and walkthroughs.
+     * Implementation Overview
+     *
+     * This class provides the central bookkeeping and control for a
+     * set of worker threads: Submissions from non-FJ threads enter
+     * into a submission queue. Workers take these tasks and typically
+     * split them into subtasks that may be stolen by other workers.
+     * The main work-stealing mechanics implemented in class
+     * ForkJoinWorkerThread give first priority to processing tasks
+     * from their own queues (LIFO or FIFO, depending on mode), then
+     * to randomized FIFO steals of tasks in other worker queues, and
+     * lastly to new submissions. These mechanics do not consider
+     * affinities, loads, cache localities, etc, so rarely provide the
+     * best possible performance on a given machine, but portably
+     * provide good throughput by averaging over these factors.
+     * (Further, even if we did try to use such information, we do not
+     * usually have a basis for exploiting it. For example, some sets
+     * of tasks profit from cache affinities, but others are harmed by
+     * cache pollution effects.)
+     *
+     * Beyond work-stealing support and essential bookkeeping, the
+     * main responsibility of this framework is to take actions when
+     * one worker is waiting to join a task stolen (or always held by)
+     * another.  Because we are multiplexing many tasks on to a pool
+     * of workers, we can't just let them block (as in Thread.join).
+     * We also cannot just reassign the joiner's run-time stack with
+     * another and replace it later, which would be a form of
+     * "continuation", that even if possible is not necessarily a good
+     * idea. Given that the creation costs of most threads on most
+     * systems mainly surrounds setting up runtime stacks, thread
+     * creation and switching is usually not much more expensive than
+     * stack creation and switching, and is more flexible). Instead we
+     * combine two tactics:
+     *
+     *   Helping: Arranging for the joiner to execute some task that it
+     *      would be running if the steal had not occurred.  Method
+     *      ForkJoinWorkerThread.helpJoinTask tracks joining->stealing
+     *      links to try to find such a task.
+     *
+     *   Compensating: Unless there are already enough live threads,
+     *      method helpMaintainParallelism() may create or
+     *      re-activate a spare thread to compensate for blocked
+     *      joiners until they unblock.
+     *
+     * It is impossible to keep exactly the target (parallelism)
+     * number of threads running at any given time.  Determining
+     * existence of conservatively safe helping targets, the
+     * availability of already-created spares, and the apparent need
+     * to create new spares are all racy and require heuristic
+     * guidance, so we rely on multiple retries of each.  Compensation
+     * occurs in slow-motion. It is triggered only upon timeouts of
+     * Object.wait used for joins. This reduces poor decisions that
+     * would otherwise be made when threads are waiting for others
+     * that are stalled because of unrelated activities such as
+     * garbage collection.
+     *
+     * The ManagedBlocker extension API can't use helping so relies
+     * only on compensation in method awaitBlocker.
+     *
+     * The main throughput advantages of work-stealing stem from
+     * decentralized control -- workers mostly steal tasks from each
+     * other. We do not want to negate this by creating bottlenecks
+     * implementing other management responsibilities. So we use a
+     * collection of techniques that avoid, reduce, or cope well with
+     * contention. These entail several instances of bit-packing into
+     * CASable fields to maintain only the minimally required
+     * atomicity. To enable such packing, we restrict maximum
+     * parallelism to (1<<15)-1 (enabling twice this (to accommodate
+     * unbalanced increments and decrements) to fit into a 16 bit
+     * field, which is far in excess of normal operating range.  Even
+     * though updates to some of these bookkeeping fields do sometimes
+     * contend with each other, they don't normally cache-contend with
+     * updates to others enough to warrant memory padding or
+     * isolation. So they are all held as fields of ForkJoinPool
+     * objects.  The main capabilities are as follows:
+     *
+     * 1. Creating and removing workers. Workers are recorded in the
+     * "workers" array. This is an array as opposed to some other data
+     * structure to support index-based random steals by workers.
+     * Updates to the array recording new workers and unrecording
+     * terminated ones are protected from each other by a lock
+     * (workerLock) but the array is otherwise concurrently readable,
+     * and accessed directly by workers. To simplify index-based
+     * operations, the array size is always a power of two, and all
+     * readers must tolerate null slots. Currently, all worker thread
+     * creation is on-demand, triggered by task submissions,
+     * replacement of terminated workers, and/or compensation for
+     * blocked workers. However, all other support code is set up to
+     * work with other policies.
+     *
+     * To ensure that we do not hold on to worker references that
+     * would prevent GC, ALL accesses to workers are via indices into
+     * the workers array (which is one source of some of the unusual
+     * code constructions here). In essence, the workers array serves
+     * as a WeakReference mechanism. Thus for example the event queue
+     * stores worker indices, not worker references. Access to the
+     * workers in associated methods (for example releaseEventWaiters)
+     * must both index-check and null-check the IDs. All such accesses
+     * ignore bad IDs by returning out early from what they are doing,
+     * since this can only be associated with shutdown, in which case
+     * it is OK to give up. On termination, we just clobber these
+     * data structures without trying to use them.
+     *
+     * 2. Bookkeeping for dynamically adding and removing workers. We
+     * aim to approximately maintain the given level of parallelism.
+     * When some workers are known to be blocked (on joins or via
+     * ManagedBlocker), we may create or resume others to take their
+     * place until they unblock (see below). Implementing this
+     * requires counts of the number of "running" threads (i.e., those
+     * that are neither blocked nor artificially suspended) as well as
+     * the total number.  These two values are packed into one field,
+     * "workerCounts" because we need accurate snapshots when deciding
+     * to create, resume or suspend.  Note however that the
+     * correspondence of these counts to reality is not guaranteed. In
+     * particular updates for unblocked threads may lag until they
+     * actually wake up.
+     *
+     * 3. Maintaining global run state. The run state of the pool
+     * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
+     * those in other Executor implementations, as well as a count of
+     * "active" workers -- those that are, or soon will be, or
+     * recently were executing tasks. The runLevel and active count
+     * are packed together in order to correctly trigger shutdown and
+     * termination. Without care, active counts can be subject to very
+     * high contention.  We substantially reduce this contention by
+     * relaxing update rules.  A worker must claim active status
+     * prospectively, by activating if it sees that a submitted or
+     * stealable task exists (it may find after activating that the
+     * task no longer exists). It stays active while processing this
+     * task (if it exists) and any other local subtasks it produces,
+     * until it cannot find any other tasks. It then tries
+     * inactivating (see method preStep), but upon update contention
+     * instead scans for more tasks, later retrying inactivation if it
+     * doesn't find any.
+     *
+     * 4. Managing idle workers waiting for tasks. We cannot let
+     * workers spin indefinitely scanning for tasks when none are
+     * available. On the other hand, we must quickly prod them into
+     * action when new tasks are submitted or generated.  We
+     * park/unpark these idle workers using an event-count scheme.
+     * Field eventCount is incremented upon events that may enable
+     * workers that previously could not find a task to now find one:
+     * Submission of a new task to the pool, or another worker pushing
+     * a task onto a previously empty queue.  (We also use this
+     * mechanism for configuration and termination actions that
+     * require wakeups of idle workers).  Each worker maintains its
+     * last known event count, and blocks when a scan for work did not
+     * find a task AND its lastEventCount matches the current
+     * eventCount. Waiting idle workers are recorded in a variant of
+     * Treiber stack headed by field eventWaiters which, when nonzero,
+     * encodes the thread index and count awaited for by the worker
+     * thread most recently calling eventSync. This thread in turn has
+     * a record (field nextEventWaiter) for the next waiting worker.
+     * In addition to allowing simpler decisions about need for
+     * wakeup, the event count bits in eventWaiters serve the role of
+     * tags to avoid ABA errors in Treiber stacks. Upon any wakeup,
+     * released threads also try to release at most two others.  The
+     * net effect is a tree-like diffusion of signals, where released
+     * threads (and possibly others) help with unparks.  To further
+     * reduce contention effects a bit, failed CASes to increment
+     * field eventCount are tolerated without retries in signalWork.
+     * Conceptually they are merged into the same event, which is OK
+     * when their only purpose is to enable workers to scan for work.
+     *
+     * 5. Managing suspension of extra workers. When a worker notices
+     * (usually upon timeout of a wait()) that there are too few
+     * running threads, we may create a new thread to maintain
+     * parallelism level, or at least avoid starvation. Usually, extra
+     * threads are needed for only very short periods, yet join
+     * dependencies are such that we sometimes need them in
+     * bursts. Rather than create new threads each time this happens,
+     * we suspend no-longer-needed extra ones as "spares". For most
+     * purposes, we don't distinguish "extra" spare threads from
+     * normal "core" threads: On each call to preStep (the only point
+     * at which we can do this) a worker checks to see if there are
+     * now too many running workers, and if so, suspends itself.
+     * Method helpMaintainParallelism looks for suspended threads to
+     * resume before considering creating a new replacement. The
+     * spares themselves are encoded on another variant of a Treiber
+     * Stack, headed at field "spareWaiters".  Note that the use of
+     * spares is intrinsically racy.  One thread may become a spare at
+     * about the same time as another is needlessly being created. We
+     * counteract this and related slop in part by requiring resumed
+     * spares to immediately recheck (in preStep) to see whether they
+     * should re-suspend.
+     *
+     * 6. Killing off unneeded workers. A timeout mechanism is used to
+     * shed unused workers: The oldest (first) event queue waiter uses
+     * a timed rather than hard wait. When this wait times out without
+     * a normal wakeup, it tries to shutdown any one (for convenience
+     * the newest) other spare or event waiter via
+     * tryShutdownUnusedWorker. This eventually reduces the number of
+     * worker threads to a minimum of one after a long enough period
+     * without use.
+     *
+     * 7. Deciding when to create new workers. The main dynamic
+     * control in this class is deciding when to create extra threads
+     * in method helpMaintainParallelism. We would like to keep
+     * exactly #parallelism threads running, which is an impossible
+     * task. We always need to create one when the number of running
+     * threads would become zero and all workers are busy. Beyond
+     * this, we must rely on heuristics that work well in the
+     * presence of transient phenomena such as GC stalls, dynamic
+     * compilation, and wake-up lags. These transients are extremely
+     * common -- we are normally trying to fully saturate the CPUs on
+     * a machine, so almost any activity other than running tasks
+     * impedes accuracy. Our main defense is to allow parallelism to
+     * lapse for a while during joins, and use a timeout to see if,
+     * after the resulting settling, there is still a need for
+     * additional workers.  This also better copes with the fact that
+     * some of the methods in this class tend to never become compiled
+     * (but are interpreted), so some components of the entire set of
+     * controls might execute 100 times faster than others. And
+     * similarly for cases where the apparent lack of work is just due
+     * to GC stalls and other transient system activity.
+     *
+     * Beware that there is a lot of representation-level coupling
+     * among classes ForkJoinPool, ForkJoinWorkerThread, and
+     * ForkJoinTask.  For example, direct access to "workers" array by
+     * workers, and direct access to ForkJoinTask.status by both
+     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
+     * trying to reduce this, since any associated future changes in
+     * representations will need to be accompanied by algorithmic
+     * changes anyway.
+     *
+     * Style notes: There are lots of inline assignments (of form
+     * "while ((local = field) != 0)") which are usually the simplest
+     * way to ensure the required read orderings (which are sometimes
+     * critical). Also several occurrences of the unusual "do {}
+     * while (!cas...)" which is the simplest way to force an update of
+     * a CAS'ed variable. There are also other coding oddities that
+     * help some methods perform reasonably even when interpreted (not
+     * compiled), at the expense of some messy constructions that
+     * reduce byte code counts.
+     *
+     * The order of declarations in this file is: (1) statics (2)
+     * fields (along with constants used when unpacking some of them)
+     * (3) internal control methods (4) callbacks and other support
+     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
+     * methods (plus a few little helpers).
      */
 
-    /** Mask for packing and unpacking shorts */
-    private static final int  shortMask = 0xffff;
-
-    /** Max pool size -- must be a power of two minus 1 */
-    private static final int MAX_THREADS =  0x7FFF;
-
     /**
      * Factory for creating new {@link ForkJoinWorkerThread}s.
      * A {@code ForkJoinWorkerThreadFactory} must be defined and used
@@ -151,14 +414,10 @@
      * Default ForkJoinWorkerThreadFactory implementation; creates a
      * new ForkJoinWorkerThread.
      */
-    static class  DefaultForkJoinWorkerThreadFactory
+    static class DefaultForkJoinWorkerThreadFactory
         implements ForkJoinWorkerThreadFactory {
         public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
-            try {
-                return new ForkJoinWorkerThread(pool);
-            } catch (OutOfMemoryError oom)  {
-                return null;
-            }
+            return new ForkJoinWorkerThread(pool);
         }
     }
 
@@ -194,47 +453,44 @@
         new AtomicInteger();
 
     /**
-     * Array holding all worker threads in the pool. Initialized upon
-     * first use. Array size must be a power of two.  Updates and
-     * replacements are protected by workerLock, but it is always kept
-     * in a consistent enough state to be randomly accessed without
-     * locking by workers performing work-stealing.
+     * The time to block in a join (see awaitJoin) before checking if
+     * a new worker should be (re)started to maintain parallelism
+     * level. The value should be short enough to maintain global
+     * responsiveness and progress but long enough to avoid
+     * counterproductive firings during GC stalls or unrelated system
+     * activity, and to not bog down systems with continual re-firings
+     * on GCs or legitimately long waits.
      */
-    volatile ForkJoinWorkerThread[] workers;
-
-    /**
-     * Lock protecting access to workers.
-     */
-    private final ReentrantLock workerLock;
-
-    /**
-     * Condition for awaitTermination.
-     */
-    private final Condition termination;
+    private static final long JOIN_TIMEOUT_MILLIS = 250L; // 4 per second
 
     /**
-     * The uncaught exception handler used when any worker
-     * abruptly terminates
+     * The wakeup interval (in nanoseconds) for the oldest worker
+     * waiting for an event to invoke tryShutdownUnusedWorker to
+     * shrink the number of workers.  The exact value does not matter
+     * too much. It must be short enough to release resources during
+     * sustained periods of idleness, but not so short that threads
+     * are continually re-created.
      */
-    private Thread.UncaughtExceptionHandler ueh;
-
-    /**
-     * Creation factory for worker threads.
-     */
-    private final ForkJoinWorkerThreadFactory factory;
+    private static final long SHRINK_RATE_NANOS =
+        30L * 1000L * 1000L * 1000L; // 2 per minute
 
     /**
-     * Head of stack of threads that were created to maintain
-     * parallelism when other threads blocked, but have since
-     * suspended when the parallelism level rose.
+     * Absolute bound for parallelism level. Twice this number plus
+     * one (i.e., 0xfff) must fit into a 16bit field to enable
+     * word-packing for some counts and indices.
      */
-    private volatile WaitQueueNode spareStack;
+    private static final int MAX_WORKERS   = 0x7fff;
 
     /**
-     * Sum of per-thread steal counts, updated only when threads are
-     * idle or terminating.
+     * Array holding all worker threads in the pool.  Array size must
+     * be a power of two.  Updates and replacements are protected by
+     * workerLock, but the array is always kept in a consistent enough
+     * state to be randomly accessed without locking by workers
+     * performing work-stealing, as well as other traversal-based
+     * methods in this class. All readers must tolerate that some
+     * array slots may be null.
      */
-    private final AtomicLong stealCount;
+    volatile ForkJoinWorkerThread[] workers;
 
     /**
      * Queue for external submissions.
@@ -242,160 +498,732 @@
     private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
 
     /**
-     * Head of Treiber stack for barrier sync. See below for explanation.
+     * Lock protecting updates to workers array.
+     */
+    private final ReentrantLock workerLock;
+
+    /**
+     * Latch released upon termination.
+     */
+    private final Phaser termination;
+
+    /**
+     * Creation factory for worker threads.
+     */
+    private final ForkJoinWorkerThreadFactory factory;
+
+    /**
+     * Sum of per-thread steal counts, updated only when threads are
+     * idle or terminating.
      */
-    private volatile WaitQueueNode syncStack;
+    private volatile long stealCount;
+
+    /**
+     * Encoded record of top of Treiber stack of threads waiting for
+     * events. The top 32 bits contain the count being waited for. The
+     * bottom 16 bits contains one plus the pool index of waiting
+     * worker thread. (Bits 16-31 are unused.)
+     */
+    private volatile long eventWaiters;
+
+    private static final int  EVENT_COUNT_SHIFT = 32;
+    private static final long WAITER_ID_MASK    = (1L << 16) - 1L;
+
+    /**
+     * A counter for events that may wake up worker threads:
+     *   - Submission of a new task to the pool
+     *   - A worker pushing a task on an empty queue
+     *   - termination
+     */
+    private volatile int eventCount;
+
+    /**
+     * Encoded record of top of Treiber stack of spare threads waiting
+     * for resumption. The top 16 bits contain an arbitrary count to
+     * avoid ABA effects. The bottom 16bits contains one plus the pool
+     * index of waiting worker thread.
+     */
+    private volatile int spareWaiters;
+
+    private static final int SPARE_COUNT_SHIFT = 16;
+    private static final int SPARE_ID_MASK     = (1 << 16) - 1;
 
     /**
-     * The count for event barrier
+     * Lifecycle control. The low word contains the number of workers
+     * that are (probably) executing tasks. This value is atomically
+     * incremented before a worker gets a task to run, and decremented
+     * when a worker has no tasks and cannot find any.  Bits 16-18
+     * contain runLevel value. When all are zero, the pool is
+     * running. Level transitions are monotonic (running -> shutdown
+     * -> terminating -> terminated) so each transition adds a bit.
+     * These are bundled together to ensure consistent read for
+     * termination checks (i.e., that runLevel is at least SHUTDOWN
+     * and active threads is zero).
+     *
+     * Notes: Most direct CASes are dependent on these bitfield
+     * positions.  Also, this field is non-private to enable direct
+     * performance-sensitive CASes in ForkJoinWorkerThread.
      */
-    private volatile long eventCount;
+    volatile int runState;
+
+    // Note: The order among run level values matters.
+    private static final int RUNLEVEL_SHIFT     = 16;
+    private static final int SHUTDOWN           = 1 << RUNLEVEL_SHIFT;
+    private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
+    private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
+    private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
+
+    /**
+     * Holds number of total (i.e., created and not yet terminated)
+     * and running (i.e., not blocked on joins or other managed sync)
+     * threads, packed together to ensure consistent snapshot when
+     * making decisions about creating and suspending spare
+     * threads. Updated only by CAS. Note that adding a new worker
+     * requires incrementing both counts, since workers start off in
+     * running state.
+     */
+    private volatile int workerCounts;
+
+    private static final int TOTAL_COUNT_SHIFT  = 16;
+    private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
+    private static final int ONE_RUNNING        = 1;
+    private static final int ONE_TOTAL          = 1 << TOTAL_COUNT_SHIFT;
+
+    /**
+     * The target parallelism level.
+     * Accessed directly by ForkJoinWorkerThreads.
+     */
+    final int parallelism;
+
+    /**
+     * True if use local fifo, not default lifo, for local polling
+     * Read by, and replicated by ForkJoinWorkerThreads
+     */
+    final boolean locallyFifo;
+
+    /**
+     * The uncaught exception handler used when any worker abruptly
+     * terminates.
+     */
+    private final Thread.UncaughtExceptionHandler ueh;
 
     /**
      * Pool number, just for assigning useful names to worker threads
      */
     private final int poolNumber;
 
-    /**
-     * The maximum allowed pool size
-     */
-    private volatile int maxPoolSize;
-
-    /**
-     * The desired parallelism level, updated only under workerLock.
-     */
-    private volatile int parallelism;
-
-    /**
-     * True if use local fifo, not default lifo, for local polling
-     */
-    private volatile boolean locallyFifo;
+    // Utilities for CASing fields. Note that most of these
+    // are usually manually inlined by callers
 
     /**
-     * Holds number of total (i.e., created and not yet terminated)
-     * and running (i.e., not blocked on joins or other managed sync)
-     * threads, packed into one int to ensure consistent snapshot when
-     * making decisions about creating and suspending spare
-     * threads. Updated only by CAS.  Note: CASes in
-     * updateRunningCount and preJoin assume that running active count
-     * is in low word, so need to be modified if this changes.
+     * Increments running count part of workerCounts
      */
-    private volatile int workerCounts;
-
-    private static int totalCountOf(int s)           { return s >>> 16;  }
-    private static int runningCountOf(int s)         { return s & shortMask; }
-    private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
-
-    /**
-     * Adds delta (which may be negative) to running count.  This must
-     * be called before (with negative arg) and after (with positive)
-     * any managed synchronization (i.e., mainly, joins).
-     *
-     * @param delta the number to add
-     */
-    final void updateRunningCount(int delta) {
-        int s;
-        do {} while (!casWorkerCounts(s = workerCounts, s + delta));
+    final void incrementRunningCount() {
+        int c;
+        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
+                                               c = workerCounts,
+                                               c + ONE_RUNNING));
     }
 
     /**
-     * Adds delta (which may be negative) to both total and running
-     * count.  This must be called upon creation and termination of
-     * worker threads.
-     *
-     * @param delta the number to add
+     * Tries to decrement running count unless already zero
      */
-    private void updateWorkerCount(int delta) {
-        int d = delta + (delta << 16); // add to both lo and hi parts
-        int s;
-        do {} while (!casWorkerCounts(s = workerCounts, s + d));
+    final boolean tryDecrementRunningCount() {
+        int wc = workerCounts;
+        if ((wc & RUNNING_COUNT_MASK) == 0)
+            return false;
+        return UNSAFE.compareAndSwapInt(this, workerCountsOffset,
+                                        wc, wc - ONE_RUNNING);
     }
 
     /**
-     * Lifecycle control. High word contains runState, low word
-     * contains the number of workers that are (probably) executing
-     * tasks. This value is atomically incremented before a worker
-     * gets a task to run, and decremented when worker has no tasks
-     * and cannot find any. These two fields are bundled together to
-     * support correct termination triggering.  Note: activeCount
-     * CAS'es cheat by assuming active count is in low word, so need
-     * to be modified if this changes
+     * Forces decrement of encoded workerCounts, awaiting nonzero if
+     * (rarely) necessary when other count updates lag.
+     *
+     * @param dr -- either zero or ONE_RUNNING
+     * @param dt -- either zero or ONE_TOTAL
      */
-    private volatile int runControl;
-
-    // RunState values. Order among values matters
-    private static final int RUNNING     = 0;
-    private static final int SHUTDOWN    = 1;
-    private static final int TERMINATING = 2;
-    private static final int TERMINATED  = 3;
-
-    private static int runStateOf(int c)             { return c >>> 16; }
-    private static int activeCountOf(int c)          { return c & shortMask; }
-    private static int runControlFor(int r, int a)   { return (r << 16) + a; }
-
-    /**
-     * Tries incrementing active count; fails on contention.
-     * Called by workers before/during executing tasks.
-     *
-     * @return true on success
-     */
-    final boolean tryIncrementActiveCount() {
-        int c = runControl;
-        return casRunControl(c, c+1);
+    private void decrementWorkerCounts(int dr, int dt) {
+        for (;;) {
+            int wc = workerCounts;
+            if ((wc & RUNNING_COUNT_MASK)  - dr < 0 ||
+                (wc >>> TOTAL_COUNT_SHIFT) - dt < 0) {
+                if ((runState & TERMINATED) != 0)
+                    return; // lagging termination on a backout
+                Thread.yield();
+            }
+            if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
+                                         wc, wc - (dr + dt)))
+                return;
+        }
     }
 
     /**
      * Tries decrementing active count; fails on contention.
-     * Possibly triggers termination on success.
-     * Called by workers when they can't find tasks.
-     *
-     * @return true on success
+     * Called when workers cannot find tasks to run.
      */
     final boolean tryDecrementActiveCount() {
-        int c = runControl;
-        int nextc = c - 1;
-        if (!casRunControl(c, nextc))
+        int c;
+        return UNSAFE.compareAndSwapInt(this, runStateOffset,
+                                        c = runState, c - 1);
+    }
+
+    /**
+     * Advances to at least the given level. Returns true if not
+     * already in at least the given level.
+     */
+    private boolean advanceRunLevel(int level) {
+        for (;;) {
+            int s = runState;
+            if ((s & level) != 0)
+                return false;
+            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
+                return true;
+        }
+    }
+
+    // workers array maintenance
+
+    /**
+     * Records and returns a workers array index for new worker.
+     */
+    private int recordWorker(ForkJoinWorkerThread w) {
+        // Try using slot totalCount-1. If not available, scan and/or resize
+        int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            ForkJoinWorkerThread[] ws = workers;
+            int n = ws.length;
+            if (k < 0 || k >= n || ws[k] != null) {
+                for (k = 0; k < n && ws[k] != null; ++k)
+                    ;
+                if (k == n)
+                    ws = Arrays.copyOf(ws, n << 1);
+            }
+            ws[k] = w;
+            workers = ws; // volatile array write ensures slot visibility
+        } finally {
+            lock.unlock();
+        }
+        return k;
+    }
+
+    /**
+     * Nulls out record of worker in workers array.
+     */
+    private void forgetWorker(ForkJoinWorkerThread w) {
+        int idx = w.poolIndex;
+        // Locking helps method recordWorker avoid unnecessary expansion
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            ForkJoinWorkerThread[] ws = workers;
+            if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
+                ws[idx] = null;
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Final callback from terminating worker.  Removes record of
+     * worker from array, and adjusts counts. If pool is shutting
+     * down, tries to complete termination.
+     *
+     * @param w the worker
+     */
+    final void workerTerminated(ForkJoinWorkerThread w) {
+        forgetWorker(w);
+        decrementWorkerCounts(w.isTrimmed()? 0 : ONE_RUNNING, ONE_TOTAL);
+        while (w.stealCount != 0) // collect final count
+            tryAccumulateStealCount(w);
+        tryTerminate(false);
+    }
+
+    // Waiting for and signalling events
+
+    /**
+     * Releases workers blocked on a count not equal to current count.
+     * Normally called after precheck that eventWaiters isn't zero to
+     * avoid wasted array checks. Gives up upon a change in count or
+     * upon releasing two workers, letting others take over.
+     */
+    private void releaseEventWaiters() {
+        ForkJoinWorkerThread[] ws = workers;
+        int n = ws.length;
+        long h = eventWaiters;
+        int ec = eventCount;
+        boolean releasedOne = false;
+        ForkJoinWorkerThread w; int id;
+        while ((id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
+               (int)(h >>> EVENT_COUNT_SHIFT) != ec &&
+               id < n && (w = ws[id]) != null) {
+            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
+                                          h,  w.nextWaiter)) {
+                LockSupport.unpark(w);
+                if (releasedOne) // exit on second release
+                    break;
+                releasedOne = true;
+            }
+            if (eventCount != ec)
+                break;
+            h = eventWaiters;
+        }
+    }
+
+    /**
+     * Tries to advance eventCount and releases waiters. Called only
+     * from workers.
+     */
+    final void signalWork() {
+        int c; // try to increment event count -- CAS failure OK
+        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
+        if (eventWaiters != 0L)
+            releaseEventWaiters();
+    }
+
+    /**
+     * Adds the given worker to event queue and blocks until
+     * terminating or event count advances from the given value
+     *
+     * @param w the calling worker thread
+     * @param ec the count
+     */
+    private void eventSync(ForkJoinWorkerThread w, int ec) {
+        long nh = (((long)ec) << EVENT_COUNT_SHIFT) | ((long)(w.poolIndex+1));
+        long h;
+        while ((runState < SHUTDOWN || !tryTerminate(false)) &&
+               (((int)((h = eventWaiters) & WAITER_ID_MASK)) == 0 ||
+                (int)(h >>> EVENT_COUNT_SHIFT) == ec) &&
+               eventCount == ec) {
+            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
+                                          w.nextWaiter = h, nh)) {
+                awaitEvent(w, ec);
+                break;
+            }
+        }
+    }
+
+    /**
+     * Blocks the given worker (that has already been entered as an
+     * event waiter) until terminating or event count advances from
+     * the given value. The oldest (first) waiter uses a timed wait to
+     * occasionally one-by-one shrink the number of workers (to a
+     * minimum of one) if the pool has not been used for extended
+     * periods.
+     *
+     * @param w the calling worker thread
+     * @param ec the count
+     */
+    private void awaitEvent(ForkJoinWorkerThread w, int ec) {
+        while (eventCount == ec) {
+            if (tryAccumulateStealCount(w)) { // transfer while idle
+                boolean untimed = (w.nextWaiter != 0L ||
+                                   (workerCounts & RUNNING_COUNT_MASK) <= 1);
+                long startTime = untimed? 0 : System.nanoTime();
+                Thread.interrupted();         // clear/ignore interrupt
+                if (eventCount != ec || w.runState != 0 ||
+                    runState >= TERMINATING)  // recheck after clear
+                    break;
+                if (untimed)
+                    LockSupport.park(w);
+                else {
+                    LockSupport.parkNanos(w, SHRINK_RATE_NANOS);
+                    if (eventCount != ec || w.runState != 0 ||
+                        runState >= TERMINATING)
+                        break;
+                    if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
+                        tryShutdownUnusedWorker(ec);
+                }
+            }
+        }
+    }
+
+    // Maintaining parallelism
+
+    /**
+     * Pushes worker onto the spare stack.
+     */
+    final void pushSpare(ForkJoinWorkerThread w) {
+        int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
+        do {} while (!UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
+                                               w.nextSpare = spareWaiters,ns));
+    }
+
+    /**
+     * Tries (once) to resume a spare if the number of running
+     * threads is less than target.
+     */
+    private void tryResumeSpare() {
+        int sw, id;
+        ForkJoinWorkerThread[] ws = workers;
+        int n = ws.length;
+        ForkJoinWorkerThread w;
+        if ((sw = spareWaiters) != 0 &&
+            (id = (sw & SPARE_ID_MASK) - 1) >= 0 &&
+            id < n && (w = ws[id]) != null &&
+            (workerCounts & RUNNING_COUNT_MASK) < parallelism &&
+            spareWaiters == sw &&
+            UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
+                                     sw, w.nextSpare)) {
+            int c; // increment running count before resume
+            do {} while (!UNSAFE.compareAndSwapInt
+                         (this, workerCountsOffset,
+                          c = workerCounts, c + ONE_RUNNING));
+            if (w.tryUnsuspend())
+                LockSupport.unpark(w);
+            else   // back out if w was shutdown
+                decrementWorkerCounts(ONE_RUNNING, 0);
+        }
+    }
+
+    /**
+     * Tries to increase the number of running workers if below target
+     * parallelism: If a spare exists tries to resume it via
+     * tryResumeSpare.  Otherwise, if not enough total workers or all
+     * existing workers are busy, adds a new worker. In all cases also
+     * helps wake up releasable workers waiting for work.
+     */
+    private void helpMaintainParallelism() {
+        int pc = parallelism;
+        int wc, rs, tc;
+        while (((wc = workerCounts) & RUNNING_COUNT_MASK) < pc &&
+               (rs = runState) < TERMINATING) {
+            if (spareWaiters != 0)
+                tryResumeSpare();
+            else if ((tc = wc >>> TOTAL_COUNT_SHIFT) >= MAX_WORKERS ||
+                     (tc >= pc && (rs & ACTIVE_COUNT_MASK) != tc))
+                break;   // enough total
+            else if (runState == rs && workerCounts == wc &&
+                     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
+                                              wc + (ONE_RUNNING|ONE_TOTAL))) {
+                ForkJoinWorkerThread w = null;
+                try {
+                    w = factory.newThread(this);
+                } finally { // adjust on null or exceptional factory return
+                    if (w == null) {
+                        decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
+                        tryTerminate(false); // handle failure during shutdown
+                    }
+                }
+                if (w == null)
+                    break;
+                w.start(recordWorker(w), ueh);
+                if ((workerCounts >>> TOTAL_COUNT_SHIFT) >= pc) {
+                    int c; // advance event count
+                    UNSAFE.compareAndSwapInt(this, eventCountOffset,
+                                             c = eventCount, c+1);
+                    break; // add at most one unless total below target
+                }
+            }
+        }
+        if (eventWaiters != 0L)
+            releaseEventWaiters();
+    }
+
+    /**
+     * Callback from the oldest waiter in awaitEvent waking up after a
+     * period of non-use. If all workers are idle, tries (once) to
+     * shutdown an event waiter or a spare, if one exists. Note that
+     * we don't need CAS or locks here because the method is called
+     * only from one thread occasionally waking (and even misfires are
+     * OK). Note that until the shutdown worker fully terminates,
+     * workerCounts will overestimate total count, which is tolerable.
+     *
+     * @param ec the event count waited on by caller (to abort
+     * attempt if count has since changed).
+     */
+    private void tryShutdownUnusedWorker(int ec) {
+        if (runState == 0 && eventCount == ec) { // only trigger if all idle
+            ForkJoinWorkerThread[] ws = workers;
+            int n = ws.length;
+            ForkJoinWorkerThread w = null;
+            boolean shutdown = false;
+            int sw;
+            long h;
+            if ((sw = spareWaiters) != 0) { // prefer killing spares
+                int id = (sw & SPARE_ID_MASK) - 1;
+                if (id >= 0 && id < n && (w = ws[id]) != null &&
+                    UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
+                                             sw, w.nextSpare))
+                    shutdown = true;
+            }
+            else if ((h = eventWaiters) != 0L) {
+                long nh;
+                int id = ((int)(h & WAITER_ID_MASK)) - 1;
+                if (id >= 0 && id < n && (w = ws[id]) != null &&
+                    (nh = w.nextWaiter) != 0L && // keep at least one worker
+                    UNSAFE.compareAndSwapLong(this, eventWaitersOffset, h, nh))
+                    shutdown = true;
+            }
+            if (w != null && shutdown) {
+                w.shutdown();
+                LockSupport.unpark(w);
+            }
+        }
+        releaseEventWaiters(); // in case of interference
+    }
+
+    /**
+     * Callback from workers invoked upon each top-level action (i.e.,
+     * stealing a task or taking a submission and running it).
+     * Performs one or more of the following:
+     *
+     * 1. If the worker is active and either did not run a task
+     *    or there are too many workers, try to set its active status
+     *    to inactive and update activeCount. On contention, we may
+     *    try again in this or a subsequent call.
+     *
+     * 2. If not enough total workers, help create some.
+     *
+     * 3. If there are too many running workers, suspend this worker
+     *    (first forcing inactive if necessary).  If it is not needed,
+     *    it may be shutdown while suspended (via
+     *    tryShutdownUnusedWorker).  Otherwise, upon resume it
+     *    rechecks running thread count and need for event sync.
+     *
+     * 4. If worker did not run a task, await the next task event via
+     *    eventSync if necessary (first forcing inactivation), upon
+     *    which the worker may be shutdown via
+     *    tryShutdownUnusedWorker.  Otherwise, help release any
+     *    existing event waiters that are now releasable,
+     *
+     * @param w the worker
+     * @param ran true if worker ran a task since last call to this method
+     */
+    final void preStep(ForkJoinWorkerThread w, boolean ran) {
+        int wec = w.lastEventCount;
+        boolean active = w.active;
+        boolean inactivate = false;
+        int pc = parallelism;
+        int rs;
+        while (w.runState == 0 && (rs = runState) < TERMINATING) {
+            if ((inactivate || (active && (rs & ACTIVE_COUNT_MASK) >= pc)) &&
+                UNSAFE.compareAndSwapInt(this, runStateOffset, rs, rs - 1))
+                inactivate = active = w.active = false;
+            int wc = workerCounts;
+            if ((wc & RUNNING_COUNT_MASK) > pc) {
+                if (!(inactivate |= active) && // must inactivate to suspend
+                    workerCounts == wc &&      // try to suspend as spare
+                    UNSAFE.compareAndSwapInt(this, workerCountsOffset,
+                                             wc, wc - ONE_RUNNING))
+                    w.suspendAsSpare();
+            }
+            else if ((wc >>> TOTAL_COUNT_SHIFT) < pc)
+                helpMaintainParallelism();     // not enough workers
+            else if (!ran) {
+                long h = eventWaiters;
+                int ec = eventCount;
+                if (h != 0L && (int)(h >>> EVENT_COUNT_SHIFT) != ec)
+                    releaseEventWaiters();     // release others before waiting
+                else if (ec != wec) {
+                    w.lastEventCount = ec;     // no need to wait
+                    break;
+                }
+                else if (!(inactivate |= active))
+                    eventSync(w, wec);         // must inactivate before sync
+            }
+            else
+                break;
+        }
+    }
+
+    /**
+     * Helps and/or blocks awaiting join of the given task.
+     * See above for explanation.
+     *
+     * @param joinMe the task to join
+     * @param worker the current worker thread
+     */
+    final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker) {
+        int retries = 2 + (parallelism >> 2); // #helpJoins before blocking
+        while (joinMe.status >= 0) {
+            int wc;
+            worker.helpJoinTask(joinMe);
+            if (joinMe.status < 0)
+                break;
+            else if (retries > 0)
+                --retries;
+            else if (((wc = workerCounts) & RUNNING_COUNT_MASK) != 0 &&
+                     UNSAFE.compareAndSwapInt(this, workerCountsOffset,
+                                              wc, wc - ONE_RUNNING)) {
+                int stat, c; long h;
+                while ((stat = joinMe.status) >= 0 &&
+                       (h = eventWaiters) != 0L && // help release others
+                       (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
+                    releaseEventWaiters();
+                if (stat >= 0 &&
+                    ((workerCounts & RUNNING_COUNT_MASK) == 0 ||
+                     (stat =
+                      joinMe.internalAwaitDone(JOIN_TIMEOUT_MILLIS)) >= 0))
+                    helpMaintainParallelism(); // timeout or no running workers
+                do {} while (!UNSAFE.compareAndSwapInt
+                             (this, workerCountsOffset,
+                              c = workerCounts, c + ONE_RUNNING));
+                if (stat < 0)
+                    break;   // else restart
+            }
+        }
+    }
+
+    /**
+     * Same idea as awaitJoin, but no helping, retries, or timeouts.
+     */
+    final void awaitBlocker(ManagedBlocker blocker)
+        throws InterruptedException {
+        while (!blocker.isReleasable()) {
+            int wc = workerCounts;
+            if ((wc & RUNNING_COUNT_MASK) != 0 &&
+                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
+                                         wc, wc - ONE_RUNNING)) {
+                try {
+                    while (!blocker.isReleasable()) {
+                        long h = eventWaiters;
+                        if (h != 0L &&
+                            (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
+                            releaseEventWaiters();
+                        else if ((workerCounts & RUNNING_COUNT_MASK) == 0 &&
+                                 runState < TERMINATING)
+                            helpMaintainParallelism();
+                        else if (blocker.block())
+                            break;
+                    }
+                } finally {
+                    int c;
+                    do {} while (!UNSAFE.compareAndSwapInt
+                                 (this, workerCountsOffset,
+                                  c = workerCounts, c + ONE_RUNNING));
+                }
+                break;
+            }
+        }
+    }
+
+    /**
+     * Possibly initiates and/or completes termination.
+     *
+     * @param now if true, unconditionally terminate, else only
+     * if shutdown and empty queue and no active workers
+     * @return true if now terminating or terminated
+     */
+    private boolean tryTerminate(boolean now) {
+        if (now)
+            advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
+        else if (runState < SHUTDOWN ||
+                 !submissionQueue.isEmpty() ||
+                 (runState & ACTIVE_COUNT_MASK) != 0)
             return false;
-        if (canTerminateOnShutdown(nextc))
-            terminateOnShutdown();
+
+        if (advanceRunLevel(TERMINATING))
+            startTerminating();
+
+        // Finish now if all threads terminated; else in some subsequent call
+        if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
+            advanceRunLevel(TERMINATED);
+            termination.arrive();
+        }
         return true;
     }
 
     /**
-     * Returns {@code true} if argument represents zero active count
-     * and nonzero runstate, which is the triggering condition for
-     * terminating on shutdown.
+     * Actions on transition to TERMINATING
+     *
+     * Runs up to four passes through workers: (0) shutting down each
+     * (without waking up if parked) to quickly spread notifications
+     * without unnecessary bouncing around event queues etc (1) wake
+     * up and help cancel tasks (2) interrupt (3) mop up races with
+     * interrupted workers
      */
-    private static boolean canTerminateOnShutdown(int c) {
-        // i.e. least bit is nonzero runState bit
-        return ((c & -c) >>> 16) != 0;
-    }
-
-    /**
-     * Transition run state to at least the given state. Return true
-     * if not already at least given state.
-     */
-    private boolean transitionRunStateTo(int state) {
-        for (;;) {
-            int c = runControl;
-            if (runStateOf(c) >= state)
-                return false;
-            if (casRunControl(c, runControlFor(state, activeCountOf(c))))
-                return true;
+    private void startTerminating() {
+        cancelSubmissions();
+        for (int passes = 0; passes < 4 && workerCounts != 0; ++passes) {
+            int c; // advance event count
+            UNSAFE.compareAndSwapInt(this, eventCountOffset,
+                                     c = eventCount, c+1);
+            eventWaiters = 0L; // clobber lists
+            spareWaiters = 0;
+            for (ForkJoinWorkerThread w : workers) {
+                if (w != null) {
+                    w.shutdown();
+                    if (passes > 0 && !w.isTerminated()) {
+                        w.cancelTasks();
+                        LockSupport.unpark(w);
+                        if (passes > 1) {
+                            try {
+                                w.interrupt();
+                            } catch (SecurityException ignore) {
+                            }
+                        }
+                    }
+                }
+            }
         }
     }
 
     /**
-     * Controls whether to add spares to maintain parallelism
+     * Clears out and cancels submissions, ignoring exceptions.
+     */
+    private void cancelSubmissions() {
+        ForkJoinTask<?> task;
+        while ((task = submissionQueue.poll()) != null) {
+            try {
+                task.cancel(false);
+            } catch (Throwable ignore) {
+            }
+        }
+    }
+
+    // misc support for ForkJoinWorkerThread
+
+    /**
+     * Returns pool number.
+     */
+    final int getPoolNumber() {
+        return poolNumber;
+    }
+
+    /**
+     * Tries to accumulate steal count from a worker, clearing
+     * the worker's value if successful.
+     *
+     * @return true if worker steal count now zero
      */
-    private volatile boolean maintainsParallelism;
+    final boolean tryAccumulateStealCount(ForkJoinWorkerThread w) {
+        int sc = w.stealCount;
+        long c = stealCount;
+        // CAS even if zero, for fence effects
+        if (UNSAFE.compareAndSwapLong(this, stealCountOffset, c, c + sc)) {
+            if (sc != 0)
+                w.stealCount = 0;
+            return true;
+        }
+        return sc == 0;
+    }
+
+    /**
+     * Returns the approximate (non-atomic) number of idle threads per
+     * active thread.
+     */
+    final int idlePerActive() {
+        int pc = parallelism; // use parallelism, not rc
+        int ac = runState;    // no mask -- artificially boosts during shutdown
+        // Use exact results for small values, saturate past 4
+        return ((pc <= ac) ? 0 :
+                (pc >>> 1 <= ac) ? 1 :
+                (pc >>> 2 <= ac) ? 3 :
+                pc >>> 3);
+    }
+
+    // Public and protected methods
 
     // Constructors
 
     /**
      * Creates a {@code ForkJoinPool} with parallelism equal to {@link
-     * java.lang.Runtime#availableProcessors}, and using the {@linkplain
-     * #defaultForkJoinWorkerThreadFactory default thread factory}.
+     * java.lang.Runtime#availableProcessors}, using the {@linkplain
+     * #defaultForkJoinWorkerThreadFactory default thread factory},
+     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
      *
      * @throws SecurityException if a security manager exists and
      *         the caller is not permitted to modify threads
@@ -404,13 +1232,14 @@
      */
     public ForkJoinPool() {
         this(Runtime.getRuntime().availableProcessors(),
-             defaultForkJoinWorkerThreadFactory);
+             defaultForkJoinWorkerThreadFactory, null, false);
     }
 
     /**
      * Creates a {@code ForkJoinPool} with the indicated parallelism
-     * level and using the {@linkplain
-     * #defaultForkJoinWorkerThreadFactory default thread factory}.
+     * level, the {@linkplain
+     * #defaultForkJoinWorkerThreadFactory default thread factory},
+     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
      *
      * @param parallelism the parallelism level
      * @throws IllegalArgumentException if parallelism less than or
@@ -421,31 +1250,25 @@
      *         java.lang.RuntimePermission}{@code ("modifyThread")}
      */
     public ForkJoinPool(int parallelism) {
-        this(parallelism, defaultForkJoinWorkerThreadFactory);
+        this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
     }
 
     /**
-     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
-     * java.lang.Runtime#availableProcessors}, and using the given
-     * thread factory.
+     * Creates a {@code ForkJoinPool} with the given parameters.
      *
-     * @param factory the factory for creating new threads
-     * @throws NullPointerException if the factory is null
-     * @throws SecurityException if a security manager exists and
-     *         the caller is not permitted to modify threads
-     *         because it does not hold {@link
-     *         java.lang.RuntimePermission}{@code ("modifyThread")}
-     */
-    public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
-        this(Runtime.getRuntime().availableProcessors(), factory);
-    }
-
-    /**
-     * Creates a {@code ForkJoinPool} with the given parallelism and
-     * thread factory.
-     *
-     * @param parallelism the parallelism level
-     * @param factory the factory for creating new threads
+     * @param parallelism the parallelism level. For default value,
+     * use {@link java.lang.Runtime#availableProcessors}.
+     * @param factory the factory for creating new threads. For default value,
+     * use {@link #defaultForkJoinWorkerThreadFactory}.
+     * @param handler the handler for internal worker threads that
+     * terminate due to unrecoverable errors encountered while executing
+     * tasks. For default value, use {@code null}.
+     * @param asyncMode if true,
+     * establishes local first-in-first-out scheduling mode for forked
+     * tasks that are never joined. This mode may be more appropriate
+     * than default locally stack-based mode in applications in which
+     * worker threads only process event-style asynchronous tasks.
+     * For default value, use {@code false}.
      * @throws IllegalArgumentException if parallelism less than or
      *         equal to zero, or greater than implementation limit
      * @throws NullPointerException if the factory is null
@@ -454,153 +1277,40 @@
      *         because it does not hold {@link
      *         java.lang.RuntimePermission}{@code ("modifyThread")}
      */
-    public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
-        if (parallelism <= 0 || parallelism > MAX_THREADS)
-            throw new IllegalArgumentException();
+    public ForkJoinPool(int parallelism,
+                        ForkJoinWorkerThreadFactory factory,
+                        Thread.UncaughtExceptionHandler handler,
+                        boolean asyncMode) {
+        checkPermission();
         if (factory == null)
             throw new NullPointerException();
-        checkPermission();
-        this.factory = factory;
+        if (parallelism <= 0 || parallelism > MAX_WORKERS)
+            throw new IllegalArgumentException();
         this.parallelism = parallelism;
-        this.maxPoolSize = MAX_THREADS;
-        this.maintainsParallelism = true;
-        this.poolNumber = poolNumberGenerator.incrementAndGet();
-        this.workerLock = new ReentrantLock();
-        this.termination = workerLock.newCondition();
-        this.stealCount = new AtomicLong();
+        this.factory = factory;
+        this.ueh = handler;
+        this.locallyFifo = asyncMode;
+        int arraySize = initialArraySizeFor(parallelism);
+        this.workers = new ForkJoinWorkerThread[arraySize];
         this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
-        // worker array and workers are lazily constructed
-    }
-
-    /**
-     * Creates a new worker thread using factory.
-     *
-     * @param index the index to assign worker
-     * @return new worker, or null if factory failed
-     */
-    private ForkJoinWorkerThread createWorker(int index) {
-        Thread.UncaughtExceptionHandler h = ueh;
-        ForkJoinWorkerThread w = factory.newThread(this);
-        if (w != null) {
-            w.poolIndex = index;
-            w.setDaemon(true);
-            w.setAsyncMode(locallyFifo);
-            w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
-            if (h != null)
-                w.setUncaughtExceptionHandler(h);
-        }
-        return w;
-    }
-
-    /**
-     * Returns a good size for worker array given pool size.
-     * Currently requires size to be a power of two.
-     */
-    private static int arraySizeFor(int poolSize) {
-        if (poolSize <= 1)
-            return 1;
-        // See Hackers Delight, sec 3.2
-        int c = poolSize >= MAX_THREADS ? MAX_THREADS : (poolSize - 1);
-        c |= c >>>  1;
-        c |= c >>>  2;
-        c |= c >>>  4;
-        c |= c >>>  8;
-        c |= c >>> 16;
-        return c + 1;
-    }
-
-    /**
-     * Creates or resizes array if necessary to hold newLength.
-     * Call only under exclusion.
-     *
-     * @return the array
-     */
-    private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
-        ForkJoinWorkerThread[] ws = workers;
-        if (ws == null)
-            return workers = new ForkJoinWorkerThread[arraySizeFor(newLength)];
-        else if (newLength > ws.length)
-            return workers = Arrays.copyOf(ws, arraySizeFor(newLength));
-        else
-            return ws;
+        this.workerLock = new ReentrantLock();
+        this.termination = new Phaser(1);
+        this.poolNumber = poolNumberGenerator.incrementAndGet();
     }
 
     /**
-     * Tries to shrink workers into smaller array after one or more terminate.
-     */
-    private void tryShrinkWorkerArray() {
-        ForkJoinWorkerThread[] ws = workers;
-        if (ws != null) {
-            int len = ws.length;
-            int last = len - 1;
-            while (last >= 0 && ws[last] == null)
-                --last;
-            int newLength = arraySizeFor(last+1);
-            if (newLength < len)
-                workers = Arrays.copyOf(ws, newLength);
-        }
-    }
-
-    /**
-     * Initializes workers if necessary.
+     * Returns initial power of two size for workers array.
+     * @param pc the initial parallelism level
      */
-    final void ensureWorkerInitialization() {
-        ForkJoinWorkerThread[] ws = workers;
-        if (ws == null) {
-            final ReentrantLock lock = this.workerLock;
-            lock.lock();
-            try {
-                ws = workers;
-                if (ws == null) {
-                    int ps = parallelism;
-                    ws = ensureWorkerArrayCapacity(ps);
-                    for (int i = 0; i < ps; ++i) {
-                        ForkJoinWorkerThread w = createWorker(i);
-                        if (w != null) {
-                            ws[i] = w;
-                            w.start();
-                            updateWorkerCount(1);
-                        }
-                    }
-                }
-            } finally {
-                lock.unlock();
-            }
-        }
-    }
-
-    /**
-     * Worker creation and startup for threads added via setParallelism.
-     */
-    private void createAndStartAddedWorkers() {
-        resumeAllSpares();  // Allow spares to convert to nonspare
-        int ps = parallelism;
-        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
-        int len = ws.length;
-        // Sweep through slots, to keep lowest indices most populated
-        int k = 0;
-        while (k < len) {
-            if (ws[k] != null) {
-                ++k;
-                continue;
-            }
-            int s = workerCounts;
-            int tc = totalCountOf(s);
-            int rc = runningCountOf(s);
-            if (rc >= ps || tc >= ps)
-                break;
-            if (casWorkerCounts (s, workerCountsFor(tc+1, rc+1))) {
-                ForkJoinWorkerThread w = createWorker(k);
-                if (w != null) {
-                    ws[k++] = w;
-                    w.start();
-                }
-                else {
-                    updateWorkerCount(-1); // back out on failed creation
-                    break;
-                }
-            }
-        }
+    private static int initialArraySizeFor(int pc) {
+        // If possible, initially allocate enough space for one spare
+        int size = pc < MAX_WORKERS ? pc + 1 : MAX_WORKERS;
+        // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
+        size |= size >>> 1;
+        size |= size >>> 2;
+        size |= size >>> 4;
+        size |= size >>> 8;
+        return size + 1;
     }
 
     // Execution methods
@@ -611,12 +1321,12 @@
     private <T> void doSubmit(ForkJoinTask<T> task) {
         if (task == null)
             throw new NullPointerException();
-        if (isShutdown())
+        if (runState >= SHUTDOWN)
             throw new RejectedExecutionException();
-        if (workers == null)
-            ensureWorkerInitialization();
         submissionQueue.offer(task);
-        signalIdleWorkers();
+        int c; // try to increment event count -- CAS failure OK
+        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
+        helpMaintainParallelism(); // create, start, or resume some workers
     }
 
     /**
@@ -662,6 +1372,20 @@
     }
 
     /**
+     * Submits a ForkJoinTask for execution.
+     *
+     * @param task the task to submit
+     * @return the task
+     * @throws NullPointerException if the task is null
+     * @throws RejectedExecutionException if the task cannot be
+     *         scheduled for execution
+     */
+    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
+        doSubmit(task);
+        return task;
+    }
+
+    /**
      * @throws NullPointerException if the task is null
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
@@ -699,21 +1423,6 @@
     }
 
     /**
-     * Submits a ForkJoinTask for execution.
-     *
-     * @param task the task to submit
-     * @return the task
-     * @throws NullPointerException if the task is null
-     * @throws RejectedExecutionException if the task cannot be
-     *         scheduled for execution
-     */
-    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
-        doSubmit(task);
-        return task;
-    }
-
-
-    /**
      * @throws NullPointerException       {@inheritDoc}
      * @throws RejectedExecutionException {@inheritDoc}
      */
@@ -725,7 +1434,7 @@
         invoke(new InvokeAll<T>(forkJoinTasks));
 
         @SuppressWarnings({"unchecked", "rawtypes"})
-        List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
+            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
         return futures;
     }
 
@@ -739,8 +1448,6 @@
         private static final long serialVersionUID = -7914297376763021607L;
     }
 
-    // Configuration and status settings and queries
-
     /**
      * Returns the factory used for constructing new workers.
      *
@@ -757,84 +1464,7 @@
      * @return the handler, or {@code null} if none
      */
     public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
-        Thread.UncaughtExceptionHandler h;
-        final ReentrantLock lock = this.workerLock;
-        lock.lock();
-        try {
-            h = ueh;
-        } finally {
-            lock.unlock();
-        }
-        return h;
-    }
-
-    /**
-     * Sets the handler for internal worker threads that terminate due
-     * to unrecoverable errors encountered while executing tasks.
-     * Unless set, the current default or ThreadGroup handler is used
-     * as handler.
-     *
-     * @param h the new handler
-     * @return the old handler, or {@code null} if none
-     * @throws SecurityException if a security manager exists and
-     *         the caller is not permitted to modify threads
-     *         because it does not hold {@link
-     *         java.lang.RuntimePermission}{@code ("modifyThread")}
-     */
-    public Thread.UncaughtExceptionHandler
-        setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
-        checkPermission();
-        Thread.UncaughtExceptionHandler old = null;
-        final ReentrantLock lock = this.workerLock;
-        lock.lock();
-        try {
-            old = ueh;
-            ueh = h;
-            ForkJoinWorkerThread[] ws = workers;
-            if (ws != null) {
-                for (int i = 0; i < ws.length; ++i) {
-                    ForkJoinWorkerThread w = ws[i];
-                    if (w != null)
-                        w.setUncaughtExceptionHandler(h);
-                }
-            }
-        } finally {
-            lock.unlock();
-        }
-        return old;
-    }
-
-
-    /**
-     * Sets the target parallelism level of this pool.
-     *
-     * @param parallelism the target parallelism
-     * @throws IllegalArgumentException if parallelism less than or
-     * equal to zero or greater than maximum size bounds
-     * @throws SecurityException if a security manager exists and
-     *         the caller is not permitted to modify threads
-     *         because it does not hold {@link
-     *         java.lang.RuntimePermission}{@code ("modifyThread")}
-     */
-    public void setParallelism(int parallelism) {
-        checkPermission();
-        if (parallelism <= 0 || parallelism > maxPoolSize)
-            throw new IllegalArgumentException();
-        final ReentrantLock lock = this.workerLock;
-        lock.lock();
-        try {
-            if (isProcessingTasks()) {
-                int p = this.parallelism;
-                this.parallelism = parallelism;
-                if (parallelism > p)
-                    createAndStartAddedWorkers();
-                else
-                    trimSpares();
-            }
-        } finally {
-            lock.unlock();
-        }
-        signalIdleWorkers();
+        return ueh;
     }
 
     /**
@@ -848,92 +1478,14 @@
 
     /**
      * Returns the number of worker threads that have started but not
-     * yet terminated.  This result returned by this method may differ
+     * yet terminated.  The result returned by this method may differ
      * from {@link #getParallelism} when threads are created to
      * maintain parallelism when others are cooperatively blocked.
      *
      * @return the number of worker threads
      */
     public int getPoolSize() {
-        return totalCountOf(workerCounts);
-    }
-
-    /**
-     * Returns the maximum number of threads allowed to exist in the
-     * pool. Unless set using {@link #setMaximumPoolSize}, the
-     * maximum is an implementation-defined value designed only to
-     * prevent runaway growth.
-     *
-     * @return the maximum
-     */
-    public int getMaximumPoolSize() {
-        return maxPoolSize;
-    }
-
-    /**
-     * Sets the maximum number of threads allowed to exist in the
-     * pool. The given value should normally be greater than or equal
-     * to the {@link #getParallelism parallelism} level. Setting this
-     * value has no effect on current pool size. It controls
-     * construction of new threads.
-     *
-     * @throws IllegalArgumentException if negative or greater than
-     * internal implementation limit
-     */
-    public void setMaximumPoolSize(int newMax) {
-        if (newMax < 0 || newMax > MAX_THREADS)
-            throw new IllegalArgumentException();
-        maxPoolSize = newMax;
-    }
-
-
-    /**
-     * Returns {@code true} if this pool dynamically maintains its
-     * target parallelism level. If false, new threads are added only
-     * to avoid possible starvation.  This setting is by default true.
-     *
-     * @return {@code true} if maintains parallelism
-     */
-    public boolean getMaintainsParallelism() {
-        return maintainsParallelism;
-    }
-
-    /**
-     * Sets whether this pool dynamically maintains its target
-     * parallelism level. If false, new threads are added only to
-     * avoid possible starvation.
-     *
-     * @param enable {@code true} to maintain parallelism
-     */
-    public void setMaintainsParallelism(boolean enable) {
-        maintainsParallelism = enable;
-    }
-
-    /**
-     * Establishes local first-in-first-out scheduling mode for forked
-     * tasks that are never joined. This mode may be more appropriate
-     * than default locally stack-based mode in applications in which
-     * worker threads only process asynchronous tasks.  This method is
-     * designed to be invoked only when the pool is quiescent, and
-     * typically only before any tasks are submitted. The effects of
-     * invocations at other times may be unpredictable.
-     *
-     * @param async if {@code true}, use locally FIFO scheduling
-     * @return the previous mode
-     * @see #getAsyncMode
-     */
-    public boolean setAsyncMode(boolean async) {
-        boolean oldMode = locallyFifo;
-        locallyFifo = async;
-        ForkJoinWorkerThread[] ws = workers;
-        if (ws != null) {
-            for (int i = 0; i < ws.length; ++i) {
-                ForkJoinWorkerThread t = ws[i];
-                if (t != null)
-                    t.setAsyncMode(async);
-            }
-        }
-        return oldMode;
+        return workerCounts >>> TOTAL_COUNT_SHIFT;
     }
 
     /**
@@ -941,7 +1493,6 @@
      * scheduling mode for forked tasks that are never joined.
      *
      * @return {@code true} if this pool uses async mode
-     * @see #setAsyncMode
      */
     public boolean getAsyncMode() {
         return locallyFifo;
@@ -950,12 +1501,13 @@
     /**
      * Returns an estimate of the number of worker threads that are
      * not blocked waiting to join tasks or for other managed
-     * synchronization.
+     * synchronization. This method may overestimate the
+     * number of running threads.
      *
      * @return the number of worker threads
      */
     public int getRunningThreadCount() {
-        return runningCountOf(workerCounts);
+        return workerCounts & RUNNING_COUNT_MASK;
     }
 
     /**
@@ -966,19 +1518,7 @@
      * @return the number of active threads
      */
     public int getActiveThreadCount() {
-        return activeCountOf(runControl);
-    }
-
-    /**
-     * Returns an estimate of the number of threads that are currently
-     * idle waiting for tasks. This method may underestimate the
-     * number of idle threads.
-     *
-     * @return the number of idle threads
-     */
-    final int getIdleThreadCount() {
-        int c = runningCountOf(workerCounts) - activeCountOf(runControl);
-        return (c <= 0) ? 0 : c;
+        return runState & ACTIVE_COUNT_MASK;
     }
 
     /**
@@ -993,7 +1533,7 @@
      * @return {@code true} if all threads are currently idle
      */
     public boolean isQuiescent() {
-        return activeCountOf(runControl) == 0;
+        return (runState & ACTIVE_COUNT_MASK) == 0;
     }
 
     /**
@@ -1008,17 +1548,7 @@
      * @return the number of steals
      */
     public long getStealCount() {
-        return stealCount.get();
-    }
-
-    /**
-     * Accumulates steal count from a worker.
-     * Call only when worker known to be idle.
-     */
-    private void updateStealCount(ForkJoinWorkerThread w) {
-        int sc = w.getAndClearStealCount();
-        if (sc != 0)
-            stealCount.addAndGet(sc);
+        return stealCount;
     }
 
     /**
@@ -1033,14 +1563,9 @@
      */
     public long getQueuedTaskCount() {
         long count = 0;
-        ForkJoinWorkerThread[] ws = workers;
-        if (ws != null) {
-            for (int i = 0; i < ws.length; ++i) {
-                ForkJoinWorkerThread t = ws[i];
-                if (t != null)
-                    count += t.getQueueSize();
-            }
-        }
+        for (ForkJoinWorkerThread w : workers)
+            if (w != null)
+                count += w.getQueueSize();
         return count;
     }
 
@@ -1094,16 +1619,11 @@
      * @return the number of elements transferred
      */
     protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
-        int n = submissionQueue.drainTo(c);
-        ForkJoinWorkerThread[] ws = workers;
-        if (ws != null) {
-            for (int i = 0; i < ws.length; ++i) {
-                ForkJoinWorkerThread w = ws[i];
-                if (w != null)
-                    n += w.drainTasksTo(c);
-            }
-        }
-        return n;
+        int count = submissionQueue.drainTo(c);
+        for (ForkJoinWorkerThread w : workers)
+            if (w != null)
+                count += w.drainTasksTo(c);
+        return count;
     }
 
     /**
@@ -1114,36 +1634,34 @@
      * @return a string identifying this pool, as well as its state
      */
     public String toString() {
-        int ps = parallelism;
-        int wc = workerCounts;
-        int rc = runControl;
         long st = getStealCount();
         long qt = getQueuedTaskCount();
         long qs = getQueuedSubmissionCount();
+        int wc = workerCounts;
+        int tc = wc >>> TOTAL_COUNT_SHIFT;
+        int rc = wc & RUNNING_COUNT_MASK;
+        int pc = parallelism;
+        int rs = runState;
+        int ac = rs & ACTIVE_COUNT_MASK;
         return super.toString() +
-            "[" + runStateToString(runStateOf(rc)) +
-            ", parallelism = " + ps +
-            ", size = " + totalCountOf(wc) +
-            ", active = " + activeCountOf(rc) +
-            ", running = " + runningCountOf(wc) +
+            "[" + runLevelToString(rs) +
+            ", parallelism = " + pc +
+            ", size = " + tc +
+            ", active = " + ac +
+            ", running = " + rc +
             ", steals = " + st +
             ", tasks = " + qt +
             ", submissions = " + qs +
             "]";
     }
 
-    private static String runStateToString(int rs) {
-        switch(rs) {
-        case RUNNING: return "Running";
-        case SHUTDOWN: return "Shutting down";
-        case TERMINATING: return "Terminating";
-        case TERMINATED: return "Terminated";
-        default: throw new Error("Unknown run state");
-        }
+    private static String runLevelToString(int s) {
+        return ((s & TERMINATED) != 0 ? "Terminated" :
+                ((s & TERMINATING) != 0 ? "Terminating" :
+                 ((s & SHUTDOWN) != 0 ? "Shutting down" :
+                  "Running")));
     }
 
-    // lifecycle control
-
     /**
      * Initiates an orderly shutdown in which previously submitted
      * tasks are executed, but no new tasks will be accepted.
@@ -1158,23 +1676,8 @@
      */
     public void shutdown() {
         checkPermission();
-        transitionRunStateTo(SHUTDOWN);
-        if (canTerminateOnShutdown(runControl)) {
-            if (workers == null) { // shutting down before workers created
-                final ReentrantLock lock = this.workerLock;
-                lock.lock();
-                try {
-                    if (workers == null) {
-                        terminate();
-                        transitionRunStateTo(TERMINATED);
-                        termination.signalAll();
-                    }
-                } finally {
-                    lock.unlock();
-                }
-            }
-            terminateOnShutdown();
-        }
+        advanceRunLevel(SHUTDOWN);
+        tryTerminate(false);
     }
 
     /**
@@ -1195,7 +1698,7 @@
      */
     public List<Runnable> shutdownNow() {
         checkPermission();
-        terminate();
+        tryTerminate(true);
         return Collections.emptyList();
     }
 
@@ -1205,7 +1708,7 @@
      * @return {@code true} if all tasks have completed following shut down
      */
     public boolean isTerminated() {
-        return runStateOf(runControl) == TERMINATED;
+        return runState >= TERMINATED;
     }
 
     /**
@@ -1219,7 +1722,7 @@
      * @return {@code true} if terminating but not yet terminated
      */
     public boolean isTerminating() {
-        return runStateOf(runControl) == TERMINATING;
+        return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
     }
 
     /**
@@ -1228,15 +1731,7 @@
      * @return {@code true} if this pool has been shut down
      */
     public boolean isShutdown() {
-        return runStateOf(runControl) >= SHUTDOWN;
-    }
-
-    /**
-     * Returns true if pool is not terminating or terminated.
-     * Used internally to suppress execution when terminating.
-     */
-    final boolean isProcessingTasks() {
-        return runStateOf(runControl) < TERMINATING;
+        return runState >= SHUTDOWN;
     }
 
     /**
@@ -1252,585 +1747,10 @@
      */
     public boolean awaitTermination(long timeout, TimeUnit unit)
         throws InterruptedException {
-        long nanos = unit.toNanos(timeout);
-        final ReentrantLock lock = this.workerLock;
-        lock.lock();
         try {
-            for (;;) {
-                if (isTerminated())
-                    return true;
-                if (nanos <= 0)
-                    return false;
-                nanos = termination.awaitNanos(nanos);
-            }
-        } finally {
-            lock.unlock();
-        }
-    }
-
-    // Shutdown and termination support
-
-    /**
-     * Callback from terminating worker. Nulls out the corresponding
-     * workers slot, and if terminating, tries to terminate; else
-     * tries to shrink workers array.
-     *
-     * @param w the worker
-     */
-    final void workerTerminated(ForkJoinWorkerThread w) {
-        updateStealCount(w);
-        updateWorkerCount(-1);
-        final ReentrantLock lock = this.workerLock;
-        lock.lock();
-        try {
-            ForkJoinWorkerThread[] ws = workers;
-            if (ws != null) {
-                int idx = w.poolIndex;
-                if (idx >= 0 && idx < ws.length && ws[idx] == w)
-                    ws[idx] = null;
-                if (totalCountOf(workerCounts) == 0) {
-                    terminate(); // no-op if already terminating
-                    transitionRunStateTo(TERMINATED);
-                    termination.signalAll();
-                }
-                else if (isProcessingTasks()) {
-                    tryShrinkWorkerArray();
-                    tryResumeSpare(true); // allow replacement
-                }
-            }
-        } finally {
-            lock.unlock();
-        }
-        signalIdleWorkers();
-    }
-
-    /**
-     * Initiates termination.
-     */
-    private void terminate() {
-        if (transitionRunStateTo(TERMINATING)) {
-            stopAllWorkers();
-            resumeAllSpares();
-            signalIdleWorkers();
-            cancelQueuedSubmissions();
-            cancelQueuedWorkerTasks();
-            interruptUnterminatedWorkers();
-            signalIdleWorkers(); // resignal after interrupt
-        }
-    }
-
-    /**
-     * Possibly terminates when on shutdown state.
-     */
-    private void terminateOnShutdown() {
-        if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
-            terminate();
-    }
-
-    /**
-     * Clears out and cancels submissions.
-     */
-    private void cancelQueuedSubmissions() {
-        ForkJoinTask<?> task;
-        while ((task = pollSubmission()) != null)
-            task.cancel(false);
-    }
-
-    /**
-     * Cleans out worker queues.
-     */
-    private void cancelQueuedWorkerTasks() {
-        final ReentrantLock lock = this.workerLock;
-        lock.lock();
-        try {
-            ForkJoinWorkerThread[] ws = workers;
-            if (ws != null) {
-                for (int i = 0; i < ws.length; ++i) {
-                    ForkJoinWorkerThread t = ws[i];
-                    if (t != null)
-                        t.cancelTasks();
-                }
-            }
-        } finally {
-            lock.unlock();
-        }
-    }
-
-    /**
-     * Sets each worker's status to terminating. Requires lock to avoid
-     * conflicts with add/remove.
-     */
-    private void stopAllWorkers() {
-        final ReentrantLock lock = this.workerLock;
-        lock.lock();
-        try {
-            ForkJoinWorkerThread[] ws = workers;
-            if (ws != null) {
-                for (int i = 0; i < ws.length; ++i) {
-                    ForkJoinWorkerThread t = ws[i];
-                    if (t != null)
-                        t.shutdownNow();
-                }
-            }
-        } finally {
-            lock.unlock();
-        }
-    }
-
-    /**
-     * Interrupts all unterminated workers.  This is not required for
-     * sake of internal control, but may help unstick user code during
-     * shutdown.
-     */
-    private void interruptUnterminatedWorkers() {
-        final ReentrantLock lock = this.workerLock;
-        lock.lock();
-        try {
-            ForkJoinWorkerThread[] ws = workers;
-            if (ws != null) {
-                for (int i = 0; i < ws.length; ++i) {
-                    ForkJoinWorkerThread t = ws[i];
-                    if (t != null && !t.isTerminated()) {
-                        try {
-                            t.interrupt();
-                        } catch (SecurityException ignore) {
-                        }
-                    }
-                }
-            }
-        } finally {
-            lock.unlock();
-        }
-    }
-
-
-    /*
-     * Nodes for event barrier to manage idle threads.  Queue nodes
-     * are basic Treiber stack nodes, also used for spare stack.
-     *
-     * The event barrier has an event count and a wait queue (actually
-     * a Treiber stack).  Workers are enabled to look for work when
-     * the eventCount is incremented. If they fail to find work, they
-     * may wait for next count. Upon release, threads help others wake
-     * up.
-     *
-     * Synchronization events occur only in enough contexts to
-     * maintain overall liveness:
-     *
-     *   - Submission of a new task to the pool
-     *   - Resizes or other changes to the workers array
-     *   - pool termination
-     *   - A worker pushing a task on an empty queue
-     *
-     * The case of pushing a task occurs often enough, and is heavy
-     * enough compared to simple stack pushes, to require special
-     * handling: Method signalWork returns without advancing count if
-     * the queue appears to be empty.  This would ordinarily result in
-     * races causing some queued waiters not to be woken up. To avoid
-     * this, the first worker enqueued in method sync (see
-     * syncIsReleasable) rescans for tasks after being enqueued, and
-     * helps signal if any are found. This works well because the
-     * worker has nothing better to do, and so might as well help
-     * alleviate the overhead and contention on the threads actually
-     * doing work.  Also, since event counts increments on task
-     * availability exist to maintain liveness (rather than to force
-     * refreshes etc), it is OK for callers to exit early if
-     * contending with another signaller.
-     */
-    static final class WaitQueueNode {
-        WaitQueueNode next; // only written before enqueued
-        volatile ForkJoinWorkerThread thread; // nulled to cancel wait
-        final long count; // unused for spare stack
-
-        WaitQueueNode(long c, ForkJoinWorkerThread w) {
-            count = c;
-            thread = w;
-        }
-
-        /**
-         * Wakes up waiter, returning false if known to already
-         */
-        boolean signal() {
-            ForkJoinWorkerThread t = thread;
-            if (t == null)
-                return false;
-            thread = null;
-            LockSupport.unpark(t);
-            return true;
-        }
-
-        /**
-         * Awaits release on sync.
-         */
-        void awaitSyncRelease(ForkJoinPool p) {
-            while (thread != null && !p.syncIsReleasable(this))
-                LockSupport.park(this);
-        }
-
-        /**
-         * Awaits resumption as spare.
-         */
-        void awaitSpareRelease() {
-            while (thread != null) {
-                if (!Thread.interrupted())
-                    LockSupport.park(this);
-            }
-        }
-    }
-
-    /**
-     * Ensures that no thread is waiting for count to advance from the
-     * current value of eventCount read on entry to this method, by
-     * releasing waiting threads if necessary.
-     *
-     * @return the count
-     */
-    final long ensureSync() {
-        long c = eventCount;
-        WaitQueueNode q;
-        while ((q = syncStack) != null && q.count < c) {
-            if (casBarrierStack(q, null)) {
-                do {
-                    q.signal();
-                } while ((q = q.next) != null);
-                break;
-            }
-        }
-        return c;
-    }
-
-    /**
-     * Increments event count and releases waiting threads.
-     */
-    private void signalIdleWorkers() {
-        long c;
-        do {} while (!casEventCount(c = eventCount, c+1));
-        ensureSync();
-    }
-
-    /**
-     * Signals threads waiting to poll a task. Because method sync
-     * rechecks availability, it is OK to only proceed if queue
-     * appears to be non-empty, and OK to skip under contention to
-     * increment count (since some other thread succeeded).
-     */
-    final void signalWork() {
-        long c;
-        WaitQueueNode q;
-        if (syncStack != null &&
-            casEventCount(c = eventCount, c+1) &&
-            (((q = syncStack) != null && q.count <= c) &&
-             (!casBarrierStack(q, q.next) || !q.signal())))
-            ensureSync();
-    }
-
-    /**
-     * Waits until event count advances from last value held by
-     * caller, or if excess threads, caller is resumed as spare, or
-     * caller or pool is terminating. Updates caller's event on exit.
-     *
-     * @param w the calling worker thread
-     */
-    final void sync(ForkJoinWorkerThread w) {
-        updateStealCount(w); // Transfer w's count while it is idle
-
-        while (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) {
-            long prev = w.lastEventCount;
-            WaitQueueNode node = null;
-            WaitQueueNode h;
-            while (eventCount == prev &&
-                   ((h = syncStack) == null || h.count == prev)) {
-                if (node == null)
-                    node = new WaitQueueNode(prev, w);
-                if (casBarrierStack(node.next = h, node)) {
-                    node.awaitSyncRelease(this);
-                    break;
-                }
-            }
-            long ec = ensureSync();
-            if (ec != prev) {
-                w.lastEventCount = ec;
-                break;
-            }
-        }
-    }
-
-    /**
-     * Returns {@code true} if worker waiting on sync can proceed:
-     *  - on signal (thread == null)
-     *  - on event count advance (winning race to notify vs signaller)
-     *  - on interrupt
-     *  - if the first queued node, we find work available
-     * If node was not signalled and event count not advanced on exit,
-     * then we also help advance event count.
-     *
-     * @return {@code true} if node can be released
-     */
-    final boolean syncIsReleasable(WaitQueueNode node) {
-        long prev = node.count;
-        if (!Thread.interrupted() && node.thread != null &&
-            (node.next != null ||
-             !ForkJoinWorkerThread.hasQueuedTasks(workers)) &&
-            eventCount == prev)
+            return termination.awaitAdvanceInterruptibly(0, timeout, unit) > 0;
+        } catch (TimeoutException ex) {
             return false;
-        if (node.thread != null) {
-            node.thread = null;
-            long ec = eventCount;
-            if (prev <= ec) // help signal
-                casEventCount(ec, ec+1);
-        }
-        return true;
-    }
-
-    /**
-     * Returns {@code true} if a new sync event occurred since last
-     * call to sync or this method, if so, updating caller's count.
-     */
-    final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
-        long lc = w.lastEventCount;
-        long ec = ensureSync();
-        if (ec == lc)
-            return false;
-        w.lastEventCount = ec;
-        return true;
-    }
-
-    //  Parallelism maintenance
-
-    /**
-     * Decrements running count; if too low, adds spare.
-     *
-     * Conceptually, all we need to do here is add or resume a
-     * spare thread when one is about to block (and remove or
-     * suspend it later when unblocked -- see suspendIfSpare).
-     * However, implementing this idea requires coping with
-     * several problems: we have imperfect information about the
-     * states of threads. Some count updates can and usually do
-     * lag run state changes, despite arrangements to keep them
-     * accurate (for example, when possible, updating counts
-     * before signalling or resuming), especially when running on
-     * dynamic JVMs that don't optimize the infrequent paths that
-     * update counts. Generating too many threads can make these
-     * problems become worse, because excess threads are more
-     * likely to be context-switched with others, slowing them all
-     * down, especially if there is no work available, so all are
-     * busy scanning or idling.  Also, excess spare threads can
-     * only be suspended or removed when they are idle, not
-     * immediately when they aren't needed. So adding threads will
-     * raise parallelism level for longer than necessary.  Also,
-     * FJ applications often encounter highly transient peaks when
-     * many threads are blocked joining, but for less time than it
-     * takes to create or resume spares.
-     *
-     * @param joinMe if non-null, return early if done
-     * @param maintainParallelism if true, try to stay within
-     * target counts, else create only to avoid starvation
-     * @return true if joinMe known to be done
-     */
-    final boolean preJoin(ForkJoinTask<?> joinMe,
-                          boolean maintainParallelism) {
-        maintainParallelism &= maintainsParallelism; // overrride
-        boolean dec = false;  // true when running count decremented
-        while (spareStack == null || !tryResumeSpare(dec)) {
-            int counts = workerCounts;
-            if (dec || (dec = casWorkerCounts(counts, --counts))) {
-                if (!needSpare(counts, maintainParallelism))
-                    break;
-                if (joinMe.status < 0)
-                    return true;
-                if (tryAddSpare(counts))
-                    break;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Same idea as preJoin
-     */
-    final boolean preBlock(ManagedBlocker blocker,
-                           boolean maintainParallelism) {
-        maintainParallelism &= maintainsParallelism;
-        boolean dec = false;
-        while (spareStack == null || !tryResumeSpare(dec)) {
-            int counts = workerCounts;
-            if (dec || (dec = casWorkerCounts(counts, --counts))) {
-                if (!needSpare(counts, maintainParallelism))
-                    break;
-                if (blocker.isReleasable())
-                    return true;
-                if (tryAddSpare(counts))
-                    break;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Returns {@code true} if a spare thread appears to be needed.
-     * If maintaining parallelism, returns true when the deficit in
-     * running threads is more than the surplus of total threads, and
-     * there is apparently some work to do.  This self-limiting rule
-     * means that the more threads that have already been added, the
-     * less parallelism we will tolerate before adding another.
-     *
-     * @param counts current worker counts
-     * @param maintainParallelism try to maintain parallelism
-     */
-    private boolean needSpare(int counts, boolean maintainParallelism) {
-        int ps = parallelism;
-        int rc = runningCountOf(counts);
-        int tc = totalCountOf(counts);
-        int runningDeficit = ps - rc;
-        int totalSurplus = tc - ps;
-        return (tc < maxPoolSize &&
-                (rc == 0 || totalSurplus < 0 ||
-                 (maintainParallelism &&
-                  runningDeficit > totalSurplus &&
-                  ForkJoinWorkerThread.hasQueuedTasks(workers))));
-    }
-
-    /**
-     * Adds a spare worker if lock available and no more than the
-     * expected numbers of threads exist.
-     *
-     * @return true if successful
-     */
-    private boolean tryAddSpare(int expectedCounts) {
-        final ReentrantLock lock = this.workerLock;
-        int expectedRunning = runningCountOf(expectedCounts);
-        int expectedTotal = totalCountOf(expectedCounts);
-        boolean success = false;
-        boolean locked = false;
-        // confirm counts while locking; CAS after obtaining lock
-        try {
-            for (;;) {
-                int s = workerCounts;
-                int tc = totalCountOf(s);
-                int rc = runningCountOf(s);
-                if (rc > expectedRunning || tc > expectedTotal)
-                    break;
-                if (!locked && !(locked = lock.tryLock()))
-                    break;
-                if (casWorkerCounts(s, workerCountsFor(tc+1, rc+1))) {
-                    createAndStartSpare(tc);
-                    success = true;
-                    break;
-                }
-            }
-        } finally {
-            if (locked)
-                lock.unlock();
-        }
-        return success;
-    }
-
-    /**
-     * Adds the kth spare worker. On entry, pool counts are already
-     * adjusted to reflect addition.
-     */
-    private void createAndStartSpare(int k) {
-        ForkJoinWorkerThread w = null;
-        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(k + 1);
-        int len = ws.length;
-        // Probably, we can place at slot k. If not, find empty slot
-        if (k < len && ws[k] != null) {
-            for (k = 0; k < len && ws[k] != null; ++k)
-                ;
-        }
-        if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) {
-            ws[k] = w;
-            w.start();
-        }
-        else
-            updateWorkerCount(-1); // adjust on failure
-        signalIdleWorkers();
-    }
-
-    /**
-     * Suspends calling thread w if there are excess threads.  Called
-     * only from sync.  Spares are enqueued in a Treiber stack using
-     * the same WaitQueueNodes as barriers.  They are resumed mainly
-     * in preJoin, but are also woken on pool events that require all
-     * threads to check run state.
-     *
-     * @param w the caller
-     */
-    private boolean suspendIfSpare(ForkJoinWorkerThread w) {
-        WaitQueueNode node = null;
-        int s;
-        while (parallelism < runningCountOf(s = workerCounts)) {
-            if (node == null)
-                node = new WaitQueueNode(0, w);
-            if (casWorkerCounts(s, s-1)) { // representation-dependent
-                // push onto stack
-                do {} while (!casSpareStack(node.next = spareStack, node));
-                // block until released by resumeSpare
-                node.awaitSpareRelease();
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Tries to pop and resume a spare thread.
-     *
-     * @param updateCount if true, increment running count on success
-     * @return true if successful
-     */
-    private boolean tryResumeSpare(boolean updateCount) {
-        WaitQueueNode q;
-        while ((q = spareStack) != null) {
-            if (casSpareStack(q, q.next)) {
-                if (updateCount)
-                    updateRunningCount(1);
-                q.signal();
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Pops and resumes all spare threads. Same idea as ensureSync.
-     *
-     * @return true if any spares released
-     */
-    private boolean resumeAllSpares() {
-        WaitQueueNode q;
-        while ( (q = spareStack) != null) {
-            if (casSpareStack(q, null)) {
-                do {
-                    updateRunningCount(1);
-                    q.signal();
-                } while ((q = q.next) != null);
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Pops and shuts down excessive spare threads. Call only while
-     * holding lock. This is not guaranteed to eliminate all excess
-     * threads, only those suspended as spares, which are the ones
-     * unlikely to be needed in the future.
-     */
-    private void trimSpares() {
-        int surplus = totalCountOf(workerCounts) - parallelism;
-        WaitQueueNode q;
-        while (surplus > 0 && (q = spareStack) != null) {
-            if (casSpareStack(q, null)) {
-                do {
-                    updateRunningCount(1);
-                    ForkJoinWorkerThread w = q.thread;
-                    if (w != null && surplus > 0 &&
-                        runningCountOf(workerCounts) > 0 && w.shutdown())
-                        --surplus;
-                    q.signal();
-                } while ((q = q.next) != null);
-            }
         }
     }
 
@@ -1838,11 +1758,17 @@
      * Interface for extending managed parallelism for tasks running
      * in {@link ForkJoinPool}s.
      *
-     * <p>A {@code ManagedBlocker} provides two methods.
-     * Method {@code isReleasable} must return {@code true} if
-     * blocking is not necessary. Method {@code block} blocks the
-     * current thread if necessary (perhaps internally invoking
-     * {@code isReleasable} before actually blocking).
+     * <p>A {@code ManagedBlocker} provides two methods.  Method
+     * {@code isReleasable} must return {@code true} if blocking is
+     * not necessary. Method {@code block} blocks the current thread
+     * if necessary (perhaps internally invoking {@code isReleasable}
+     * before actually blocking). The unusual methods in this API
+     * accommodate synchronizers that may, but don't usually, block
+     * for long periods. Similarly, they allow more efficient internal
+     * handling of cases in which additional workers may be, but
+     * usually are not, needed to ensure sufficient parallelism.
+     * Toward this end, implementations of method {@code isReleasable}
+     * must be amenable to repeated invocation.
      *
      * <p>For example, here is a ManagedBlocker based on a
      * ReentrantLock:
@@ -1860,6 +1786,26 @@
      *     return hasLock || (hasLock = lock.tryLock());
      *   }
      * }}</pre>
+     *
+     * <p>Here is a class that possibly blocks waiting for an
+     * item on a given queue:
+     *  <pre> {@code
+     * class QueueTaker<E> implements ManagedBlocker {
+     *   final BlockingQueue<E> queue;
+     *   volatile E item = null;
+     *   QueueTaker(BlockingQueue<E> q) { this.queue = q; }
+     *   public boolean block() throws InterruptedException {
+     *     if (item == null)
+     *       item = queue.take();
+     *     return true;
+     *   }
+     *   public boolean isReleasable() {
+     *     return item != null || (item = queue.poll()) != null;
+     *   }
+     *   public E getItem() { // call after pool.managedBlock completes
+     *     return item;
+     *   }
+     * }}</pre>
      */
     public static interface ManagedBlocker {
         /**
@@ -1883,14 +1829,7 @@
      * Blocks in accord with the given blocker.  If the current thread
      * is a {@link ForkJoinWorkerThread}, this method possibly
      * arranges for a spare thread to be activated if necessary to
-     * ensure parallelism while the current thread is blocked.
-     *
-     * <p>If {@code maintainParallelism} is {@code true} and the pool
-     * supports it ({@link #getMaintainsParallelism}), this method
-     * attempts to maintain the pool's nominal parallelism. Otherwise
-     * it activates a thread only if necessary to avoid complete
-     * starvation. This option may be preferable when blockages use
-     * timeouts, or are almost always brief.
+     * ensure sufficient parallelism while the current thread is blocked.
      *
      * <p>If the caller is not a {@link ForkJoinTask}, this method is
      * behaviorally equivalent to
@@ -1904,33 +1843,18 @@
      * first be expanded to ensure parallelism, and later adjusted.
      *
      * @param blocker the blocker
-     * @param maintainParallelism if {@code true} and supported by
-     * this pool, attempt to maintain the pool's nominal parallelism;
-     * otherwise activate a thread only if necessary to avoid
-     * complete starvation.
      * @throws InterruptedException if blocker.block did so
      */
-    public static void managedBlock(ManagedBlocker blocker,
-                                    boolean maintainParallelism)
+    public static void managedBlock(ManagedBlocker blocker)
         throws InterruptedException {
         Thread t = Thread.currentThread();
-        ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ?
-                             ((ForkJoinWorkerThread) t).pool : null);
-        if (!blocker.isReleasable()) {
-            try {
-                if (pool == null ||
-                    !pool.preBlock(blocker, maintainParallelism))
-                    awaitBlocker(blocker);
-            } finally {
-                if (pool != null)
-                    pool.updateRunningCount(1);
-            }
+        if (t instanceof ForkJoinWorkerThread) {
+            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
+            w.pool.awaitBlocker(blocker);
         }
-    }
-
-    private static void awaitBlocker(ManagedBlocker blocker)
-        throws InterruptedException {
-        do {} while (!blocker.isReleasable() && !blocker.block());
+        else {
+            do {} while (!blocker.isReleasable() && !blocker.block());
+        }
     }
 
     // AbstractExecutorService overrides.  These rely on undocumented
@@ -1948,32 +1872,18 @@
     // Unsafe mechanics
 
     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
-    private static final long eventCountOffset =
-        objectFieldOffset("eventCount", ForkJoinPool.class);
     private static final long workerCountsOffset =
         objectFieldOffset("workerCounts", ForkJoinPool.class);
-    private static final long runControlOffset =
-        objectFieldOffset("runControl", ForkJoinPool.class);
-    private static final long syncStackOffset =
-        objectFieldOffset("syncStack",ForkJoinPool.class);
-    private static final long spareStackOffset =
-        objectFieldOffset("spareStack", ForkJoinPool.class);
-
-    private boolean casEventCount(long cmp, long val) {
-        return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
-    }
-    private boolean casWorkerCounts(int cmp, int val) {
-        return UNSAFE.compareAndSwapInt(this, workerCountsOffset, cmp, val);
-    }
-    private boolean casRunControl(int cmp, int val) {
-        return UNSAFE.compareAndSwapInt(this, runControlOffset, cmp, val);
-    }
-    private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
-        return UNSAFE.compareAndSwapObject(this, spareStackOffset, cmp, val);
-    }
-    private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
-        return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
-    }
+    private static final long runStateOffset =
+        objectFieldOffset("runState", ForkJoinPool.class);
+    private static final long eventCountOffset =
+        objectFieldOffset("eventCount", ForkJoinPool.class);
+    private static final long eventWaitersOffset =
+        objectFieldOffset("eventWaiters", ForkJoinPool.class);
+    private static final long stealCountOffset =
+        objectFieldOffset("stealCount", ForkJoinPool.class);
+    private static final long spareWaitersOffset =
+        objectFieldOffset("spareWaiters", ForkJoinPool.class);
 
     private static long objectFieldOffset(String field, Class<?> klazz) {
         try {
--- a/src/share/classes/java/util/concurrent/ForkJoinTask.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/concurrent/ForkJoinTask.java	Fri Sep 24 16:41:32 2010 -0700
@@ -91,10 +91,7 @@
  * results of a task is {@link #join}, but there are several variants:
  * The {@link Future#get} methods support interruptible and/or timed
  * waits for completion and report results using {@code Future}
- * conventions. Method {@link #helpJoin} enables callers to actively
- * execute other tasks while awaiting joins, which is sometimes more
- * efficient but only applies when all subtasks are known to be
- * strictly tree-structured. Method {@link #invoke} is semantically
+ * conventions. Method {@link #invoke} is semantically
  * equivalent to {@code fork(); join()} but always attempts to begin
  * execution in the current thread. The "<em>quiet</em>" forms of
  * these methods do not extract results or report exceptions. These
@@ -130,7 +127,7 @@
  * ForkJoinTasks (as may be determined using method {@link
  * #inForkJoinPool}).  Attempts to invoke them in other contexts
  * result in exceptions or errors, possibly including
- * ClassCastException.
+ * {@code ClassCastException}.
  *
  * <p>Most base support methods are {@code final}, to prevent
  * overriding of implementations that are intrinsically tied to the
@@ -152,9 +149,8 @@
  *
  * <p>This class provides {@code adapt} methods for {@link Runnable}
  * and {@link Callable}, that may be of use when mixing execution of
- * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
- * are of this form, consider using a pool in
- * {@linkplain ForkJoinPool#setAsyncMode async mode}.
+ * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
+ * of this form, consider using a pool constructed in <em>asyncMode</em>.
  *
  * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
  * used in extensions such as remote execution frameworks. It is
@@ -166,33 +162,43 @@
  */
 public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
 
-    /**
-     * Run control status bits packed into a single int to minimize
-     * footprint and to ensure atomicity (via CAS).  Status is
-     * initially zero, and takes on nonnegative values until
-     * completed, upon which status holds COMPLETED. CANCELLED, or
-     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
-     * blocking waits by other threads have SIGNAL_MASK bits set --
-     * bit 15 for external (nonFJ) waits, and the rest a count of
-     * waiting FJ threads.  (This representation relies on
-     * ForkJoinPool max thread limits). Completion of a stolen task
-     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
-     * though suboptimal for some purposes, we use basic builtin
-     * wait/notify to take advantage of "monitor inflation" in JVMs
-     * that we would otherwise need to emulate to avoid adding further
-     * per-task bookkeeping overhead. Note that bits 16-28 are
-     * currently unused. Also value 0x80000000 is available as spare
-     * completion value.
+    /*
+     * See the internal documentation of class ForkJoinPool for a
+     * general implementation overview.  ForkJoinTasks are mainly
+     * responsible for maintaining their "status" field amidst relays
+     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
+     * methods of this class are more-or-less layered into (1) basic
+     * status maintenance (2) execution and awaiting completion (3)
+     * user-level methods that additionally report results. This is
+     * sometimes hard to see because this file orders exported methods
+     * in a way that flows well in javadocs. In particular, most
+     * join mechanics are in method quietlyJoin, below.
      */
+
+    /*
+     * The status field holds run control status bits packed into a
+     * single int to minimize footprint and to ensure atomicity (via
+     * CAS).  Status is initially zero, and takes on nonnegative
+     * values until completed, upon which status holds value
+     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
+     * waits by other threads have the SIGNAL bit set.  Completion of
+     * a stolen task with SIGNAL set awakens any waiters via
+     * notifyAll. Even though suboptimal for some purposes, we use
+     * basic builtin wait/notify to take advantage of "monitor
+     * inflation" in JVMs that we would otherwise need to emulate to
+     * avoid adding further per-task bookkeeping overhead.  We want
+     * these monitors to be "fat", i.e., not use biasing or thin-lock
+     * techniques, so use some odd coding idioms that tend to avoid
+     * them.
+     */
+
+    /** The run status of this task */
     volatile int status; // accessed directly by pool and workers
 
-    static final int COMPLETION_MASK      = 0xe0000000;
-    static final int NORMAL               = 0xe0000000; // == mask
-    static final int CANCELLED            = 0xc0000000;
-    static final int EXCEPTIONAL          = 0xa0000000;
-    static final int SIGNAL_MASK          = 0x0000ffff;
-    static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
-    static final int EXTERNAL_SIGNAL      = 0x00008000; // top bit of low word
+    private static final int NORMAL      = -1;
+    private static final int CANCELLED   = -2;
+    private static final int EXCEPTIONAL = -3;
+    private static final int SIGNAL      =  1;
 
     /**
      * Table of exceptions thrown by tasks, to enable reporting by
@@ -206,176 +212,94 @@
         Collections.synchronizedMap
         (new WeakHashMap<ForkJoinTask<?>, Throwable>());
 
-    // within-package utilities
+    // Maintaining completion status
 
     /**
-     * Gets current worker thread, or null if not a worker thread.
-     */
-    static ForkJoinWorkerThread getWorker() {
-        Thread t = Thread.currentThread();
-        return ((t instanceof ForkJoinWorkerThread) ?
-                (ForkJoinWorkerThread) t : null);
-    }
-
-    final boolean casStatus(int cmp, int val) {
-        return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
-    }
-
-    /**
-     * Workaround for not being able to rethrow unchecked exceptions.
-     */
-    static void rethrowException(Throwable ex) {
-        if (ex != null)
-            UNSAFE.throwException(ex);
-    }
-
-    // Setting completion status
-
-    /**
-     * Marks completion and wakes up threads waiting to join this task.
+     * Marks completion and wakes up threads waiting to join this task,
+     * also clearing signal request bits.
      *
      * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
      */
-    final void setCompletion(int completion) {
-        ForkJoinPool pool = getPool();
-        if (pool != null) {
-            int s; // Clear signal bits while setting completion status
-            do {} while ((s = status) >= 0 && !casStatus(s, completion));
-
-            if ((s & SIGNAL_MASK) != 0) {
-                if ((s &= INTERNAL_SIGNAL_MASK) != 0)
-                    pool.updateRunningCount(s);
-                synchronized (this) { notifyAll(); }
-            }
-        }
-        else
-            externallySetCompletion(completion);
-    }
-
-    /**
-     * Version of setCompletion for non-FJ threads.  Leaves signal
-     * bits for unblocked threads to adjust, and always notifies.
-     */
-    private void externallySetCompletion(int completion) {
+    private void setCompletion(int completion) {
         int s;
-        do {} while ((s = status) >= 0 &&
-                     !casStatus(s, (s & SIGNAL_MASK) | completion));
-        synchronized (this) { notifyAll(); }
-    }
-
-    /**
-     * Sets status to indicate normal completion.
-     */
-    final void setNormalCompletion() {
-        // Try typical fast case -- single CAS, no signal, not already done.
-        // Manually expand casStatus to improve chances of inlining it
-        if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
-            setCompletion(NORMAL);
-    }
-
-    // internal waiting and notification
-
-    /**
-     * Performs the actual monitor wait for awaitDone.
-     */
-    private void doAwaitDone() {
-        // Minimize lock bias and in/de-flation effects by maximizing
-        // chances of waiting inside sync
-        try {
-            while (status >= 0)
-                synchronized (this) { if (status >= 0) wait(); }
-        } catch (InterruptedException ie) {
-            onInterruptedWait();
+        while ((s = status) >= 0) {
+            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
+                if (s != 0)
+                    synchronized (this) { notifyAll(); }
+                break;
+            }
         }
     }
 
     /**
-     * Performs the actual timed monitor wait for awaitDone.
+     * Records exception and sets exceptional completion.
+     *
+     * @return status on exit
      */
-    private void doAwaitDone(long startTime, long nanos) {
-        synchronized (this) {
+    private void setExceptionalCompletion(Throwable rex) {
+        exceptionMap.put(this, rex);
+        setCompletion(EXCEPTIONAL);
+    }
+
+    /**
+     * Blocks a worker thread until completion. Called only by
+     * pool. Currently unused -- pool-based waits use timeout
+     * version below.
+     */
+    final void internalAwaitDone() {
+        int s;         // the odd construction reduces lock bias effects
+        while ((s = status) >= 0) {
             try {
-                while (status >= 0) {
-                    long nt = nanos - (System.nanoTime() - startTime);
-                    if (nt <= 0)
-                        break;
-                    wait(nt / 1000000, (int) (nt % 1000000));
+                synchronized(this) {
+                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
+                        wait();
                 }
             } catch (InterruptedException ie) {
-                onInterruptedWait();
+                cancelIfTerminating();
             }
         }
     }
 
-    // Awaiting completion
-
     /**
-     * Sets status to indicate there is joiner, then waits for join,
-     * surrounded with pool notifications.
+     * Blocks a worker thread until completed or timed out.  Called
+     * only by pool.
      *
-     * @return status upon exit
+     * @return status on exit
      */
-    private int awaitDone(ForkJoinWorkerThread w,
-                          boolean maintainParallelism) {
-        ForkJoinPool pool = (w == null) ? null : w.pool;
+    final int internalAwaitDone(long millis) {
         int s;
-        while ((s = status) >= 0) {
-            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
-                if (pool == null || !pool.preJoin(this, maintainParallelism))
-                    doAwaitDone();
-                if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
-                    adjustPoolCountsOnUnblock(pool);
-                break;
+        if ((s = status) >= 0) {
+            try {
+                synchronized(this) {
+                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
+                        wait(millis, 0);
+                }
+            } catch (InterruptedException ie) {
+                cancelIfTerminating();
             }
+            s = status;
         }
         return s;
     }
 
     /**
-     * Timed version of awaitDone
-     *
-     * @return status upon exit
+     * Blocks a non-worker-thread until completion.
      */
-    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
-        ForkJoinPool pool = (w == null) ? null : w.pool;
+    private void externalAwaitDone() {
         int s;
         while ((s = status) >= 0) {
-            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
-                long startTime = System.nanoTime();
-                if (pool == null || !pool.preJoin(this, false))
-                    doAwaitDone(startTime, nanos);
-                if ((s = status) >= 0) {
-                    adjustPoolCountsOnCancelledWait(pool);
-                    s = status;
-                }
-                if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
-                    adjustPoolCountsOnUnblock(pool);
-                break;
-            }
-        }
-        return s;
-    }
-
-    /**
-     * Notifies pool that thread is unblocked. Called by signalled
-     * threads when woken by non-FJ threads (which is atypical).
-     */
-    private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
-        int s;
-        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
-        if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
-            pool.updateRunningCount(s);
-    }
-
-    /**
-     * Notifies pool to adjust counts on cancelled or timed out wait.
-     */
-    private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
-        if (pool != null) {
-            int s;
-            while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
-                if (casStatus(s, s - 1)) {
-                    pool.updateRunningCount(1);
+            synchronized(this) {
+                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
+                    boolean interrupted = false;
+                    while (status >= 0) {
+                        try {
+                            wait();
+                        } catch (InterruptedException ie) {
+                            interrupted = true;
+                        }
+                    }
+                    if (interrupted)
+                        Thread.currentThread().interrupt();
                     break;
                 }
             }
@@ -383,153 +307,19 @@
     }
 
     /**
-     * Handles interruptions during waits.
-     */
-    private void onInterruptedWait() {
-        ForkJoinWorkerThread w = getWorker();
-        if (w == null)
-            Thread.currentThread().interrupt(); // re-interrupt
-        else if (w.isTerminating())
-            cancelIgnoringExceptions();
-        // else if FJworker, ignore interrupt
-    }
-
-    // Recording and reporting exceptions
-
-    private void setDoneExceptionally(Throwable rex) {
-        exceptionMap.put(this, rex);
-        setCompletion(EXCEPTIONAL);
-    }
-
-    /**
-     * Throws the exception associated with status s.
-     *
-     * @throws the exception
-     */
-    private void reportException(int s) {
-        if ((s &= COMPLETION_MASK) < NORMAL) {
-            if (s == CANCELLED)
-                throw new CancellationException();
-            else
-                rethrowException(exceptionMap.get(this));
-        }
-    }
-
-    /**
-     * Returns result or throws exception using j.u.c.Future conventions.
-     * Only call when {@code isDone} known to be true or thread known
-     * to be interrupted.
-     */
-    private V reportFutureResult()
-        throws InterruptedException, ExecutionException {
-        if (Thread.interrupted())
-            throw new InterruptedException();
-        int s = status & COMPLETION_MASK;
-        if (s < NORMAL) {
-            Throwable ex;
-            if (s == CANCELLED)
-                throw new CancellationException();
-            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
-                throw new ExecutionException(ex);
-        }
-        return getRawResult();
-    }
-
-    /**
-     * Returns result or throws exception using j.u.c.Future conventions
-     * with timeouts.
-     */
-    private V reportTimedFutureResult()
-        throws InterruptedException, ExecutionException, TimeoutException {
-        if (Thread.interrupted())
-            throw new InterruptedException();
-        Throwable ex;
-        int s = status & COMPLETION_MASK;
-        if (s == NORMAL)
-            return getRawResult();
-        else if (s == CANCELLED)
-            throw new CancellationException();
-        else if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
-            throw new ExecutionException(ex);
-        else
-            throw new TimeoutException();
-    }
-
-    // internal execution methods
-
-    /**
-     * Calls exec, recording completion, and rethrowing exception if
-     * encountered. Caller should normally check status before calling.
-     *
-     * @return true if completed normally
-     */
-    private boolean tryExec() {
-        try { // try block must contain only call to exec
-            if (!exec())
-                return false;
-        } catch (Throwable rex) {
-            setDoneExceptionally(rex);
-            rethrowException(rex);
-            return false; // not reached
-        }
-        setNormalCompletion();
-        return true;
-    }
-
-    /**
-     * Main execution method used by worker threads. Invokes
-     * base computation unless already complete.
+     * Unless done, calls exec and records status if completed, but
+     * doesn't wait for completion otherwise. Primary execution method
+     * for ForkJoinWorkerThread.
      */
     final void quietlyExec() {
-        if (status >= 0) {
-            try {
-                if (!exec())
-                    return;
-            } catch (Throwable rex) {
-                setDoneExceptionally(rex);
+        try {
+            if (status < 0 || !exec())
                 return;
-            }
-            setNormalCompletion();
-        }
-    }
-
-    /**
-     * Calls exec(), recording but not rethrowing exception.
-     * Caller should normally check status before calling.
-     *
-     * @return true if completed normally
-     */
-    private boolean tryQuietlyInvoke() {
-        try {
-            if (!exec())
-                return false;
         } catch (Throwable rex) {
-            setDoneExceptionally(rex);
-            return false;
+            setExceptionalCompletion(rex);
+            return;
         }
-        setNormalCompletion();
-        return true;
-    }
-
-    /**
-     * Cancels, ignoring any exceptions it throws.
-     */
-    final void cancelIgnoringExceptions() {
-        try {
-            cancel(false);
-        } catch (Throwable ignore) {
-        }
-    }
-
-    /**
-     * Main implementation of helpJoin
-     */
-    private int busyJoin(ForkJoinWorkerThread w) {
-        int s;
-        ForkJoinTask<?> t;
-        while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
-            t.quietlyExec();
-        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
+        setCompletion(NORMAL); // must be outside try block
     }
 
     // public methods
@@ -567,34 +357,41 @@
      * @return the computed result
      */
     public final V join() {
-        ForkJoinWorkerThread w = getWorker();
-        if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
-            reportException(awaitDone(w, true));
+        quietlyJoin();
+        Throwable ex;
+        if (status < NORMAL && (ex = getException()) != null)
+            UNSAFE.throwException(ex);
         return getRawResult();
     }
 
     /**
      * Commences performing this task, awaits its completion if
-     * necessary, and return its result, or throws an (unchecked)
-     * exception if the underlying computation did so.
+     * necessary, and returns its result, or throws an (unchecked)
+     * {@code RuntimeException} or {@code Error} if the underlying
+     * computation did so.
      *
      * @return the computed result
      */
     public final V invoke() {
-        if (status >= 0 && tryExec())
-            return getRawResult();
-        else
-            return join();
+        quietlyInvoke();
+        Throwable ex;
+        if (status < NORMAL && (ex = getException()) != null)
+            UNSAFE.throwException(ex);
+        return getRawResult();
     }
 
     /**
      * Forks the given tasks, returning when {@code isDone} holds for
      * each task or an (unchecked) exception is encountered, in which
-     * case the exception is rethrown.  If either task encounters an
-     * exception, the other one may be, but is not guaranteed to be,
-     * cancelled.  If both tasks throw an exception, then this method
-     * throws one of them.  The individual status of each task may be
-     * checked using {@link #getException()} and related methods.
+     * case the exception is rethrown. If more than one task
+     * encounters an exception, then this method throws any one of
+     * these exceptions. If any task encounters an exception, the
+     * other may be cancelled. However, the execution status of
+     * individual tasks is not guaranteed upon exceptional return. The
+     * status of each task may be obtained using {@link
+     * #getException()} and related methods to check if they have been
+     * cancelled, completed normally or exceptionally, or left
+     * unprocessed.
      *
      * <p>This method may be invoked only from within {@code
      * ForkJoinTask} computations (as may be determined using method
@@ -615,12 +412,14 @@
     /**
      * Forks the given tasks, returning when {@code isDone} holds for
      * each task or an (unchecked) exception is encountered, in which
-     * case the exception is rethrown. If any task encounters an
-     * exception, others may be, but are not guaranteed to be,
-     * cancelled.  If more than one task encounters an exception, then
-     * this method throws any one of these exceptions.  The individual
-     * status of each task may be checked using {@link #getException()}
-     * and related methods.
+     * case the exception is rethrown. If more than one task
+     * encounters an exception, then this method throws any one of
+     * these exceptions. If any task encounters an exception, others
+     * may be cancelled. However, the execution status of individual
+     * tasks is not guaranteed upon exceptional return. The status of
+     * each task may be obtained using {@link #getException()} and
+     * related methods to check if they have been cancelled, completed
+     * normally or exceptionally, or left unprocessed.
      *
      * <p>This method may be invoked only from within {@code
      * ForkJoinTask} computations (as may be determined using method
@@ -644,7 +443,7 @@
                 t.fork();
             else {
                 t.quietlyInvoke();
-                if (ex == null)
+                if (ex == null && t.status < NORMAL)
                     ex = t.getException();
             }
         }
@@ -655,26 +454,27 @@
                     t.cancel(false);
                 else {
                     t.quietlyJoin();
-                    if (ex == null)
+                    if (ex == null && t.status < NORMAL)
                         ex = t.getException();
                 }
             }
         }
         if (ex != null)
-            rethrowException(ex);
+            UNSAFE.throwException(ex);
     }
 
     /**
      * Forks all tasks in the specified collection, returning when
      * {@code isDone} holds for each task or an (unchecked) exception
-     * is encountered.  If any task encounters an exception, others
-     * may be, but are not guaranteed to be, cancelled.  If more than
-     * one task encounters an exception, then this method throws any
-     * one of these exceptions.  The individual status of each task
-     * may be checked using {@link #getException()} and related
-     * methods.  The behavior of this operation is undefined if the
-     * specified collection is modified while the operation is in
-     * progress.
+     * is encountered, in which case the exception is rethrown. If
+     * more than one task encounters an exception, then this method
+     * throws any one of these exceptions. If any task encounters an
+     * exception, others may be cancelled. However, the execution
+     * status of individual tasks is not guaranteed upon exceptional
+     * return. The status of each task may be obtained using {@link
+     * #getException()} and related methods to check if they have been
+     * cancelled, completed normally or exceptionally, or left
+     * unprocessed.
      *
      * <p>This method may be invoked only from within {@code
      * ForkJoinTask} computations (as may be determined using method
@@ -706,7 +506,7 @@
                 t.fork();
             else {
                 t.quietlyInvoke();
-                if (ex == null)
+                if (ex == null && t.status < NORMAL)
                     ex = t.getException();
             }
         }
@@ -717,13 +517,13 @@
                     t.cancel(false);
                 else {
                     t.quietlyJoin();
-                    if (ex == null)
+                    if (ex == null && t.status < NORMAL)
                         ex = t.getException();
                 }
             }
         }
         if (ex != null)
-            rethrowException(ex);
+            UNSAFE.throwException(ex);
         return tasks;
     }
 
@@ -753,7 +553,35 @@
      */
     public boolean cancel(boolean mayInterruptIfRunning) {
         setCompletion(CANCELLED);
-        return (status & COMPLETION_MASK) == CANCELLED;
+        return status == CANCELLED;
+    }
+
+    /**
+     * Cancels, ignoring any exceptions thrown by cancel. Used during
+     * worker and pool shutdown. Cancel is spec'ed not to throw any
+     * exceptions, but if it does anyway, we have no recourse during
+     * shutdown, so guard against this case.
+     */
+    final void cancelIgnoringExceptions() {
+        try {
+            cancel(false);
+        } catch (Throwable ignore) {
+        }
+    }
+
+    /**
+     * Cancels if current thread is a terminating worker thread,
+     * ignoring any exceptions thrown by cancel.
+     */
+    final void cancelIfTerminating() {
+        Thread t = Thread.currentThread();
+        if ((t instanceof ForkJoinWorkerThread) &&
+            ((ForkJoinWorkerThread) t).isTerminating()) {
+            try {
+                cancel(false);
+            } catch (Throwable ignore) {
+            }
+        }
     }
 
     public final boolean isDone() {
@@ -761,7 +589,7 @@
     }
 
     public final boolean isCancelled() {
-        return (status & COMPLETION_MASK) == CANCELLED;
+        return status == CANCELLED;
     }
 
     /**
@@ -770,7 +598,7 @@
      * @return {@code true} if this task threw an exception or was cancelled
      */
     public final boolean isCompletedAbnormally() {
-        return (status & COMPLETION_MASK) < NORMAL;
+        return status < NORMAL;
     }
 
     /**
@@ -781,7 +609,7 @@
      * exception and was not cancelled
      */
     public final boolean isCompletedNormally() {
-        return (status & COMPLETION_MASK) == NORMAL;
+        return status == NORMAL;
     }
 
     /**
@@ -792,7 +620,7 @@
      * @return the exception, or {@code null} if none
      */
     public final Throwable getException() {
-        int s = status & COMPLETION_MASK;
+        int s = status;
         return ((s >= NORMAL)    ? null :
                 (s == CANCELLED) ? new CancellationException() :
                 exceptionMap.get(this));
@@ -813,20 +641,21 @@
      * thrown will be a {@code RuntimeException} with cause {@code ex}.
      */
     public void completeExceptionally(Throwable ex) {
-        setDoneExceptionally((ex instanceof RuntimeException) ||
-                             (ex instanceof Error) ? ex :
-                             new RuntimeException(ex));
+        setExceptionalCompletion((ex instanceof RuntimeException) ||
+                                 (ex instanceof Error) ? ex :
+                                 new RuntimeException(ex));
     }
 
     /**
      * Completes this task, and if not already aborted or cancelled,
-     * returning a {@code null} result upon {@code join} and related
-     * operations. This method may be used to provide results for
-     * asynchronous tasks, or to provide alternative handling for
-     * tasks that would not otherwise complete normally. Its use in
-     * other situations is discouraged. This method is
-     * overridable, but overridden versions must invoke {@code super}
-     * implementation to maintain guarantees.
+     * returning the given value as the result of subsequent
+     * invocations of {@code join} and related operations. This method
+     * may be used to provide results for asynchronous tasks, or to
+     * provide alternative handling for tasks that would not otherwise
+     * complete normally. Its use in other situations is
+     * discouraged. This method is overridable, but overridden
+     * versions must invoke {@code super} implementation to maintain
+     * guarantees.
      *
      * @param value the result value for this task
      */
@@ -834,97 +663,151 @@
         try {
             setRawResult(value);
         } catch (Throwable rex) {
-            setDoneExceptionally(rex);
+            setExceptionalCompletion(rex);
             return;
         }
-        setNormalCompletion();
+        setCompletion(NORMAL);
     }
 
     public final V get() throws InterruptedException, ExecutionException {
-        ForkJoinWorkerThread w = getWorker();
-        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
-            awaitDone(w, true);
-        return reportFutureResult();
+        quietlyJoin();
+        if (Thread.interrupted())
+            throw new InterruptedException();
+        int s = status;
+        if (s < NORMAL) {
+            Throwable ex;
+            if (s == CANCELLED)
+                throw new CancellationException();
+            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
+                throw new ExecutionException(ex);
+        }
+        return getRawResult();
     }
 
     public final V get(long timeout, TimeUnit unit)
         throws InterruptedException, ExecutionException, TimeoutException {
+        Thread t = Thread.currentThread();
+        ForkJoinPool pool;
+        if (t instanceof ForkJoinWorkerThread) {
+            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
+            if (status >= 0 && w.unpushTask(this))
+                quietlyExec();
+            pool = w.pool;
+        }
+        else
+            pool = null;
+        /*
+         * Timed wait loop intermixes cases for FJ (pool != null) and
+         * non FJ threads. For FJ, decrement pool count but don't try
+         * for replacement; increment count on completion. For non-FJ,
+         * deal with interrupts. This is messy, but a little less so
+         * than is splitting the FJ and nonFJ cases.
+         */
+        boolean interrupted = false;
+        boolean dec = false; // true if pool count decremented
         long nanos = unit.toNanos(timeout);
-        ForkJoinWorkerThread w = getWorker();
-        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
-            awaitDone(w, nanos);
-        return reportTimedFutureResult();
-    }
-
-    /**
-     * Possibly executes other tasks until this task {@link #isDone is
-     * done}, then returns the result of the computation.  This method
-     * may be more efficient than {@code join}, but is only applicable
-     * when there are no potential dependencies between continuation
-     * of the current task and that of any other task that might be
-     * executed while helping. (This usually holds for pure
-     * divide-and-conquer tasks).
-     *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinTask} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     *
-     * @return the computed result
-     */
-    public final V helpJoin() {
-        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
-        if (status < 0 || !w.unpushTask(this) || !tryExec())
-            reportException(busyJoin(w));
+        for (;;) {
+            if (pool == null && Thread.interrupted()) {
+                interrupted = true;
+                break;
+            }
+            int s = status;
+            if (s < 0)
+                break;
+            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
+                long startTime = System.nanoTime();
+                long nt; // wait time
+                while (status >= 0 &&
+                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
+                    if (pool != null && !dec)
+                        dec = pool.tryDecrementRunningCount();
+                    else {
+                        long ms = nt / 1000000;
+                        int ns = (int) (nt % 1000000);
+                        try {
+                            synchronized(this) {
+                                if (status >= 0)
+                                    wait(ms, ns);
+                            }
+                        } catch (InterruptedException ie) {
+                            if (pool != null)
+                                cancelIfTerminating();
+                            else {
+                                interrupted = true;
+                                break;
+                            }
+                        }
+                    }
+                }
+                break;
+            }
+        }
+        if (pool != null && dec)
+            pool.incrementRunningCount();
+        if (interrupted)
+            throw new InterruptedException();
+        int es = status;
+        if (es != NORMAL) {
+            Throwable ex;
+            if (es == CANCELLED)
+                throw new CancellationException();
+            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
+                throw new ExecutionException(ex);
+            throw new TimeoutException();
+        }
         return getRawResult();
     }
 
     /**
-     * Possibly executes other tasks until this task {@link #isDone is
-     * done}.  This method may be useful when processing collections
-     * of tasks when some have been cancelled or otherwise known to
-     * have aborted.
-     *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinTask} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     */
-    public final void quietlyHelpJoin() {
-        if (status >= 0) {
-            ForkJoinWorkerThread w =
-                (ForkJoinWorkerThread) Thread.currentThread();
-            if (!w.unpushTask(this) || !tryQuietlyInvoke())
-                busyJoin(w);
-        }
-    }
-
-    /**
-     * Joins this task, without returning its result or throwing an
+     * Joins this task, without returning its result or throwing its
      * exception. This method may be useful when processing
      * collections of tasks when some have been cancelled or otherwise
      * known to have aborted.
      */
     public final void quietlyJoin() {
-        if (status >= 0) {
-            ForkJoinWorkerThread w = getWorker();
-            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
-                awaitDone(w, true);
+        Thread t;
+        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
+            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
+            if (status >= 0) {
+                if (w.unpushTask(this)) {
+                    boolean completed;
+                    try {
+                        completed = exec();
+                    } catch (Throwable rex) {
+                        setExceptionalCompletion(rex);
+                        return;
+                    }
+                    if (completed) {
+                        setCompletion(NORMAL);
+                        return;
+                    }
+                }
+                w.joinTask(this);
+            }
         }
+        else
+            externalAwaitDone();
     }
 
     /**
      * Commences performing this task and awaits its completion if
-     * necessary, without returning its result or throwing an
-     * exception. This method may be useful when processing
-     * collections of tasks when some have been cancelled or otherwise
-     * known to have aborted.
+     * necessary, without returning its result or throwing its
+     * exception.
      */
     public final void quietlyInvoke() {
-        if (status >= 0 && !tryQuietlyInvoke())
-            quietlyJoin();
+        if (status >= 0) {
+            boolean completed;
+            try {
+                completed = exec();
+            } catch (Throwable rex) {
+                setExceptionalCompletion(rex);
+                return;
+            }
+            if (completed)
+                setCompletion(NORMAL);
+            else
+                quietlyJoin();
+        }
     }
 
     /**
@@ -956,7 +839,7 @@
      * pre-constructed trees of subtasks in loops.
      */
     public void reinitialize() {
-        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
+        if (status == EXCEPTIONAL)
             exceptionMap.remove(this);
         status = 0;
     }
@@ -1246,7 +1129,7 @@
     private static final long serialVersionUID = -7721805057305804111L;
 
     /**
-     * Saves the state to a stream.
+     * Saves the state to a stream (that is, serializes it).
      *
      * @serialData the current run status and the exception thrown
      * during execution, or {@code null} if none
@@ -1259,18 +1142,16 @@
     }
 
     /**
-     * Reconstitutes the instance from a stream.
+     * Reconstitutes the instance from a stream (that is, deserializes it).
      *
      * @param s the stream
      */
     private void readObject(java.io.ObjectInputStream s)
         throws java.io.IOException, ClassNotFoundException {
         s.defaultReadObject();
-        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
-        status |= EXTERNAL_SIGNAL; // conservatively set external signal
         Object ex = s.readObject();
         if (ex != null)
-            setDoneExceptionally((Throwable) ex);
+            setExceptionalCompletion((Throwable) ex);
     }
 
     // Unsafe mechanics
--- a/src/share/classes/java/util/concurrent/ForkJoinWorkerThread.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/concurrent/ForkJoinWorkerThread.java	Fri Sep 24 16:41:32 2010 -0700
@@ -35,7 +35,9 @@
 
 package java.util.concurrent;
 
+import java.util.Random;
 import java.util.Collection;
+import java.util.concurrent.locks.LockSupport;
 
 /**
  * A thread managed by a {@link ForkJoinPool}.  This class is
@@ -52,46 +54,55 @@
  */
 public class ForkJoinWorkerThread extends Thread {
     /*
-     * Algorithm overview:
+     * Overview:
+     *
+     * ForkJoinWorkerThreads are managed by ForkJoinPools and perform
+     * ForkJoinTasks. This class includes bookkeeping in support of
+     * worker activation, suspension, and lifecycle control described
+     * in more detail in the internal documentation of class
+     * ForkJoinPool. And as described further below, this class also
+     * includes special-cased support for some ForkJoinTask
+     * methods. But the main mechanics involve work-stealing:
      *
-     * 1. Work-Stealing: Work-stealing queues are special forms of
-     * Deques that support only three of the four possible
-     * end-operations -- push, pop, and deq (aka steal), and only do
-     * so under the constraints that push and pop are called only from
-     * the owning thread, while deq may be called from other threads.
-     * (If you are unfamiliar with them, you probably want to read
-     * Herlihy and Shavit's book "The Art of Multiprocessor
-     * programming", chapter 16 describing these in more detail before
-     * proceeding.)  The main work-stealing queue design is roughly
-     * similar to "Dynamic Circular Work-Stealing Deque" by David
-     * Chase and Yossi Lev, SPAA 2005
-     * (http://research.sun.com/scalable/pubs/index.html).  The main
-     * difference ultimately stems from gc requirements that we null
-     * out taken slots as soon as we can, to maintain as small a
-     * footprint as possible even in programs generating huge numbers
-     * of tasks. To accomplish this, we shift the CAS arbitrating pop
-     * vs deq (steal) from being on the indices ("base" and "sp") to
-     * the slots themselves (mainly via method "casSlotNull()"). So,
-     * both a successful pop and deq mainly entail CAS'ing a non-null
-     * slot to null.  Because we rely on CASes of references, we do
-     * not need tag bits on base or sp.  They are simple ints as used
-     * in any circular array-based queue (see for example ArrayDeque).
-     * Updates to the indices must still be ordered in a way that
-     * guarantees that (sp - base) > 0 means the queue is empty, but
-     * otherwise may err on the side of possibly making the queue
-     * appear nonempty when a push, pop, or deq have not fully
-     * committed. Note that this means that the deq operation,
-     * considered individually, is not wait-free. One thief cannot
-     * successfully continue until another in-progress one (or, if
-     * previously empty, a push) completes.  However, in the
-     * aggregate, we ensure at least probabilistic
-     * non-blockingness. If an attempted steal fails, a thief always
-     * chooses a different random victim target to try next. So, in
-     * order for one thief to progress, it suffices for any
-     * in-progress deq or new push on any empty queue to complete. One
-     * reason this works well here is that apparently-nonempty often
-     * means soon-to-be-stealable, which gives threads a chance to
-     * activate if necessary before stealing (see below).
+     * Work-stealing queues are special forms of Deques that support
+     * only three of the four possible end-operations -- push, pop,
+     * and deq (aka steal), under the further constraints that push
+     * and pop are called only from the owning thread, while deq may
+     * be called from other threads.  (If you are unfamiliar with
+     * them, you probably want to read Herlihy and Shavit's book "The
+     * Art of Multiprocessor programming", chapter 16 describing these
+     * in more detail before proceeding.)  The main work-stealing
+     * queue design is roughly similar to those in the papers "Dynamic
+     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
+     * (http://research.sun.com/scalable/pubs/index.html) and
+     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
+     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
+     * The main differences ultimately stem from gc requirements that
+     * we null out taken slots as soon as we can, to maintain as small
+     * a footprint as possible even in programs generating huge
+     * numbers of tasks. To accomplish this, we shift the CAS
+     * arbitrating pop vs deq (steal) from being on the indices
+     * ("base" and "sp") to the slots themselves (mainly via method
+     * "casSlotNull()"). So, both a successful pop and deq mainly
+     * entail a CAS of a slot from non-null to null.  Because we rely
+     * on CASes of references, we do not need tag bits on base or sp.
+     * They are simple ints as used in any circular array-based queue
+     * (see for example ArrayDeque).  Updates to the indices must
+     * still be ordered in a way that guarantees that sp == base means
+     * the queue is empty, but otherwise may err on the side of
+     * possibly making the queue appear nonempty when a push, pop, or
+     * deq have not fully committed. Note that this means that the deq
+     * operation, considered individually, is not wait-free. One thief
+     * cannot successfully continue until another in-progress one (or,
+     * if previously empty, a push) completes.  However, in the
+     * aggregate, we ensure at least probabilistic non-blockingness.
+     * If an attempted steal fails, a thief always chooses a different
+     * random victim target to try next. So, in order for one thief to
+     * progress, it suffices for any in-progress deq or new push on
+     * any empty queue to complete. One reason this works well here is
+     * that apparently-nonempty often means soon-to-be-stealable,
+     * which gives threads a chance to set activation status if
+     * necessary before stealing.
      *
      * This approach also enables support for "async mode" where local
      * task processing is in FIFO, not LIFO order; simply by using a
@@ -99,24 +110,54 @@
      * by the ForkJoinPool).  This allows use in message-passing
      * frameworks in which tasks are never joined.
      *
-     * Efficient implementation of this approach currently relies on
-     * an uncomfortable amount of "Unsafe" mechanics. To maintain
+     * When a worker would otherwise be blocked waiting to join a
+     * task, it first tries a form of linear helping: Each worker
+     * records (in field currentSteal) the most recent task it stole
+     * from some other worker. Plus, it records (in field currentJoin)
+     * the task it is currently actively joining. Method joinTask uses
+     * these markers to try to find a worker to help (i.e., steal back
+     * a task from and execute it) that could hasten completion of the
+     * actively joined task. In essence, the joiner executes a task
+     * that would be on its own local deque had the to-be-joined task
+     * not been stolen. This may be seen as a conservative variant of
+     * the approach in Wagner & Calder "Leapfrogging: a portable
+     * technique for implementing efficient futures" SIGPLAN Notices,
+     * 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs
+     * in that: (1) We only maintain dependency links across workers
+     * upon steals, rather than use per-task bookkeeping.  This may
+     * require a linear scan of workers array to locate stealers, but
+     * usually doesn't because stealers leave hints (that may become
+     * stale/wrong) of where to locate them. This isolates cost to
+     * when it is needed, rather than adding to per-task overhead.
+     * (2) It is "shallow", ignoring nesting and potentially cyclic
+     * mutual steals.  (3) It is intentionally racy: field currentJoin
+     * is updated only while actively joining, which means that we
+     * miss links in the chain during long-lived tasks, GC stalls etc
+     * (which is OK since blocking in such cases is usually a good
+     * idea).  (4) We bound the number of attempts to find work (see
+     * MAX_HELP_DEPTH) and fall back to suspending the worker and if
+     * necessary replacing it with a spare (see
+     * ForkJoinPool.awaitJoin).
+     *
+     * Efficient implementation of these algorithms currently relies
+     * on an uncomfortable amount of "Unsafe" mechanics. To maintain
      * correct orderings, reads and writes of variable base require
-     * volatile ordering.  Variable sp does not require volatile write
-     * but needs cheaper store-ordering on writes.  Because they are
-     * protected by volatile base reads, reads of the queue array and
-     * its slots do not need volatile load semantics, but writes (in
-     * push) require store order and CASes (in pop and deq) require
-     * (volatile) CAS semantics.  (See "Idempotent work stealing" by
-     * Michael, Saraswat, and Vechev, PPoPP 2009
-     * http://portal.acm.org/citation.cfm?id=1504186 for an algorithm
-     * with similar properties, but without support for nulling
-     * slots.)  Since these combinations aren't supported using
-     * ordinary volatiles, the only way to accomplish these
-     * efficiently is to use direct Unsafe calls. (Using external
-     * AtomicIntegers and AtomicReferenceArrays for the indices and
-     * array is significantly slower because of memory locality and
-     * indirection effects.)
+     * volatile ordering.  Variable sp does not require volatile
+     * writes but still needs store-ordering, which we accomplish by
+     * pre-incrementing sp before filling the slot with an ordered
+     * store.  (Pre-incrementing also enables backouts used in
+     * joinTask.)  Because they are protected by volatile base reads,
+     * reads of the queue array and its slots by other threads do not
+     * need volatile load semantics, but writes (in push) require
+     * store order and CASes (in pop and deq) require (volatile) CAS
+     * semantics.  (Michael, Saraswat, and Vechev's algorithm has
+     * similar properties, but without support for nulling slots.)
+     * Since these combinations aren't supported using ordinary
+     * volatiles, the only way to accomplish these efficiently is to
+     * use direct Unsafe calls. (Using external AtomicIntegers and
+     * AtomicReferenceArrays for the indices and array is
+     * significantly slower because of memory locality and indirection
+     * effects.)
      *
      * Further, performance on most platforms is very sensitive to
      * placement and sizing of the (resizable) queue array.  Even
@@ -124,56 +165,45 @@
      * initial size must be large enough to counteract cache
      * contention effects across multiple queues (especially in the
      * presence of GC cardmarking). Also, to improve thread-locality,
-     * queues are currently initialized immediately after the thread
-     * gets the initial signal to start processing tasks.  However,
-     * all queue-related methods except pushTask are written in a way
-     * that allows them to instead be lazily allocated and/or disposed
-     * of when empty. All together, these low-level implementation
-     * choices produce as much as a factor of 4 performance
-     * improvement compared to naive implementations, and enable the
-     * processing of billions of tasks per second, sometimes at the
-     * expense of ugliness.
-     *
-     * 2. Run control: The primary run control is based on a global
-     * counter (activeCount) held by the pool. It uses an algorithm
-     * similar to that in Herlihy and Shavit section 17.6 to cause
-     * threads to eventually block when all threads declare they are
-     * inactive. For this to work, threads must be declared active
-     * when executing tasks, and before stealing a task. They must be
-     * inactive before blocking on the Pool Barrier (awaiting a new
-     * submission or other Pool event). In between, there is some free
-     * play which we take advantage of to avoid contention and rapid
-     * flickering of the global activeCount: If inactive, we activate
-     * only if a victim queue appears to be nonempty (see above).
-     * Similarly, a thread tries to inactivate only after a full scan
-     * of other threads.  The net effect is that contention on
-     * activeCount is rarely a measurable performance issue. (There
-     * are also a few other cases where we scan for work rather than
-     * retry/block upon contention.)
-     *
-     * 3. Selection control. We maintain policy of always choosing to
-     * run local tasks rather than stealing, and always trying to
-     * steal tasks before trying to run a new submission. All steals
-     * are currently performed in randomly-chosen deq-order. It may be
-     * worthwhile to bias these with locality / anti-locality
-     * information, but doing this well probably requires more
-     * lower-level information from JVMs than currently provided.
+     * queues are initialized after starting.  All together, these
+     * low-level implementation choices produce as much as a factor of
+     * 4 performance improvement compared to naive implementations,
+     * and enable the processing of billions of tasks per second,
+     * sometimes at the expense of ugliness.
      */
 
     /**
+     * Generator for initial random seeds for random victim
+     * selection. This is used only to create initial seeds. Random
+     * steals use a cheaper xorshift generator per steal attempt. We
+     * expect only rare contention on seedGenerator, so just use a
+     * plain Random.
+     */
+    private static final Random seedGenerator = new Random();
+
+    /**
+     * The maximum stolen->joining link depth allowed in helpJoinTask.
+     * Depths for legitimate chains are unbounded, but we use a fixed
+     * constant to avoid (otherwise unchecked) cycles and bound
+     * staleness of traversal parameters at the expense of sometimes
+     * blocking when we could be helping.
+     */
+    private static final int MAX_HELP_DEPTH = 8;
+
+    /**
      * Capacity of work-stealing queue array upon initialization.
-     * Must be a power of two. Initial size must be at least 2, but is
+     * Must be a power of two. Initial size must be at least 4, but is
      * padded to minimize cache effects.
      */
     private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
 
     /**
      * Maximum work-stealing queue array size.  Must be less than or
-     * equal to 1 << 28 to ensure lack of index wraparound. (This
-     * is less than usual bounds, because we need leftshift by 3
-     * to be in int range).
+     * equal to 1 << (31 - width of array entry) to ensure lack of
+     * index wraparound. The value is set in the static block
+     * at the end of this file after obtaining width.
      */
-    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
+    private static final int MAXIMUM_QUEUE_CAPACITY;
 
     /**
      * The pool this thread works in. Accessed directly by ForkJoinTask.
@@ -182,65 +212,118 @@
 
     /**
      * The work-stealing queue array. Size must be a power of two.
-     * Initialized when thread starts, to improve memory locality.
+     * Initialized in onStart, to improve memory locality.
      */
     private ForkJoinTask<?>[] queue;
 
     /**
-     * Index (mod queue.length) of next queue slot to push to or pop
-     * from. It is written only by owner thread, via ordered store.
-     * Both sp and base are allowed to wrap around on overflow, but
-     * (sp - base) still estimates size.
-     */
-    private volatile int sp;
-
-    /**
      * Index (mod queue.length) of least valid queue slot, which is
      * always the next position to steal from if nonempty.
      */
     private volatile int base;
 
     /**
-     * Activity status. When true, this worker is considered active.
-     * Must be false upon construction. It must be true when executing
-     * tasks, and BEFORE stealing a task. It must be false before
-     * calling pool.sync.
+     * Index (mod queue.length) of next queue slot to push to or pop
+     * from. It is written only by owner thread, and accessed by other
+     * threads only after reading (volatile) base.  Both sp and base
+     * are allowed to wrap around on overflow, but (sp - base) still
+     * estimates size.
      */
-    private boolean active;
+    private int sp;
+
+    /**
+     * The index of most recent stealer, used as a hint to avoid
+     * traversal in method helpJoinTask. This is only a hint because a
+     * worker might have had multiple steals and this only holds one
+     * of them (usually the most current). Declared non-volatile,
+     * relying on other prevailing sync to keep reasonably current.
+     */
+    private int stealHint;
 
     /**
-     * Run state of this worker. Supports simple versions of the usual
-     * shutdown/shutdownNow control.
+     * Run state of this worker. In addition to the usual run levels,
+     * tracks if this worker is suspended as a spare, and if it was
+     * killed (trimmed) while suspended. However, "active" status is
+     * maintained separately and modified only in conjunction with
+     * CASes of the pool's runState (which are currently sadly
+     * manually inlined for performance.)  Accessed directly by pool
+     * to simplify checks for normal (zero) status.
      */
-    private volatile int runState;
+    volatile int runState;
+
+    private static final int TERMINATING = 0x01;
+    private static final int TERMINATED  = 0x02;
+    private static final int SUSPENDED   = 0x04; // inactive spare
+    private static final int TRIMMED     = 0x08; // killed while suspended
+
+    /**
+     * Number of steals. Directly accessed (and reset) by
+     * pool.tryAccumulateStealCount when idle.
+     */
+    int stealCount;
 
     /**
      * Seed for random number generator for choosing steal victims.
-     * Uses Marsaglia xorshift. Must be nonzero upon initialization.
+     * Uses Marsaglia xorshift. Must be initialized as nonzero.
      */
     private int seed;
 
     /**
-     * Number of steals, transferred to pool when idle
+     * Activity status. When true, this worker is considered active.
+     * Accessed directly by pool.  Must be false upon construction.
      */
-    private int stealCount;
+    boolean active;
+
+    /**
+     * True if use local fifo, not default lifo, for local polling.
+     * Shadows value from ForkJoinPool.
+     */
+    private final boolean locallyFifo;
 
     /**
      * Index of this worker in pool array. Set once by pool before
-     * running, and accessed directly by pool during cleanup etc.
+     * running, and accessed directly by pool to locate this worker in
+     * its workers array.
      */
     int poolIndex;
 
     /**
-     * The last barrier event waited for. Accessed in pool callback
-     * methods, but only by current thread.
+     * The last pool event waited for. Accessed only by pool in
+     * callback methods invoked within this thread.
      */
-    long lastEventCount;
+    int lastEventCount;
+
+    /**
+     * Encoded index and event count of next event waiter. Accessed
+     * only by ForkJoinPool for managing event waiters.
+     */
+    volatile long nextWaiter;
+
+    /**
+     * Number of times this thread suspended as spare. Accessed only
+     * by pool.
+     */
+    int spareCount;
 
     /**
-     * True if use local fifo, not default lifo, for local polling
+     * Encoded index and count of next spare waiter. Accessed only
+     * by ForkJoinPool for managing spares.
      */
-    private boolean locallyFifo;
+    volatile int nextSpare;
+
+    /**
+     * The task currently being joined, set only when actively trying
+     * to help other stealers in helpJoinTask. Written only by this
+     * thread, but read by others.
+     */
+    private volatile ForkJoinTask<?> currentJoin;
+
+    /**
+     * The task most recently stolen from another worker (or
+     * submission queue).  Written only by this thread, but read by
+     * others.
+     */
+    private volatile ForkJoinTask<?> currentSteal;
 
     /**
      * Creates a ForkJoinWorkerThread operating in the given pool.
@@ -249,13 +332,24 @@
      * @throws NullPointerException if pool is null
      */
     protected ForkJoinWorkerThread(ForkJoinPool pool) {
-        if (pool == null) throw new NullPointerException();
         this.pool = pool;
-        // Note: poolIndex is set by pool during construction
-        // Remaining initialization is deferred to onStart
+        this.locallyFifo = pool.locallyFifo;
+        setDaemon(true);
+        // To avoid exposing construction details to subclasses,
+        // remaining initialization is in start() and onStart()
     }
 
-    // Public access methods
+    /**
+     * Performs additional initialization and starts this thread.
+     */
+    final void start(int poolIndex, UncaughtExceptionHandler ueh) {
+        this.poolIndex = poolIndex;
+        if (ueh != null)
+            setUncaughtExceptionHandler(ueh);
+        start();
+    }
+
+    // Public/protected methods
 
     /**
      * Returns the pool hosting this thread.
@@ -280,129 +374,24 @@
     }
 
     /**
-     * Establishes local first-in-first-out scheduling mode for forked
-     * tasks that are never joined.
-     *
-     * @param async if true, use locally FIFO scheduling
-     */
-    void setAsyncMode(boolean async) {
-        locallyFifo = async;
-    }
-
-    // Runstate management
-
-    // Runstate values. Order matters
-    private static final int RUNNING     = 0;
-    private static final int SHUTDOWN    = 1;
-    private static final int TERMINATING = 2;
-    private static final int TERMINATED  = 3;
-
-    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
-    final boolean isTerminating() { return runState >= TERMINATING;  }
-    final boolean isTerminated()  { return runState == TERMINATED; }
-    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
-    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
-
-    /**
-     * Transitions to at least the given state.
-     *
-     * @return {@code true} if not already at least at given state
-     */
-    private boolean transitionRunStateTo(int state) {
-        for (;;) {
-            int s = runState;
-            if (s >= state)
-                return false;
-            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, state))
-                return true;
-        }
-    }
-
-    /**
-     * Tries to set status to active; fails on contention.
-     */
-    private boolean tryActivate() {
-        if (!active) {
-            if (!pool.tryIncrementActiveCount())
-                return false;
-            active = true;
-        }
-        return true;
-    }
-
-    /**
-     * Tries to set status to inactive; fails on contention.
-     */
-    private boolean tryInactivate() {
-        if (active) {
-            if (!pool.tryDecrementActiveCount())
-                return false;
-            active = false;
-        }
-        return true;
-    }
-
-    /**
-     * Computes next value for random victim probe.  Scans don't
-     * require a very high quality generator, but also not a crummy
-     * one.  Marsaglia xor-shift is cheap and works well.
-     */
-    private static int xorShift(int r) {
-        r ^= (r << 13);
-        r ^= (r >>> 17);
-        return r ^ (r << 5);
-    }
-
-    // Lifecycle methods
-
-    /**
-     * This method is required to be public, but should never be
-     * called explicitly. It performs the main run loop to execute
-     * ForkJoinTasks.
-     */
-    public void run() {
-        Throwable exception = null;
-        try {
-            onStart();
-            pool.sync(this); // await first pool event
-            mainLoop();
-        } catch (Throwable ex) {
-            exception = ex;
-        } finally {
-            onTermination(exception);
-        }
-    }
-
-    /**
-     * Executes tasks until shut down.
-     */
-    private void mainLoop() {
-        while (!isShutdown()) {
-            ForkJoinTask<?> t = pollTask();
-            if (t != null || (t = pollSubmission()) != null)
-                t.quietlyExec();
-            else if (tryInactivate())
-                pool.sync(this);
-        }
-    }
-
-    /**
      * Initializes internal state after construction but before
      * processing any tasks. If you override this method, you must
-     * invoke super.onStart() at the beginning of the method.
+     * invoke @code{super.onStart()} at the beginning of the method.
      * Initialization requires care: Most fields must have legal
      * default values, to ensure that attempted accesses from other
      * threads work correctly even before this thread starts
      * processing tasks.
      */
     protected void onStart() {
-        // Allocate while starting to improve chances of thread-local
-        // isolation
+        int rs = seedGenerator.nextInt();
+        seed = rs == 0? 1 : rs; // seed must be nonzero
+
+        // Allocate name string and arrays in this thread
+        String pid = Integer.toString(pool.getPoolNumber());
+        String wid = Integer.toString(poolIndex);
+        setName("ForkJoinPool-" + pid + "-worker-" + wid);
+
         queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
-        // Initial value of seed need not be especially random but
-        // should differ across workers and must be nonzero
-        int p = poolIndex + 1;
-        seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits
     }
 
     /**
@@ -414,97 +403,187 @@
      * to an unrecoverable error, or {@code null} if completed normally
      */
     protected void onTermination(Throwable exception) {
-        // Execute remaining local tasks unless aborting or terminating
-        while (exception == null && pool.isProcessingTasks() && base != sp) {
-            try {
-                ForkJoinTask<?> t = popTask();
-                if (t != null)
-                    t.quietlyExec();
-            } catch (Throwable ex) {
-                exception = ex;
+        try {
+            ForkJoinPool p = pool;
+            if (active) {
+                int a; // inline p.tryDecrementActiveCount
+                active = false;
+                do {} while (!UNSAFE.compareAndSwapInt
+                             (p, poolRunStateOffset, a = p.runState, a - 1));
             }
-        }
-        // Cancel other tasks, transition status, notify pool, and
-        // propagate exception to uncaught exception handler
-        try {
-            do {} while (!tryInactivate()); // ensure inactive
             cancelTasks();
-            runState = TERMINATED;
-            pool.workerTerminated(this);
+            setTerminated();
+            p.workerTerminated(this);
         } catch (Throwable ex) {        // Shouldn't ever happen
             if (exception == null)      // but if so, at least rethrown
                 exception = ex;
         } finally {
             if (exception != null)
-                ForkJoinTask.rethrowException(exception);
+                UNSAFE.throwException(exception);
+        }
+    }
+
+    /**
+     * This method is required to be public, but should never be
+     * called explicitly. It performs the main run loop to execute
+     * ForkJoinTasks.
+     */
+    public void run() {
+        Throwable exception = null;
+        try {
+            onStart();
+            mainLoop();
+        } catch (Throwable ex) {
+            exception = ex;
+        } finally {
+            onTermination(exception);
         }
     }
 
-    // Intrinsics-based support for queue operations.
+    // helpers for run()
 
-    private static long slotOffset(int i) {
-        return ((long) i << qShift) + qBase;
+    /**
+     * Finds and executes tasks, and checks status while running.
+     */
+    private void mainLoop() {
+        boolean ran = false; // true if ran a task on last step
+        ForkJoinPool p = pool;
+        for (;;) {
+            p.preStep(this, ran);
+            if (runState != 0)
+                break;
+            ran = tryExecSteal() || tryExecSubmission();
+        }
     }
 
     /**
-     * Adds in store-order the given task at given slot of q to null.
-     * Caller must ensure q is non-null and index is in range.
+     * Tries to steal a task and execute it.
+     *
+     * @return true if ran a task
      */
-    private static void setSlot(ForkJoinTask<?>[] q, int i,
-                                ForkJoinTask<?> t) {
-        UNSAFE.putOrderedObject(q, slotOffset(i), t);
+    private boolean tryExecSteal() {
+        ForkJoinTask<?> t;
+        if ((t = scan()) != null) {
+            t.quietlyExec();
+            UNSAFE.putOrderedObject(this, currentStealOffset, null);
+            if (sp != base)
+                execLocalTasks();
+            return true;
+        }
+        return false;
     }
 
     /**
-     * CAS given slot of q to null. Caller must ensure q is non-null
-     * and index is in range.
+     * If a submission exists, try to activate and run it.
+     *
+     * @return true if ran a task
      */
-    private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
-                                       ForkJoinTask<?> t) {
-        return UNSAFE.compareAndSwapObject(q, slotOffset(i), t, null);
+    private boolean tryExecSubmission() {
+        ForkJoinPool p = pool;
+        // This loop is needed in case attempt to activate fails, in
+        // which case we only retry if there still appears to be a
+        // submission.
+        while (p.hasQueuedSubmissions()) {
+            ForkJoinTask<?> t; int a;
+            if (active || // inline p.tryIncrementActiveCount
+                (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
+                                                   a = p.runState, a + 1))) {
+                if ((t = p.pollSubmission()) != null) {
+                    UNSAFE.putOrderedObject(this, currentStealOffset, t);
+                    t.quietlyExec();
+                    UNSAFE.putOrderedObject(this, currentStealOffset, null);
+                    if (sp != base)
+                        execLocalTasks();
+                    return true;
+                }
+            }
+        }
+        return false;
     }
 
     /**
-     * Sets sp in store-order.
+     * Runs local tasks until queue is empty or shut down.  Call only
+     * while active.
      */
-    private void storeSp(int s) {
-        UNSAFE.putOrderedInt(this, spOffset, s);
+    private void execLocalTasks() {
+        while (runState == 0) {
+            ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask();
+            if (t != null)
+                t.quietlyExec();
+            else if (sp == base)
+                break;
+        }
     }
 
-    // Main queue methods
+    /*
+     * Intrinsics-based atomic writes for queue slots. These are
+     * basically the same as methods in AtomicReferenceArray, but
+     * specialized for (1) ForkJoinTask elements (2) requirement that
+     * nullness and bounds checks have already been performed by
+     * callers and (3) effective offsets are known not to overflow
+     * from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't
+     * need corresponding version for reads: plain array reads are OK
+     * because they are protected by other volatile reads and are
+     * confirmed by CASes.
+     *
+     * Most uses don't actually call these methods, but instead contain
+     * inlined forms that enable more predictable optimization.  We
+     * don't define the version of write used in pushTask at all, but
+     * instead inline there a store-fenced array slot write.
+     */
 
     /**
-     * Pushes a task. Called only by current thread.
+     * CASes slot i of array q from t to null. Caller must ensure q is
+     * non-null and index is in range.
+     */
+    private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i,
+                                             ForkJoinTask<?> t) {
+        return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
+    }
+
+    /**
+     * Performs a volatile write of the given task at given slot of
+     * array q.  Caller must ensure q is non-null and index is in
+     * range. This method is used only during resets and backouts.
+     */
+    private static final void writeSlot(ForkJoinTask<?>[] q, int i,
+                                        ForkJoinTask<?> t) {
+        UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t);
+    }
+
+    // queue methods
+
+    /**
+     * Pushes a task. Call only from this thread.
      *
      * @param t the task. Caller must ensure non-null.
      */
     final void pushTask(ForkJoinTask<?> t) {
         ForkJoinTask<?>[] q = queue;
-        int mask = q.length - 1;
-        int s = sp;
-        setSlot(q, s & mask, t);
-        storeSp(++s);
-        if ((s -= base) == 1)
-            pool.signalWork();
-        else if (s >= mask)
-            growQueue();
+        int mask = q.length - 1; // implicit assert q != null
+        int s = sp++;            // ok to increment sp before slot write
+        UNSAFE.putOrderedObject(q, ((s & mask) << qShift) + qBase, t);
+        if ((s -= base) == 0)
+            pool.signalWork();   // was empty
+        else if (s == mask)
+            growQueue();         // is full
     }
 
     /**
      * Tries to take a task from the base of the queue, failing if
-     * either empty or contended.
+     * empty or contended. Note: Specializations of this code appear
+     * in locallyDeqTask and elsewhere.
      *
      * @return a task, or null if none or contended
      */
     final ForkJoinTask<?> deqTask() {
         ForkJoinTask<?> t;
         ForkJoinTask<?>[] q;
-        int i;
-        int b;
+        int b, i;
         if (sp != (b = base) &&
             (q = queue) != null && // must read q after b
-            (t = q[i = (q.length - 1) & b]) != null &&
-            casSlotNull(q, i, t)) {
+            (t = q[i = (q.length - 1) & b]) != null && base == b &&
+            UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
             base = b + 1;
             return t;
         }
@@ -512,19 +591,20 @@
     }
 
     /**
-     * Tries to take a task from the base of own queue, activating if
-     * necessary, failing only if empty. Called only by current thread.
+     * Tries to take a task from the base of own queue. Assumes active
+     * status.  Called only by this thread.
      *
      * @return a task, or null if none
      */
     final ForkJoinTask<?> locallyDeqTask() {
-        int b;
-        while (sp != (b = base)) {
-            if (tryActivate()) {
-                ForkJoinTask<?>[] q = queue;
-                int i = (q.length - 1) & b;
-                ForkJoinTask<?> t = q[i];
-                if (t != null && casSlotNull(q, i, t)) {
+        ForkJoinTask<?>[] q = queue;
+        if (q != null) {
+            ForkJoinTask<?> t;
+            int b, i;
+            while (sp != (b = base)) {
+                if ((t = q[i = (q.length - 1) & b]) != null && base == b &&
+                    UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase,
+                                                t, null)) {
                     base = b + 1;
                     return t;
                 }
@@ -534,46 +614,50 @@
     }
 
     /**
-     * Returns a popped task, or null if empty. Ensures active status
-     * if non-null. Called only by current thread.
+     * Returns a popped task, or null if empty. Assumes active status.
+     * Called only by this thread.
      */
-    final ForkJoinTask<?> popTask() {
-        int s = sp;
-        while (s != base) {
-            if (tryActivate()) {
-                ForkJoinTask<?>[] q = queue;
-                int mask = q.length - 1;
-                int i = (s - 1) & mask;
+    private ForkJoinTask<?> popTask() {
+        ForkJoinTask<?>[] q = queue;
+        if (q != null) {
+            int s;
+            while ((s = sp) != base) {
+                int i = (q.length - 1) & --s;
+                long u = (i << qShift) + qBase; // raw offset
                 ForkJoinTask<?> t = q[i];
-                if (t == null || !casSlotNull(q, i, t))
+                if (t == null)   // lost to stealer
                     break;
-                storeSp(s - 1);
-                return t;
+                if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
+                    sp = s; // putOrderedInt may encourage more timely write
+                    // UNSAFE.putOrderedInt(this, spOffset, s);
+                    return t;
+                }
             }
         }
         return null;
     }
 
     /**
-     * Specialized version of popTask to pop only if
-     * topmost element is the given task. Called only
-     * by current thread while active.
+     * Specialized version of popTask to pop only if topmost element
+     * is the given task. Called only by this thread while active.
      *
      * @param t the task. Caller must ensure non-null.
      */
     final boolean unpushTask(ForkJoinTask<?> t) {
+        int s;
         ForkJoinTask<?>[] q = queue;
-        int mask = q.length - 1;
-        int s = sp - 1;
-        if (casSlotNull(q, s & mask, t)) {
-            storeSp(s);
+        if ((s = sp) != base && q != null &&
+            UNSAFE.compareAndSwapObject
+            (q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) {
+            sp = s; // putOrderedInt may encourage more timely write
+            // UNSAFE.putOrderedInt(this, spOffset, s);
             return true;
         }
         return false;
     }
 
     /**
-     * Returns next task or null if empty or contended
+     * Returns next task, or null if empty or contended.
      */
     final ForkJoinTask<?> peekTask() {
         ForkJoinTask<?>[] q = queue;
@@ -606,104 +690,209 @@
             ForkJoinTask<?> t = oldQ[oldIndex];
             if (t != null && !casSlotNull(oldQ, oldIndex, t))
                 t = null;
-            setSlot(newQ, b & newMask, t);
+            writeSlot(newQ, b & newMask, t);
         } while (++b != bf);
         pool.signalWork();
     }
 
     /**
+     * Computes next value for random victim probe in scan().  Scans
+     * don't require a very high quality generator, but also not a
+     * crummy one.  Marsaglia xor-shift is cheap and works well enough.
+     * Note: This is manually inlined in scan().
+     */
+    private static final int xorShift(int r) {
+        r ^= r << 13;
+        r ^= r >>> 17;
+        return r ^ (r << 5);
+    }
+
+    /**
      * Tries to steal a task from another worker. Starts at a random
      * index of workers array, and probes workers until finding one
      * with non-empty queue or finding that all are empty.  It
      * randomly selects the first n probes. If these are empty, it
-     * resorts to a full circular traversal, which is necessary to
-     * accurately set active status by caller. Also restarts if pool
-     * events occurred since last scan, which forces refresh of
-     * workers array, in case barrier was associated with resize.
+     * resorts to a circular sweep, which is necessary to accurately
+     * set active status. (The circular sweep uses steps of
+     * approximately half the array size plus 1, to avoid bias
+     * stemming from leftmost packing of the array in ForkJoinPool.)
      *
      * This method must be both fast and quiet -- usually avoiding
      * memory accesses that could disrupt cache sharing etc other than
-     * those needed to check for and take tasks. This accounts for,
-     * among other things, updating random seed in place without
-     * storing it until exit.
+     * those needed to check for and take tasks (or to activate if not
+     * already active). This accounts for, among other things,
+     * updating random seed in place without storing it until exit.
      *
      * @return a task, or null if none found
      */
     private ForkJoinTask<?> scan() {
-        ForkJoinTask<?> t = null;
-        int r = seed;                    // extract once to keep scan quiet
-        ForkJoinWorkerThread[] ws;       // refreshed on outer loop
-        int mask;                        // must be power 2 minus 1 and > 0
-        outer:do {
-            if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) {
-                int idx = r;
-                int probes = ~mask;      // use random index while negative
-                for (;;) {
-                    r = xorShift(r);     // update random seed
-                    ForkJoinWorkerThread v = ws[mask & idx];
-                    if (v == null || v.sp == v.base) {
-                        if (probes <= mask)
-                            idx = (probes++ < 0) ? r : (idx + 1);
-                        else
-                            break;
+        ForkJoinPool p = pool;
+        ForkJoinWorkerThread[] ws;        // worker array
+        int n;                            // upper bound of #workers
+        if ((ws = p.workers) != null && (n = ws.length) > 1) {
+            boolean canSteal = active;    // shadow active status
+            int r = seed;                 // extract seed once
+            int mask = n - 1;
+            int j = -n;                   // loop counter
+            int k = r;                    // worker index, random if j < 0
+            for (;;) {
+                ForkJoinWorkerThread v = ws[k & mask];
+                r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift
+                ForkJoinTask<?>[] q; ForkJoinTask<?> t; int b, a;
+                if (v != null && (b = v.base) != v.sp &&
+                    (q = v.queue) != null) {
+                    int i = (q.length - 1) & b;
+                    long u = (i << qShift) + qBase; // raw offset
+                    int pid = poolIndex;
+                    if ((t = q[i]) != null) {
+                        if (!canSteal &&  // inline p.tryIncrementActiveCount
+                            UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
+                                                     a = p.runState, a + 1))
+                            canSteal = active = true;
+                        if (canSteal && v.base == b++ &&
+                            UNSAFE.compareAndSwapObject(q, u, t, null)) {
+                            v.base = b;
+                            v.stealHint = pid;
+                            UNSAFE.putOrderedObject(this,
+                                                    currentStealOffset, t);
+                            seed = r;
+                            ++stealCount;
+                            return t;
+                        }
                     }
-                    else if (!tryActivate() || (t = v.deqTask()) == null)
-                        continue outer;  // restart on contention
-                    else
-                        break outer;
+                    j = -n;
+                    k = r;                // restart on contention
                 }
+                else if (++j <= 0)
+                    k = r;
+                else if (j <= n)
+                    k += (n >>> 1) | 1;
+                else
+                    break;
             }
-        } while (pool.hasNewSyncEvent(this)); // retry on pool events
-        seed = r;
-        return t;
-    }
-
-    /**
-     * Gets and removes a local or stolen task.
-     *
-     * @return a task, if available
-     */
-    final ForkJoinTask<?> pollTask() {
-        ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask();
-        if (t == null && (t = scan()) != null)
-            ++stealCount;
-        return t;
-    }
-
-    /**
-     * Gets a local task.
-     *
-     * @return a task, if available
-     */
-    final ForkJoinTask<?> pollLocalTask() {
-        return locallyFifo ? locallyDeqTask() : popTask();
-    }
-
-    /**
-     * Returns a pool submission, if one exists, activating first.
-     *
-     * @return a submission, if available
-     */
-    private ForkJoinTask<?> pollSubmission() {
-        ForkJoinPool p = pool;
-        while (p.hasQueuedSubmissions()) {
-            ForkJoinTask<?> t;
-            if (tryActivate() && (t = p.pollSubmission()) != null)
-                return t;
         }
         return null;
     }
 
-    // Methods accessed only by Pool
+    // Run State management
+
+    // status check methods used mainly by ForkJoinPool
+    final boolean isRunning()     { return runState == 0; }
+    final boolean isTerminating() { return (runState & TERMINATING) != 0; }
+    final boolean isTerminated()  { return (runState & TERMINATED) != 0; }
+    final boolean isSuspended()   { return (runState & SUSPENDED) != 0; }
+    final boolean isTrimmed()     { return (runState & TRIMMED) != 0; }
+
+    /**
+     * Sets state to TERMINATING. Does NOT unpark or interrupt
+     * to wake up if currently blocked. Callers must do so if desired.
+     */
+    final void shutdown() {
+        for (;;) {
+            int s = runState;
+            if ((s & (TERMINATING|TERMINATED)) != 0)
+                break;
+            if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended
+                if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
+                                             (s & ~SUSPENDED) |
+                                             (TRIMMED|TERMINATING)))
+                    break;
+            }
+            else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
+                                              s | TERMINATING))
+                break;
+        }
+    }
+
+    /**
+     * Sets state to TERMINATED. Called only by onTermination().
+     */
+    private void setTerminated() {
+        int s;
+        do {} while (!UNSAFE.compareAndSwapInt(this, runStateOffset,
+                                               s = runState,
+                                               s | (TERMINATING|TERMINATED)));
+    }
+
+    /**
+     * If suspended, tries to set status to unsuspended.
+     * Does NOT wake up if blocked.
+     *
+     * @return true if successful
+     */
+    final boolean tryUnsuspend() {
+        int s;
+        while (((s = runState) & SUSPENDED) != 0) {
+            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
+                                         s & ~SUSPENDED))
+                return true;
+        }
+        return false;
+    }
+
+    /**
+     * Sets suspended status and blocks as spare until resumed
+     * or shutdown.
+     */
+    final void suspendAsSpare() {
+        for (;;) {                  // set suspended unless terminating
+            int s = runState;
+            if ((s & TERMINATING) != 0) { // must kill
+                if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
+                                             s | (TRIMMED | TERMINATING)))
+                    return;
+            }
+            else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
+                                              s | SUSPENDED))
+                break;
+        }
+        ForkJoinPool p = pool;
+        p.pushSpare(this);
+        while ((runState & SUSPENDED) != 0) {
+            if (p.tryAccumulateStealCount(this)) {
+                interrupted();          // clear/ignore interrupts
+                if ((runState & SUSPENDED) == 0)
+                    break;
+                LockSupport.park(this);
+            }
+        }
+    }
+
+    // Misc support methods for ForkJoinPool
+
+    /**
+     * Returns an estimate of the number of tasks in the queue.  Also
+     * used by ForkJoinTask.
+     */
+    final int getQueueSize() {
+        int n; // external calls must read base first
+        return (n = -base + sp) <= 0 ? 0 : n;
+    }
 
     /**
      * Removes and cancels all tasks in queue.  Can be called from any
      * thread.
      */
     final void cancelTasks() {
-        ForkJoinTask<?> t;
-        while (base != sp && (t = deqTask()) != null)
-            t.cancelIgnoringExceptions();
+        ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
+        if (cj != null) {
+            currentJoin = null;
+            cj.cancelIgnoringExceptions();
+            try {
+                this.interrupt(); // awaken wait
+            } catch (SecurityException ignore) {
+            }
+        }
+        ForkJoinTask<?> cs = currentSteal;
+        if (cs != null) {
+            currentSteal = null;
+            cs.cancelIgnoringExceptions();
+        }
+        while (base != sp) {
+            ForkJoinTask<?> t = deqTask();
+            if (t != null)
+                t.cancelIgnoringExceptions();
+        }
     }
 
     /**
@@ -713,87 +902,266 @@
      */
     final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
         int n = 0;
-        ForkJoinTask<?> t;
-        while (base != sp && (t = deqTask()) != null) {
-            c.add(t);
-            ++n;
+        while (base != sp) {
+            ForkJoinTask<?> t = deqTask();
+            if (t != null) {
+                c.add(t);
+                ++n;
+            }
         }
         return n;
     }
 
-    /**
-     * Gets and clears steal count for accumulation by pool.  Called
-     * only when known to be idle (in pool.sync and termination).
-     */
-    final int getAndClearStealCount() {
-        int sc = stealCount;
-        stealCount = 0;
-        return sc;
-    }
-
-    /**
-     * Returns {@code true} if at least one worker in the given array
-     * appears to have at least one queued task.
-     *
-     * @param ws array of workers
-     */
-    static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
-        if (ws != null) {
-            int len = ws.length;
-            for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
-                for (int i = 0; i < len; ++i) {
-                    ForkJoinWorkerThread w = ws[i];
-                    if (w != null && w.sp != w.base)
-                        return true;
-                }
-            }
-        }
-        return false;
-    }
-
     // Support methods for ForkJoinTask
 
     /**
-     * Returns an estimate of the number of tasks in the queue.
+     * Gets and removes a local task.
+     *
+     * @return a task, if available
+     */
+    final ForkJoinTask<?> pollLocalTask() {
+        ForkJoinPool p = pool;
+        while (sp != base) {
+            int a; // inline p.tryIncrementActiveCount
+            if (active ||
+                (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
+                                                   a = p.runState, a + 1)))
+                return locallyFifo ? locallyDeqTask() : popTask();
+        }
+        return null;
+    }
+
+    /**
+     * Gets and removes a local or stolen task.
+     *
+     * @return a task, if available
+     */
+    final ForkJoinTask<?> pollTask() {
+        ForkJoinTask<?> t = pollLocalTask();
+        if (t == null) {
+            t = scan();
+            // cannot retain/track/help steal
+            UNSAFE.putOrderedObject(this, currentStealOffset, null);
+        }
+        return t;
+    }
+
+    /**
+     * Possibly runs some tasks and/or blocks, until task is done.
+     *
+     * @param joinMe the task to join
      */
-    final int getQueueSize() {
-        // suppress momentarily negative values
-        return Math.max(0, sp - base);
+    final void joinTask(ForkJoinTask<?> joinMe) {
+        // currentJoin only written by this thread; only need ordered store
+        ForkJoinTask<?> prevJoin = currentJoin;
+        UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe);
+        if (sp != base)
+            localHelpJoinTask(joinMe);
+        if (joinMe.status >= 0)
+            pool.awaitJoin(joinMe, this);
+        UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin);
+    }
+
+    /**
+     * Run tasks in local queue until given task is done.
+     *
+     * @param joinMe the task to join
+     */
+    private void localHelpJoinTask(ForkJoinTask<?> joinMe) {
+        int s;
+        ForkJoinTask<?>[] q;
+        while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) {
+            int i = (q.length - 1) & --s;
+            long u = (i << qShift) + qBase; // raw offset
+            ForkJoinTask<?> t = q[i];
+            if (t == null)  // lost to a stealer
+                break;
+            if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
+                /*
+                 * This recheck (and similarly in helpJoinTask)
+                 * handles cases where joinMe is independently
+                 * cancelled or forced even though there is other work
+                 * available. Back out of the pop by putting t back
+                 * into slot before we commit by writing sp.
+                 */
+                if (joinMe.status < 0) {
+                    UNSAFE.putObjectVolatile(q, u, t);
+                    break;
+                }
+                sp = s;
+                // UNSAFE.putOrderedInt(this, spOffset, s);
+                t.quietlyExec();
+            }
+        }
     }
 
     /**
-     * Returns an estimate of the number of tasks, offset by a
-     * function of number of idle workers.
+     * Unless terminating, tries to locate and help perform tasks for
+     * a stealer of the given task, or in turn one of its stealers.
+     * Traces currentSteal->currentJoin links looking for a thread
+     * working on a descendant of the given task and with a non-empty
+     * queue to steal back and execute tasks from.
+     *
+     * The implementation is very branchy to cope with potential
+     * inconsistencies or loops encountering chains that are stale,
+     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
+     * of these cases are dealt with by just returning back to the
+     * caller, who is expected to retry if other join mechanisms also
+     * don't work out.
+     *
+     * @param joinMe the task to join
      */
-    final int getEstimatedSurplusTaskCount() {
-        // The halving approximates weighting idle vs non-idle workers
-        return (sp - base) - (pool.getIdleThreadCount() >>> 1);
+    final void helpJoinTask(ForkJoinTask<?> joinMe) {
+        ForkJoinWorkerThread[] ws;
+        int n;
+        if (joinMe.status < 0)                // already done
+            return;
+        if ((runState & TERMINATING) != 0) {  // cancel if shutting down
+            joinMe.cancelIgnoringExceptions();
+            return;
+        }
+        if ((ws = pool.workers) == null || (n = ws.length) <= 1)
+            return;                           // need at least 2 workers
+
+        ForkJoinTask<?> task = joinMe;        // base of chain
+        ForkJoinWorkerThread thread = this;   // thread with stolen task
+        for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length
+            // Try to find v, the stealer of task, by first using hint
+            ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)];
+            if (v == null || v.currentSteal != task) {
+                for (int j = 0; ; ++j) {      // search array
+                    if (j < n) {
+                        ForkJoinTask<?> vs;
+                        if ((v = ws[j]) != null &&
+                            (vs = v.currentSteal) != null) {
+                            if (joinMe.status < 0 || task.status < 0)
+                                return;       // stale or done
+                            if (vs == task) {
+                                thread.stealHint = j;
+                                break;        // save hint for next time
+                            }
+                        }
+                    }
+                    else
+                        return;               // no stealer
+                }
+            }
+            for (;;) { // Try to help v, using specialized form of deqTask
+                if (joinMe.status < 0)
+                    return;
+                int b = v.base;
+                ForkJoinTask<?>[] q = v.queue;
+                if (b == v.sp || q == null)
+                    break;
+                int i = (q.length - 1) & b;
+                long u = (i << qShift) + qBase;
+                ForkJoinTask<?> t = q[i];
+                int pid = poolIndex;
+                ForkJoinTask<?> ps = currentSteal;
+                if (task.status < 0)
+                    return;                   // stale or done
+                if (t != null && v.base == b++ &&
+                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
+                    if (joinMe.status < 0) {
+                        UNSAFE.putObjectVolatile(q, u, t);
+                        return;               // back out on cancel
+                    }
+                    v.base = b;
+                    v.stealHint = pid;
+                    UNSAFE.putOrderedObject(this, currentStealOffset, t);
+                    t.quietlyExec();
+                    UNSAFE.putOrderedObject(this, currentStealOffset, ps);
+                }
+            }
+            // Try to descend to find v's stealer
+            ForkJoinTask<?> next = v.currentJoin;
+            if (task.status < 0 || next == null || next == task ||
+                joinMe.status < 0)
+                return;
+            task = next;
+            thread = v;
+        }
     }
 
     /**
-     * Scans, returning early if joinMe done.
+     * Implements ForkJoinTask.getSurplusQueuedTaskCount().
+     * Returns an estimate of the number of tasks, offset by a
+     * function of number of idle workers.
+     *
+     * This method provides a cheap heuristic guide for task
+     * partitioning when programmers, frameworks, tools, or languages
+     * have little or no idea about task granularity.  In essence by
+     * offering this method, we ask users only about tradeoffs in
+     * overhead vs expected throughput and its variance, rather than
+     * how finely to partition tasks.
+     *
+     * In a steady state strict (tree-structured) computation, each
+     * thread makes available for stealing enough tasks for other
+     * threads to remain active. Inductively, if all threads play by
+     * the same rules, each thread should make available only a
+     * constant number of tasks.
+     *
+     * The minimum useful constant is just 1. But using a value of 1
+     * would require immediate replenishment upon each steal to
+     * maintain enough tasks, which is infeasible.  Further,
+     * partitionings/granularities of offered tasks should minimize
+     * steal rates, which in general means that threads nearer the top
+     * of computation tree should generate more than those nearer the
+     * bottom. In perfect steady state, each thread is at
+     * approximately the same level of computation tree. However,
+     * producing extra tasks amortizes the uncertainty of progress and
+     * diffusion assumptions.
+     *
+     * So, users will want to use values larger, but not much larger
+     * than 1 to both smooth over transient shortages and hedge
+     * against uneven progress; as traded off against the cost of
+     * extra task overhead. We leave the user to pick a threshold
+     * value to compare with the results of this call to guide
+     * decisions, but recommend values such as 3.
+     *
+     * When all threads are active, it is on average OK to estimate
+     * surplus strictly locally. In steady-state, if one thread is
+     * maintaining say 2 surplus tasks, then so are others. So we can
+     * just use estimated queue length (although note that (sp - base)
+     * can be an overestimate because of stealers lagging increments
+     * of base).  However, this strategy alone leads to serious
+     * mis-estimates in some non-steady-state conditions (ramp-up,
+     * ramp-down, other stalls). We can detect many of these by
+     * further considering the number of "idle" threads, that are
+     * known to have zero queued tasks, so compensate by a factor of
+     * (#idle/#active) threads.
      */
-    final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
-        ForkJoinTask<?> t = pollTask();
-        if (t != null && joinMe.status < 0 && sp == base) {
-            pushTask(t); // unsteal if done and this task would be stealable
-            t = null;
-        }
-        return t;
+    final int getEstimatedSurplusTaskCount() {
+        return sp - base - pool.idlePerActive();
     }
 
     /**
      * Runs tasks until {@code pool.isQuiescent()}.
      */
     final void helpQuiescePool() {
+        ForkJoinTask<?> ps = currentSteal; // to restore below
         for (;;) {
-            ForkJoinTask<?> t = pollTask();
-            if (t != null)
+            ForkJoinTask<?> t = pollLocalTask();
+            if (t != null || (t = scan()) != null)
                 t.quietlyExec();
-            else if (tryInactivate() && pool.isQuiescent())
-                break;
+            else {
+                ForkJoinPool p = pool;
+                int a; // to inline CASes
+                if (active) {
+                    if (!UNSAFE.compareAndSwapInt
+                        (p, poolRunStateOffset, a = p.runState, a - 1))
+                        continue;   // retry later
+                    active = false; // inactivate
+                    UNSAFE.putOrderedObject(this, currentStealOffset, ps);
+                }
+                if (p.isQuiescent()) {
+                    active = true; // re-activate
+                    do {} while (!UNSAFE.compareAndSwapInt
+                                 (p, poolRunStateOffset, a = p.runState, a+1));
+                    return;
+                }
+            }
         }
-        do {} while (!tryActivate()); // re-activate on exit
     }
 
     // Unsafe mechanics
@@ -803,15 +1171,23 @@
         objectFieldOffset("sp", ForkJoinWorkerThread.class);
     private static final long runStateOffset =
         objectFieldOffset("runState", ForkJoinWorkerThread.class);
-    private static final long qBase;
+    private static final long currentJoinOffset =
+        objectFieldOffset("currentJoin", ForkJoinWorkerThread.class);
+    private static final long currentStealOffset =
+        objectFieldOffset("currentSteal", ForkJoinWorkerThread.class);
+    private static final long qBase =
+        UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
+    private static final long poolRunStateOffset = // to inline CAS
+        objectFieldOffset("runState", ForkJoinPool.class);
+
     private static final int qShift;
 
     static {
-        qBase = UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
         int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
         if ((s & (s-1)) != 0)
             throw new Error("data type scale not a power of two");
         qShift = 31 - Integer.numberOfLeadingZeros(s);
+        MAXIMUM_QUEUE_CAPACITY = 1 << (31 - qShift);
     }
 
     private static long objectFieldOffset(String field, Class<?> klazz) {
--- a/src/share/classes/java/util/concurrent/LinkedTransferQueue.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/concurrent/LinkedTransferQueue.java	Fri Sep 24 16:41:32 2010 -0700
@@ -42,6 +42,7 @@
 import java.util.NoSuchElementException;
 import java.util.Queue;
 import java.util.concurrent.locks.LockSupport;
+
 /**
  * An unbounded {@link TransferQueue} based on linked nodes.
  * This queue orders elements FIFO (first-in-first-out) with respect
@@ -233,24 +234,6 @@
      * additional GC bookkeeping ("write barriers") that are sometimes
      * more costly than the writes themselves because of contention).
      *
-     * Removal of interior nodes (due to timed out or interrupted
-     * waits, or calls to remove(x) or Iterator.remove) can use a
-     * scheme roughly similar to that described in Scherer, Lea, and
-     * Scott's SynchronousQueue. Given a predecessor, we can unsplice
-     * any node except the (actual) tail of the queue. To avoid
-     * build-up of cancelled trailing nodes, upon a request to remove
-     * a trailing node, it is placed in field "cleanMe" to be
-     * unspliced upon the next call to unsplice any other node.
-     * Situations needing such mechanics are not common but do occur
-     * in practice; for example when an unbounded series of short
-     * timed calls to poll repeatedly time out but never otherwise
-     * fall off the list because of an untimed call to take at the
-     * front of the queue. Note that maintaining field cleanMe does
-     * not otherwise much impact garbage retention even if never
-     * cleared by some other call because the held node will
-     * eventually either directly or indirectly lead to a self-link
-     * once off the list.
-     *
      * *** Overview of implementation ***
      *
      * We use a threshold-based approach to updates, with a slack
@@ -266,15 +249,10 @@
      * per-thread one available, but even ThreadLocalRandom is too
      * heavy for these purposes.
      *
-     * With such a small slack threshold value, it is rarely
-     * worthwhile to augment this with path short-circuiting; i.e.,
-     * unsplicing nodes between head and the first unmatched node, or
-     * similarly for tail, rather than advancing head or tail
-     * proper. However, it is used (in awaitMatch) immediately before
-     * a waiting thread starts to block, as a final bit of helping at
-     * a point when contention with others is extremely unlikely
-     * (since if other threads that could release it are operating,
-     * then the current thread wouldn't be blocking).
+     * With such a small slack threshold value, it is not worthwhile
+     * to augment this with path short-circuiting (i.e., unsplicing
+     * interior nodes) except in the case of cancellation/removal (see
+     * below).
      *
      * We allow both the head and tail fields to be null before any
      * nodes are enqueued; initializing upon first append.  This
@@ -356,6 +334,70 @@
      *    versa) compared to their predecessors receive additional
      *    chained spins, reflecting longer paths typically required to
      *    unblock threads during phase changes.
+     *
+     *
+     * ** Unlinking removed interior nodes **
+     *
+     * In addition to minimizing garbage retention via self-linking
+     * described above, we also unlink removed interior nodes. These
+     * may arise due to timed out or interrupted waits, or calls to
+     * remove(x) or Iterator.remove.  Normally, given a node that was
+     * at one time known to be the predecessor of some node s that is
+     * to be removed, we can unsplice s by CASing the next field of
+     * its predecessor if it still points to s (otherwise s must
+     * already have been removed or is now offlist). But there are two
+     * situations in which we cannot guarantee to make node s
+     * unreachable in this way: (1) If s is the trailing node of list
+     * (i.e., with null next), then it is pinned as the target node
+     * for appends, so can only be removed later after other nodes are
+     * appended. (2) We cannot necessarily unlink s given a
+     * predecessor node that is matched (including the case of being
+     * cancelled): the predecessor may already be unspliced, in which
+     * case some previous reachable node may still point to s.
+     * (For further explanation see Herlihy & Shavit "The Art of
+     * Multiprocessor Programming" chapter 9).  Although, in both
+     * cases, we can rule out the need for further action if either s
+     * or its predecessor are (or can be made to be) at, or fall off
+     * from, the head of list.
+     *
+     * Without taking these into account, it would be possible for an
+     * unbounded number of supposedly removed nodes to remain
+     * reachable.  Situations leading to such buildup are uncommon but
+     * can occur in practice; for example when a series of short timed
+     * calls to poll repeatedly time out but never otherwise fall off
+     * the list because of an untimed call to take at the front of the
+     * queue.
+     *
+     * When these cases arise, rather than always retraversing the
+     * entire list to find an actual predecessor to unlink (which
+     * won't help for case (1) anyway), we record a conservative
+     * estimate of possible unsplice failures (in "sweepVotes").
+     * We trigger a full sweep when the estimate exceeds a threshold
+     * ("SWEEP_THRESHOLD") indicating the maximum number of estimated
+     * removal failures to tolerate before sweeping through, unlinking
+     * cancelled nodes that were not unlinked upon initial removal.
+     * We perform sweeps by the thread hitting threshold (rather than
+     * background threads or by spreading work to other threads)
+     * because in the main contexts in which removal occurs, the
+     * caller is already timed-out, cancelled, or performing a
+     * potentially O(n) operation (e.g. remove(x)), none of which are
+     * time-critical enough to warrant the overhead that alternatives
+     * would impose on other threads.
+     *
+     * Because the sweepVotes estimate is conservative, and because
+     * nodes become unlinked "naturally" as they fall off the head of
+     * the queue, and because we allow votes to accumulate even while
+     * sweeps are in progress, there are typically significantly fewer
+     * such nodes than estimated.  Choice of a threshold value
+     * balances the likelihood of wasted effort and contention, versus
+     * providing a worst-case bound on retention of interior nodes in
+     * quiescent queues. The value defined below was chosen
+     * empirically to balance these under various timeout scenarios.
+     *
+     * Note that we cannot self-link unlinked interior nodes during
+     * sweeps. However, the associated garbage chains terminate when
+     * some successor ultimately falls off the head of the list and is
+     * self-linked.
      */
 
     /** True if on multiprocessor */
@@ -382,11 +424,19 @@
     private static final int CHAINED_SPINS = FRONT_SPINS >>> 1;
 
     /**
+     * The maximum number of estimated removal failures (sweepVotes)
+     * to tolerate before sweeping through the queue unlinking
+     * cancelled nodes that were not unlinked upon initial
+     * removal. See above for explanation. The value must be at least
+     * two to avoid useless sweeps when removing trailing nodes.
+     */
+    static final int SWEEP_THRESHOLD = 32;
+
+    /**
      * Queue nodes. Uses Object, not E, for items to allow forgetting
      * them after use.  Relies heavily on Unsafe mechanics to minimize
-     * unnecessary ordering constraints: Writes that intrinsically
-     * precede or follow CASes use simple relaxed forms.  Other
-     * cleanups use releasing/lazy writes.
+     * unnecessary ordering constraints: Writes that are intrinsically
+     * ordered wrt other accesses or CASes use simple relaxed forms.
      */
     static final class Node {
         final boolean isData;   // false if this is a request node
@@ -400,13 +450,13 @@
         }
 
         final boolean casItem(Object cmp, Object val) {
-            // assert cmp == null || cmp.getClass() != Node.class;
+            //            assert cmp == null || cmp.getClass() != Node.class;
             return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
         }
 
         /**
-         * Creates a new node. Uses relaxed write because item can only
-         * be seen if followed by CAS.
+         * Constructs a new node.  Uses relaxed write because item can
+         * only be seen after publication via casNext.
          */
         Node(Object item, boolean isData) {
             UNSAFE.putObject(this, itemOffset, item); // relaxed write
@@ -422,13 +472,17 @@
         }
 
         /**
-         * Sets item to self (using a releasing/lazy write) and waiter
-         * to null, to avoid garbage retention after extracting or
-         * cancelling.
+         * Sets item to self and waiter to null, to avoid garbage
+         * retention after matching or cancelling. Uses relaxed writes
+         * because order is already constrained in the only calling
+         * contexts: item is forgotten only after volatile/atomic
+         * mechanics that extract items.  Similarly, clearing waiter
+         * follows either CAS or return from park (if ever parked;
+         * else we don't care).
          */
         final void forgetContents() {
-            UNSAFE.putOrderedObject(this, itemOffset, this);
-            UNSAFE.putOrderedObject(this, waiterOffset, null);
+            UNSAFE.putObject(this, itemOffset, this);
+            UNSAFE.putObject(this, waiterOffset, null);
         }
 
         /**
@@ -462,7 +516,7 @@
          * Tries to artificially match a data node -- used by remove.
          */
         final boolean tryMatchData() {
-            // assert isData;
+            //            assert isData;
             Object x = item;
             if (x != null && x != this && casItem(x, null)) {
                 LockSupport.unpark(waiter);
@@ -486,12 +540,12 @@
     /** head of the queue; null until first enqueue */
     transient volatile Node head;
 
-    /** predecessor of dangling unspliceable node */
-    private transient volatile Node cleanMe; // decl here reduces contention
-
     /** tail of the queue; null until first append */
     private transient volatile Node tail;
 
+    /** The number of apparent failures to unsplice removed nodes */
+    private transient volatile int sweepVotes;
+
     // CAS methods for fields
     private boolean casTail(Node cmp, Node val) {
         return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
@@ -501,8 +555,8 @@
         return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
     }
 
-    private boolean casCleanMe(Node cmp, Node val) {
-        return UNSAFE.compareAndSwapObject(this, cleanMeOffset, cmp, val);
+    private boolean casSweepVotes(int cmp, int val) {
+        return UNSAFE.compareAndSwapInt(this, sweepVotesOffset, cmp, val);
     }
 
     /*
@@ -515,7 +569,7 @@
 
     @SuppressWarnings("unchecked")
     static <E> E cast(Object item) {
-        // assert item == null || item.getClass() != Node.class;
+        //        assert item == null || item.getClass() != Node.class;
         return (E) item;
     }
 
@@ -544,10 +598,8 @@
                         break;
                     if (p.casItem(item, e)) { // match
                         for (Node q = p; q != h;) {
-                            Node n = q.next;  // update head by 2
-                            if (n != null)    // unless singleton
-                                q = n;
-                            if (head == h && casHead(h, q)) {
+                            Node n = q.next;  // update by 2 unless singleton
+                            if (head == h && casHead(h, n == null? q : n)) {
                                 h.forgetNext();
                                 break;
                             }                 // advance and retry
@@ -632,12 +684,12 @@
         for (;;) {
             Object item = s.item;
             if (item != e) {                  // matched
-                // assert item != s;
+                //                assert item != s;
                 s.forgetContents();           // avoid garbage
                 return this.<E>cast(item);
             }
             if ((w.isInterrupted() || (timed && nanos <= 0)) &&
-                    s.casItem(e, s)) {       // cancel
+                    s.casItem(e, s)) {        // cancel
                 unsplice(pred, s);
                 return e;
             }
@@ -647,9 +699,8 @@
                     randomYields = ThreadLocalRandom.current();
             }
             else if (spins > 0) {             // spin
-                if (--spins == 0)
-                    shortenHeadPath();        // reduce slack before blocking
-                else if (randomYields.nextInt(CHAINED_SPINS) == 0)
+                --spins;
+                if (randomYields.nextInt(CHAINED_SPINS) == 0)
                     Thread.yield();           // occasionally yield
             }
             else if (s.waiter == null) {
@@ -663,8 +714,6 @@
             }
             else {
                 LockSupport.park(this);
-                s.waiter = null;
-                spins = -1;                   // spin if front upon wakeup
             }
         }
     }
@@ -685,27 +734,6 @@
         return 0;
     }
 
-    /**
-     * Tries (once) to unsplice nodes between head and first unmatched
-     * or trailing node; failing on contention.
-     */
-    private void shortenHeadPath() {
-        Node h, hn, p, q;
-        if ((p = h = head) != null && h.isMatched() &&
-            (q = hn = h.next) != null) {
-            Node n;
-            while ((n = q.next) != q) {
-                if (n == null || !q.isMatched()) {
-                    if (hn != q && h.next == hn)
-                        h.casNext(hn, q);
-                    break;
-                }
-                p = q;
-                q = n;
-            }
-        }
-    }
-
     /* -------------- Traversal methods -------------- */
 
     /**
@@ -818,7 +846,8 @@
         public final void remove() {
             Node p = lastRet;
             if (p == null) throw new IllegalStateException();
-            findAndRemoveDataNode(lastPred, p);
+            if (p.tryMatchData())
+                unsplice(lastPred, p);
         }
     }
 
@@ -828,99 +857,68 @@
      * Unsplices (now or later) the given deleted/cancelled node with
      * the given predecessor.
      *
-     * @param pred predecessor of node to be unspliced
+     * @param pred a node that was at one time known to be the
+     * predecessor of s, or null or s itself if s is/was at head
      * @param s the node to be unspliced
      */
-    private void unsplice(Node pred, Node s) {
-        s.forgetContents(); // clear unneeded fields
+    final void unsplice(Node pred, Node s) {
+        s.forgetContents(); // forget unneeded fields
         /*
-         * At any given time, exactly one node on list cannot be
-         * unlinked -- the last inserted node. To accommodate this, if
-         * we cannot unlink s, we save its predecessor as "cleanMe",
-         * processing the previously saved version first. Because only
-         * one node in the list can have a null next, at least one of
-         * node s or the node previously saved can always be
-         * processed, so this always terminates.
+         * See above for rationale. Briefly: if pred still points to
+         * s, try to unlink s.  If s cannot be unlinked, because it is
+         * trailing node or pred might be unlinked, and neither pred
+         * nor s are head or offlist, add to sweepVotes, and if enough
+         * votes have accumulated, sweep.
          */
-        if (pred != null && pred != s) {
-            while (pred.next == s) {
-                Node oldpred = (cleanMe == null) ? null : reclean();
-                Node n = s.next;
-                if (n != null) {
-                    if (n != s)
-                        pred.casNext(s, n);
-                    break;
+        if (pred != null && pred != s && pred.next == s) {
+            Node n = s.next;
+            if (n == null ||
+                (n != s && pred.casNext(s, n) && pred.isMatched())) {
+                for (;;) {               // check if at, or could be, head
+                    Node h = head;
+                    if (h == pred || h == s || h == null)
+                        return;          // at head or list empty
+                    if (!h.isMatched())
+                        break;
+                    Node hn = h.next;
+                    if (hn == null)
+                        return;          // now empty
+                    if (hn != h && casHead(h, hn))
+                        h.forgetNext();  // advance head
                 }
-                if (oldpred == pred ||      // Already saved
-                    ((oldpred == null || oldpred.next == s) &&
-                     casCleanMe(oldpred, pred))) {
-                    break;
+                if (pred.next != pred && s.next != s) { // recheck if offlist
+                    for (;;) {           // sweep now if enough votes
+                        int v = sweepVotes;
+                        if (v < SWEEP_THRESHOLD) {
+                            if (casSweepVotes(v, v + 1))
+                                break;
+                        }
+                        else if (casSweepVotes(v, 0)) {
+                            sweep();
+                            break;
+                        }
+                    }
                 }
             }
         }
     }
 
     /**
-     * Tries to unsplice the deleted/cancelled node held in cleanMe
-     * that was previously uncleanable because it was at tail.
-     *
-     * @return current cleanMe node (or null)
+     * Unlinks matched (typically cancelled) nodes encountered in a
+     * traversal from head.
      */
-    private Node reclean() {
-        /*
-         * cleanMe is, or at one time was, predecessor of a cancelled
-         * node s that was the tail so could not be unspliced.  If it
-         * is no longer the tail, try to unsplice if necessary and
-         * make cleanMe slot available.  This differs from similar
-         * code in unsplice() because we must check that pred still
-         * points to a matched node that can be unspliced -- if not,
-         * we can (must) clear cleanMe without unsplicing.  This can
-         * loop only due to contention.
-         */
-        Node pred;
-        while ((pred = cleanMe) != null) {
-            Node s = pred.next;
-            Node n;
-            if (s == null || s == pred || !s.isMatched())
-                casCleanMe(pred, null); // already gone
-            else if ((n = s.next) != null) {
-                if (n != s)
-                    pred.casNext(s, n);
-                casCleanMe(pred, null);
-            }
-            else
+    private void sweep() {
+        for (Node p = head, s, n; p != null && (s = p.next) != null; ) {
+            if (!s.isMatched())
+                // Unmatched nodes are never self-linked
+                p = s;
+            else if ((n = s.next) == null) // trailing node is pinned
                 break;
-        }
-        return pred;
-    }
-
-    /**
-     * Main implementation of Iterator.remove(). Finds
-     * and unsplices the given data node.
-     *
-     * @param possiblePred possible predecessor of s
-     * @param s the node to remove
-     */
-    final void findAndRemoveDataNode(Node possiblePred, Node s) {
-        // assert s.isData;
-        if (s.tryMatchData()) {
-            if (possiblePred != null && possiblePred.next == s)
-                unsplice(possiblePred, s); // was actual predecessor
-            else {
-                for (Node pred = null, p = head; p != null; ) {
-                    if (p == s) {
-                        unsplice(pred, p);
-                        break;
-                    }
-                    if (p.isUnmatchedRequest())
-                        break;
-                    pred = p;
-                    if ((p = p.next) == pred) { // stale
-                        pred = null;
-                        p = head;
-                    }
-                }
-            }
+            else if (s == n)    // stale
+                // No need to also check for p == s, since that implies s == n
+                p = head;
+            else
+                p.casNext(s, n);
         }
     }
 
@@ -1158,7 +1156,11 @@
      * @return {@code true} if this queue contains no elements
      */
     public boolean isEmpty() {
-        return firstOfMode(true) == null;
+        for (Node p = head; p != null; p = succ(p)) {
+            if (!p.isMatched())
+                return !p.isData;
+        }
+        return true;
     }
 
     public boolean hasWaitingConsumer() {
@@ -1252,8 +1254,8 @@
         objectFieldOffset(UNSAFE, "head", LinkedTransferQueue.class);
     private static final long tailOffset =
         objectFieldOffset(UNSAFE, "tail", LinkedTransferQueue.class);
-    private static final long cleanMeOffset =
-        objectFieldOffset(UNSAFE, "cleanMe", LinkedTransferQueue.class);
+    private static final long sweepVotesOffset =
+        objectFieldOffset(UNSAFE, "sweepVotes", LinkedTransferQueue.class);
 
     static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
                                   String field, Class<?> klazz) {
@@ -1266,5 +1268,4 @@
             throw error;
         }
     }
-
 }
--- a/src/share/classes/java/util/concurrent/Phaser.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/concurrent/Phaser.java	Fri Sep 24 16:41:32 2010 -0700
@@ -898,7 +898,7 @@
         boolean doWait() {
             if (thread != null) {
                 try {
-                    ForkJoinPool.managedBlock(this, false);
+                    ForkJoinPool.managedBlock(this);
                 } catch (InterruptedException ie) {
                 }
             }
--- a/src/share/classes/java/util/spi/LocaleNameProvider.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/spi/LocaleNameProvider.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -44,22 +44,23 @@
     }
 
     /**
-     * Returns a localized name for the given ISO 639 language code and the
-     * given locale that is appropriate for display to the user.
+     * Returns a localized name for the given <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt">
+     * IETF BCP47</a> language code and the given locale that is appropriate for
+     * display to the user.
      * For example, if <code>languageCode</code> is "fr" and <code>locale</code>
      * is en_US, getDisplayLanguage() will return "French"; if <code>languageCode</code>
      * is "en" and <code>locale</code> is fr_FR, getDisplayLanguage() will return "anglais".
      * If the name returned cannot be localized according to <code>locale</code>,
      * (say, the provider does not have a Japanese name for Croatian),
      * this method returns null.
-     * @param languageCode the ISO 639 language code string in the form of two
+     * @param languageCode the language code string in the form of two to eight
      *     lower-case letters between 'a' (U+0061) and 'z' (U+007A)
      * @param locale the desired locale
      * @return the name of the given language code for the specified locale, or null if it's not
      *     available.
      * @exception NullPointerException if <code>languageCode</code> or <code>locale</code> is null
      * @exception IllegalArgumentException if <code>languageCode</code> is not in the form of
-     *     two lower-case letters, or <code>locale</code> isn't
+     *     two or three lower-case letters, or <code>locale</code> isn't
      *     one of the locales returned from
      *     {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
      *     getAvailableLocales()}.
@@ -68,22 +69,52 @@
     public abstract String getDisplayLanguage(String languageCode, Locale locale);
 
     /**
-     * Returns a localized name for the given ISO 3166 country code and the
-     * given locale that is appropriate for display to the user.
+     * Returns a localized name for the given <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt">
+     * IETF BCP47</a> script code and the given locale that is appropriate for
+     * display to the user.
+     * For example, if <code>scriptCode</code> is "Latn" and <code>locale</code>
+     * is en_US, getDisplayScript() will return "Latin"; if <code>scriptCode</code>
+     * is "Cyrl" and <code>locale</code> is fr_FR, getDisplayScript() will return "cyrillique".
+     * If the name returned cannot be localized according to <code>locale</code>,
+     * (say, the provider does not have a Japanese name for Cyrillic),
+     * this method returns null.
+     * @param scriptCode the four letter script code string in the form of title-case
+     *     letters (the first letter is upper-case character between 'A' (U+0041) and
+     *     'Z' (U+005A) followed by three lower-case character between 'a' (U+0061)
+     *     and 'z' (U+007A)).
+     * @param locale the desired locale
+     * @return the name of the given script code for the specified locale, or null if it's not
+     *     available.
+     * @exception NullPointerException if <code>scriptCode</code> or <code>locale</code> is null
+     * @exception IllegalArgumentException if <code>scriptCode</code> is not in the form of
+     *     four title case letters, or <code>locale</code> isn't
+     *     one of the locales returned from
+     *     {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
+     *     getAvailableLocales()}.
+     * @see java.util.Locale#getDisplayScript(java.util.Locale)
+     * @since 1.7
+     */
+    public abstract String getDisplayScript(String scriptCode, Locale locale);
+
+    /**
+     * Returns a localized name for the given <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt">
+     * IETF BCP47</a> region code (either ISO 3166 country code or UN M.49 area
+     * codes) and the given locale that is appropriate for display to the user.
      * For example, if <code>countryCode</code> is "FR" and <code>locale</code>
      * is en_US, getDisplayCountry() will return "France"; if <code>countryCode</code>
      * is "US" and <code>locale</code> is fr_FR, getDisplayCountry() will return "Etats-Unis".
      * If the name returned cannot be localized according to <code>locale</code>,
      * (say, the provider does not have a Japanese name for Croatia),
      * this method returns null.
-     * @param countryCode the ISO 3166 country code string in the form of two
-     *     upper-case letters between 'A' (U+0041) and 'Z' (U+005A)
+     * @param countryCode the country(region) code string in the form of two
+     *     upper-case letters between 'A' (U+0041) and 'Z' (U+005A) or the UN M.49 area code
+     *     in the form of three digit letters between '0' (U+0030) and '9' (U+0039).
      * @param locale the desired locale
      * @return the name of the given country code for the specified locale, or null if it's not
      *     available.
      * @exception NullPointerException if <code>countryCode</code> or <code>locale</code> is null
      * @exception IllegalArgumentException if <code>countryCode</code> is not in the form of
-     *     two upper-case letters, or <code>locale</code> isn't
+     *     two upper-case letters or three digit letters, or <code>locale</code> isn't
      *     one of the locales returned from
      *     {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
      *     getAvailableLocales()}.
--- a/src/share/classes/java/util/spi/LocaleServiceProvider.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/java/util/spi/LocaleServiceProvider.java	Fri Sep 24 16:41:32 2010 -0700
@@ -86,18 +86,19 @@
  * Otherwise, they call the <code>getAvailableLocales()</code> methods of
  * installed providers for the appropriate interface to find one that
  * supports the requested locale. If such a provider is found, its other
- * methods are called to obtain the requested object or name. If neither
- * the Java runtime environment itself nor an installed provider supports
- * the requested locale, a fallback locale is constructed by replacing the
- * first of the variant, country, or language strings of the locale that's
- * not an empty string with an empty string, and the lookup process is
- * restarted. In the case that the variant contains one or more '_'s, the
- * fallback locale is constructed by replacing the variant with a new variant
- * which eliminates the last '_' and the part following it.  Even if a
- * fallback occurs, methods that return requested objects or name are
- * invoked with the original locale before the fallback.The Java runtime
- * environment must support the root locale for all locale sensitive services
- * in order to guarantee that this process terminates.
+ * methods are called to obtain the requested object or name.  When checking
+ * whether a locale is supported, the locale's extensions are ignored.
+ * If neither the Java runtime environment itself nor an installed provider
+ * supports the requested locale, the methods go through a list of candidate
+ * locales and repeat the availability check for each until a match is found.
+ * The algorithm used for creating a list of candidate locales is same as
+ * the one used by <code>ResourceBunlde</code> by default (see
+ * {@link java.util.ResourceBundle.Control#getCandidateLocales getCandidateLocales}
+ * for the details).  Even if a locale is resolved from the candidate list,
+ * methods that return requested objects or names are invoked with the original
+ * requested locale including extensions.  The Java runtime environment must
+ * support the root locale for all locale sensitive services in order to
+ * guarantee that this process terminates.
  * <p>
  * Providers of names (but not providers of other objects) are allowed to
  * return null for some name requests even for locales that they claim to
@@ -124,6 +125,11 @@
     /**
      * Returns an array of all locales for which this locale service provider
      * can provide localized objects or names.
+     * <p>
+     * <b>Note:</b> Extensions in a <code>Locale</code> are ignored during
+     * service provider lookup.  So the array returned by this method should
+     * not include two or more <code>Locale</code> objects only differing in
+     * their extensions.
      *
      * @return An array of all locales for which this locale service provider
      * can provide localized objects or names.
--- a/src/share/classes/javax/sound/midi/MidiDevice.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/sound/midi/MidiDevice.java	Fri Sep 24 16:41:32 2010 -0700
@@ -204,6 +204,9 @@
      * MIDI data.  The returned receiver must be closed when the application
      * has finished using it.
      *
+     * <p>Usually the returned receiver implements
+     * the {@code MidiDeviceReceiver} interface.
+     *
      * <p>Obtaining a <code>Receiver</code> with this method does not
      * open the device. To be able to use the device, it has to be
      * opened explicitly by calling {@link #open}. Also, closing the
@@ -223,6 +226,10 @@
      * connected with this MidiDevice.
      * A receiver can be removed
      * from the device by closing it.
+     *
+     * <p>Usually the returned receivers implement
+     * the {@code MidiDeviceReceiver} interface.
+     *
      * @return an unmodifiable list of the open receivers
      * @since 1.5
      */
@@ -234,6 +241,9 @@
      * MIDI data  The returned transmitter must be closed when the application
      * has finished using it.
      *
+     * <p>Usually the returned transmitter implements
+     * the {@code MidiDeviceTransmitter} interface.
+     *
      * <p>Obtaining a <code>Transmitter</code> with this method does not
      * open the device. To be able to use the device, it has to be
      * opened explicitly by calling {@link #open}. Also, closing the
@@ -253,6 +263,10 @@
      * connected with this MidiDevice.
      * A transmitter can be removed
      * from the device by closing it.
+     *
+     * <p>Usually the returned transmitters implement
+     * the {@code MidiDeviceTransmitter} interface.
+     *
      * @return an unmodifiable list of the open transmitters
      * @since 1.5
      */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/sound/midi/MidiDeviceReceiver.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javax.sound.midi;
+
+/**
+ * <p>{@code MidiDeviceReceiver} is a {@code Receiver} which represents
+ * a MIDI input connector of a {@code MidiDevice}
+ * (see {@link MidiDevice#getReceiver()}).
+ *
+ * @since 1.7
+ */
+public interface MidiDeviceReceiver extends Receiver {
+    /** Obtains a MidiDevice object which is an owner of this Receiver.
+     */
+    public MidiDevice getMidiDevice();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/sound/midi/MidiDeviceTransmitter.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javax.sound.midi;
+
+
+/**
+ * <p>{@code MidiDeviceTransmitter} is a {@code Transmitter} which represents
+ * a MIDI input connector of a {@code MidiDevice}
+ * (see {@link MidiDevice#getTransmitter()}).
+ *
+ * @since 1.7
+ */
+public interface MidiDeviceTransmitter extends Transmitter {
+
+    /** Obtains a MidiDevice object which is an owner of this Transmitter.
+     */
+    public MidiDevice getMidiDevice();
+}
--- a/src/share/classes/javax/sound/midi/MidiSystem.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/sound/midi/MidiSystem.java	Fri Sep 24 16:41:32 2010 -0700
@@ -47,6 +47,8 @@
 import com.sun.media.sound.JDK13Services;
 import com.sun.media.sound.ReferenceCountingDevice;
 import com.sun.media.sound.AutoConnectSequencer;
+import com.sun.media.sound.MidiDeviceReceiverEnvelope;
+import com.sun.media.sound.MidiDeviceTransmitterEnvelope;
 
 
 /**
@@ -225,6 +227,8 @@
     /**
      * Obtains a MIDI receiver from an external MIDI port
      * or other default device.
+     * The returned receiver always implements
+     * the {@code MidiDeviceReceiver} interface.
      *
      * <p>If the system property
      * <code>javax.sound.midi.Receiver</code>
@@ -261,6 +265,9 @@
         } else {
             receiver = device.getReceiver();
         }
+        if (!(receiver instanceof MidiDeviceReceiver)) {
+            receiver = new MidiDeviceReceiverEnvelope(device, receiver);
+        }
         return receiver;
     }
 
@@ -268,6 +275,8 @@
     /**
      * Obtains a MIDI transmitter from an external MIDI port
      * or other default source.
+     * The returned transmitter always implements
+     * the {@code MidiDeviceTransmitter} interface.
      *
      * <p>If the system property
      * <code>javax.sound.midi.Transmitter</code>
@@ -301,6 +310,9 @@
         } else {
             transmitter = device.getTransmitter();
         }
+        if (!(transmitter instanceof MidiDeviceReceiver)) {
+            transmitter = new MidiDeviceTransmitterEnvelope(device, transmitter);
+        }
         return transmitter;
     }
 
--- a/src/share/classes/javax/sound/sampled/AudioFormat.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/sound/sampled/AudioFormat.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2010, Oracle and/or its affiliates. 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
@@ -431,34 +431,36 @@
 
 
     /**
-     * Indicates whether this format matches the one specified.  To match,
-     * two formats must have the same encoding, the same number of channels,
-     * and the same number of bits per sample and bytes per frame.
-     * The two formats must also have the same sample rate,
-     * unless the specified format has the sample rate value <code>AudioSystem.NOT_SPECIFIED</code>,
-     * which any sample rate will match.  The frame rates must
-     * similarly be equal, unless the specified format has the frame rate
-     * value <code>AudioSystem.NOT_SPECIFIED</code>.  The byte order (big-endian or little-endian)
-     * must match if the sample size is greater than one byte.
+     * Indicates whether this format matches the one specified.
+     * To match, two formats must have the same encoding,
+     * and consistent values of the number of channels, sample rate, sample size,
+     * frame rate, and frame size.
+     * The values of the property are consistent if they are equal
+     * or the specified format has the property value
+     * {@code AudioSystem.NOT_SPECIFIED}.
+     * The byte order (big-endian or little-endian) must be the same
+     * if the sample size is greater than one byte.
      *
      * @param format format to test for match
-     * @return <code>true</code> if this format matches the one specified,
-     * <code>false</code> otherwise.
-     */
-    /*
-     * $$kk: 04.20.99: i changed the semantics of this.
+     * @return {@code true} if this format matches the one specified,
+     *         {@code false} otherwise.
      */
     public boolean matches(AudioFormat format) {
-
-        if (format.getEncoding().equals(getEncoding()) &&
-            ( (format.getSampleRate() == (float)AudioSystem.NOT_SPECIFIED) || (format.getSampleRate() == getSampleRate()) ) &&
-            (format.getSampleSizeInBits() == getSampleSizeInBits()) &&
-            (format.getChannels() == getChannels() &&
-             (format.getFrameSize() == getFrameSize()) &&
-             ( (format.getFrameRate() == (float)AudioSystem.NOT_SPECIFIED) || (format.getFrameRate() == getFrameRate()) ) &&
-             ( (format.getSampleSizeInBits() <= 8)  || (format.isBigEndian() == isBigEndian()) ) ) )
+        if (format.getEncoding().equals(getEncoding())
+                && (format.getChannels() == AudioSystem.NOT_SPECIFIED
+                    || format.getChannels() == getChannels())
+                && (format.getSampleRate() == (float)AudioSystem.NOT_SPECIFIED
+                    || format.getSampleRate() == getSampleRate())
+                && (format.getSampleSizeInBits() == AudioSystem.NOT_SPECIFIED
+                    || format.getSampleSizeInBits() == getSampleSizeInBits())
+                && (format.getFrameRate() == (float)AudioSystem.NOT_SPECIFIED
+                    || format.getFrameRate() == getFrameRate())
+                && (format.getFrameSize() == AudioSystem.NOT_SPECIFIED
+                    || format.getFrameSize() == getFrameSize())
+                && (getSampleSizeInBits() <= 8
+                    || format.isBigEndian() == isBigEndian())) {
             return true;
-
+        }
         return false;
     }
 
@@ -552,14 +554,14 @@
      * which is simply a linear (proportional) representation of the sound
      * waveform.  With PCM, the number stored in each sample is proportional
      * to the instantaneous amplitude of the sound pressure at that point in
-     * time.  The numbers are frequently signed or unsigned integers.
+     * time.  The numbers may be signed or unsigned integers or floats.
      * Besides PCM, other encodings include mu-law and a-law, which are nonlinear
      * mappings of the sound amplitude that are often used for recording speech.
      * <p>
      * You can use a predefined encoding by referring to one of the static
      * objects created by this class, such as PCM_SIGNED or
      * PCM_UNSIGNED.  Service providers can create new encodings, such as
-     * compressed audio formats or floating-point PCM samples, and make
+     * compressed audio formats, and make
      * these available through the <code>{@link AudioSystem}</code> class.
      * <p>
      * The <code>Encoding</code> class is static, so that all
@@ -590,6 +592,13 @@
         public static final Encoding PCM_UNSIGNED = new Encoding("PCM_UNSIGNED");
 
         /**
+         * Specifies floating-point PCM data.
+         *
+         * @since 1.7
+         */
+        public static final Encoding PCM_FLOAT = new Encoding("PCM_FLOAT");
+
+        /**
          * Specifies u-law encoded data.
          */
         public static final Encoding ULAW = new Encoding("ULAW");
--- a/src/share/classes/javax/sql/CommonDataSource.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/sql/CommonDataSource.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -27,6 +27,8 @@
 
 import java.sql.SQLException;
 import java.io.PrintWriter;
+import java.sql.SQLFeatureNotSupportedException;
+import java.util.logging.Logger;
 
 /**
  * Interface that defines the methods which are common between <code>DataSource</code>,
@@ -35,79 +37,93 @@
  */
 public interface CommonDataSource {
 
-  /**
-   * <p>Retrieves the log writer for this <code>DataSource</code>
-   * object.
-   *
-   * <p>The log writer is a character output stream to which all logging
-   * and tracing messages for this data source will be
-   * printed.  This includes messages printed by the methods of this
-   * object, messages printed by methods of other objects manufactured
-   * by this object, and so on.  Messages printed to a data source
-   * specific log writer are not printed to the log writer associated
-   * with the <code>java.sql.DriverManager</code> class.  When a
-   * <code>DataSource</code> object is
-   * created, the log writer is initially null; in other words, the
-   * default is for logging to be disabled.
-   *
-   * @return the log writer for this data source or null if
-   *        logging is disabled
-   * @exception java.sql.SQLException if a database access error occurs
-   * @see #setLogWriter
-   * @since 1.4
-   */
-  java.io.PrintWriter getLogWriter() throws SQLException;
+    /**
+     * <p>Retrieves the log writer for this <code>DataSource</code>
+     * object.
+     *
+     * <p>The log writer is a character output stream to which all logging
+     * and tracing messages for this data source will be
+     * printed.  This includes messages printed by the methods of this
+     * object, messages printed by methods of other objects manufactured
+     * by this object, and so on.  Messages printed to a data source
+     * specific log writer are not printed to the log writer associated
+     * with the <code>java.sql.DriverManager</code> class.  When a
+     * <code>DataSource</code> object is
+     * created, the log writer is initially null; in other words, the
+     * default is for logging to be disabled.
+     *
+     * @return the log writer for this data source or null if
+     *        logging is disabled
+     * @exception java.sql.SQLException if a database access error occurs
+     * @see #setLogWriter
+     * @since 1.4
+     */
+    java.io.PrintWriter getLogWriter() throws SQLException;
+
+    /**
+     * <p>Sets the log writer for this <code>DataSource</code>
+     * object to the given <code>java.io.PrintWriter</code> object.
+     *
+     * <p>The log writer is a character output stream to which all logging
+     * and tracing messages for this data source will be
+     * printed.  This includes messages printed by the methods of this
+     * object, messages printed by methods of other objects manufactured
+     * by this object, and so on.  Messages printed to a data source-
+     * specific log writer are not printed to the log writer associated
+     * with the <code>java.sql.DriverManager</code> class. When a
+     * <code>DataSource</code> object is created the log writer is
+     * initially null; in other words, the default is for logging to be
+     * disabled.
+     *
+     * @param out the new log writer; to disable logging, set to null
+     * @exception SQLException if a database access error occurs
+     * @see #getLogWriter
+     * @since 1.4
+     */
+    void setLogWriter(java.io.PrintWriter out) throws SQLException;
 
-  /**
-   * <p>Sets the log writer for this <code>DataSource</code>
-   * object to the given <code>java.io.PrintWriter</code> object.
-   *
-   * <p>The log writer is a character output stream to which all logging
-   * and tracing messages for this data source will be
-   * printed.  This includes messages printed by the methods of this
-   * object, messages printed by methods of other objects manufactured
-   * by this object, and so on.  Messages printed to a data source-
-   * specific log writer are not printed to the log writer associated
-   * with the <code>java.sql.DriverManager</code> class. When a
-   * <code>DataSource</code> object is created the log writer is
-   * initially null; in other words, the default is for logging to be
-   * disabled.
-   *
-   * @param out the new log writer; to disable logging, set to null
-   * @exception SQLException if a database access error occurs
-   * @see #getLogWriter
-   * @since 1.4
-   */
-  void setLogWriter(java.io.PrintWriter out) throws SQLException;
+    /**
+     * <p>Sets the maximum time in seconds that this data source will wait
+     * while attempting to connect to a database.  A value of zero
+     * specifies that the timeout is the default system timeout
+     * if there is one; otherwise, it specifies that there is no timeout.
+     * When a <code>DataSource</code> object is created, the login timeout is
+     * initially zero.
+     *
+     * @param seconds the data source login time limit
+     * @exception SQLException if a database access error occurs.
+     * @see #getLoginTimeout
+     * @since 1.4
+     */
+    void setLoginTimeout(int seconds) throws SQLException;
 
-  /**
-   * <p>Sets the maximum time in seconds that this data source will wait
-   * while attempting to connect to a database.  A value of zero
-   * specifies that the timeout is the default system timeout
-   * if there is one; otherwise, it specifies that there is no timeout.
-   * When a <code>DataSource</code> object is created, the login timeout is
-   * initially zero.
-   *
-   * @param seconds the data source login time limit
-   * @exception SQLException if a database access error occurs.
-   * @see #getLoginTimeout
-   * @since 1.4
-   */
-  void setLoginTimeout(int seconds) throws SQLException;
+    /**
+     * Gets the maximum time in seconds that this data source can wait
+     * while attempting to connect to a database.  A value of zero
+     * means that the timeout is the default system timeout
+     * if there is one; otherwise, it means that there is no timeout.
+     * When a <code>DataSource</code> object is created, the login timeout is
+     * initially zero.
+     *
+     * @return the data source login time limit
+     * @exception SQLException if a database access error occurs.
+     * @see #setLoginTimeout
+     * @since 1.4
+     */
+    int getLoginTimeout() throws SQLException;
 
-  /**
-   * Gets the maximum time in seconds that this data source can wait
-   * while attempting to connect to a database.  A value of zero
-   * means that the timeout is the default system timeout
-   * if there is one; otherwise, it means that there is no timeout.
-   * When a <code>DataSource</code> object is created, the login timeout is
-   * initially zero.
-   *
-   * @return the data source login time limit
-   * @exception SQLException if a database access error occurs.
-   * @see #setLoginTimeout
-   * @since 1.4
-   */
-  int getLoginTimeout() throws SQLException;
+    //------------------------- JDBC 4.1 -----------------------------------
 
+    /**
+     * Return the parent Logger of all the Loggers used by this data source. This
+     * should be the Logger farthest from the root Logger that is
+     * still an ancestor of all of the Loggers used by this data source. Configuring
+     * this Logger will affect all of the log messages generated by the data source.
+     * In the worst case, this may be the root Logger.
+     *
+     * @return the parent Logger for this data source
+     * @throws SQLFeatureNotSupportedException if the data source does not use <code>java.util.logging<code>.
+     * @since 1.7
+     */
+    public Logger getParentLogger() throws SQLFeatureNotSupportedException;
 }
--- a/src/share/classes/javax/sql/rowset/CachedRowSet.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/sql/rowset/CachedRowSet.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -644,10 +644,10 @@
     * of <code>execute</code> that takes a <code>ResultSet</code> object.
     *
     * @param data the <code>ResultSet</code> object containing the data
-    *           to be read into this <code>CachedRowSet</code> object
+    * to be read into this <code>CachedRowSet</code> object
     * @throws SQLException if a null <code>ResultSet</code> object is supplied
-    *           or this <code>CachedRowSet</code> object cannot
-    *           retrieve the associated <code>ResultSetMetaData</code> object
+    * or this <code>CachedRowSet</code> object cannot
+    * retrieve the associated <code>ResultSetMetaData</code> object
     * @see #execute
     * @see java.sql.ResultSet
     * @see java.sql.ResultSetMetaData
@@ -674,10 +674,10 @@
     * to commit outstanding updates, those updates are lost.
     *
     * @param conn a standard JDBC <code>Connection</code> object with valid
-    *           properties
+    * properties
     * @throws SQLException if an invalid <code>Connection</code> object is supplied
-    *           or an error occurs in establishing the connection to the
-    *           data source
+    * or an error occurs in establishing the connection to the
+    * data source
     * @see #populate
     * @see java.sql.Connection
     */
@@ -736,8 +736,8 @@
     *
     * @throws SQLException if the cursor is on the insert row
     * @throws SyncProviderException if the underlying
-    *           synchronization provider's writer fails to write the updates
-    *           back to the data source
+    * synchronization provider's writer fails to write the updates
+    * back to the data source
     * @see #acceptChanges(java.sql.Connection)
     * @see javax.sql.RowSetWriter
     * @see javax.sql.rowset.spi.SyncFactory
@@ -807,8 +807,8 @@
     * @param con a standard JDBC <code>Connection</code> object
     * @throws SQLException if the cursor is on the insert row
     * @throws SyncProviderException if the underlying
-    *           synchronization provider's writer fails to write the updates
-    *           back to the data source
+    * synchronization provider's writer fails to write the updates
+    * back to the data source
     * @see #acceptChanges()
     * @see javax.sql.RowSetWriter
     * @see javax.sql.rowset.spi.SyncFactory
@@ -867,7 +867,7 @@
     * the rowset's Java VM resources.
     *
     * @throws SQLException if an error occurs flushing the contents of this
-    *           <code>CachedRowSet</code> object
+    * <code>CachedRowSet</code> object
     * @see javax.sql.RowSetListener#rowSetChanged
     * @see java.sql.ResultSet#close
     */
@@ -948,9 +948,9 @@
     *
     * @param idx an <code>int</code> identifying the column to be checked for updates
     * @return <code>true</code> if the designated column has been visibly updated;
-    *           <code>false</code> otherwise
+    * <code>false</code> otherwise
     * @throws SQLException if the cursor is on the insert row, before the first row,
-    *       or after the last row
+    *     or after the last row
     * @see java.sql.DatabaseMetaData#updatesAreDetected
     */
     public boolean columnUpdated(int idx) throws SQLException;
@@ -963,9 +963,9 @@
     * @param columnName a <code>String</code> object giving the name of the
     *        column to be checked for updates
     * @return <code>true</code> if the column has been visibly updated;
-    *           <code>false</code> otherwise
+    * <code>false</code> otherwise
     * @throws SQLException if the cursor is on the insert row, before the first row,
-    *       or after the last row
+    *      or after the last row
     * @see java.sql.DatabaseMetaData#updatesAreDetected
     */
     public boolean columnUpdated(String columnName) throws SQLException;
@@ -1003,7 +1003,7 @@
     * <P>
     *
     * @return a <code>Collection</code> object that contains the values in
-    *           each row in this <code>CachedRowSet</code> object
+    * each row in this <code>CachedRowSet</code> object
     * @throws SQLException if an error occurs generating the collection
     * @see #toCollection(int)
     * @see #toCollection(String)
@@ -1030,10 +1030,10 @@
     * @param column an <code>int</code> indicating the column whose values
     *        are to be represented in a <code>Collection</code> object
     * @return a <code>Collection</code> object that contains the values
-    *           stored in the specified column of this <code>CachedRowSet</code>
-    *           object
+    * stored in the specified column of this <code>CachedRowSet</code>
+    * object
     * @throws SQLException if an error occurs generating the collection or
-    *           an invalid column id is provided
+    * an invalid column id is provided
     * @see #toCollection
     * @see #toCollection(String)
     */
@@ -1059,10 +1059,10 @@
     * @param column a <code>String</code> object giving the name of the
     *        column whose values are to be represented in a collection
     * @return a <code>Collection</code> object that contains the values
-    *           stored in the specified column of this <code>CachedRowSet</code>
-    *           object
+    * stored in the specified column of this <code>CachedRowSet</code>
+    * object
     * @throws SQLException if an error occurs generating the collection or
-    *           an invalid column id is provided
+    * an invalid column id is provided
     * @see #toCollection
     * @see #toCollection(int)
     */
@@ -1100,7 +1100,7 @@
     * @return the <code>SyncProvider</code> object that was set when the rowset
     *      was instantiated, or if none was was set, the default provider
     * @throws SQLException if an error occurs while returning the
-    *           <code>SyncProvider</code> object
+    * <code>SyncProvider</code> object
     * @see #setSyncProvider
     */
     public SyncProvider getSyncProvider() throws SQLException;
@@ -1127,7 +1127,7 @@
     * @param provider a <code>String</code> object giving the fully qualified class
     *        name of a <code>SyncProvider</code> implementation
     * @throws SQLException if an error occurs while attempting to reset the
-    *           <code>SyncProvider</code> implementation
+    * <code>SyncProvider</code> implementation
     * @see #getSyncProvider
     */
     public void setSyncProvider(String provider) throws SQLException;
@@ -1152,9 +1152,9 @@
     * object to the rowset.
     *
     * @param md a <code>RowSetMetaData</code> object containing
-    *           metadata about the columns in this <code>CachedRowSet</code> object
+    * metadata about the columns in this <code>CachedRowSet</code> object
     * @throws SQLException if invalid metadata is supplied to the
-    *           rowset
+    * rowset
     */
     public void setMetaData(RowSetMetaData md) throws SQLException;
 
@@ -1183,7 +1183,7 @@
     * @return a <code>ResultSet</code> object that contains the original value for
     *         this <code>CachedRowSet</code> object
     * @throws SQLException if an error occurs producing the
-    *           <code>ResultSet</code> object
+    * <code>ResultSet</code> object
     */
    public ResultSet getOriginal() throws SQLException;
 
@@ -1217,7 +1217,7 @@
     * A call to <code>setOriginalRow</code> is irreversible.
     *
     * @throws SQLException if there is no current row or an error is
-    *           encountered resetting the contents of the original row
+    * encountered resetting the contents of the original row
     * @see #getOriginalRow
     */
     public void setOriginalRow() throws SQLException;
@@ -1326,7 +1326,7 @@
     *         as this <code>CachedRowSet</code> object and that has a cursor over
     *         the same data
     * @throws SQLException if an error occurs or cloning is not
-    *           supported in the underlying platform
+    * supported in the underlying platform
     * @see javax.sql.RowSetEvent
     * @see javax.sql.RowSetListener
     */
@@ -1344,10 +1344,10 @@
     * established must be maintained.
     *
     * @return a new <code>RowSet</code> object that is a deep copy
-    *         of this <code>CachedRowSet</code> object and is
-    *         completely independent of this <code>CachedRowSet</code> object
+    * of this <code>CachedRowSet</code> object and is
+    * completely independent of this <code>CachedRowSet</code> object
     * @throws SQLException if an error occurs in generating the copy of
-    *         the of this <code>CachedRowSet</code> object
+    * the of this <code>CachedRowSet</code> object
     * @see #createShared
     * @see #createCopySchema
     * @see #createCopyNoConstraints
@@ -1396,10 +1396,10 @@
      * in the copy.
      *
      * @return a new <code>CachedRowSet</code> object that is a deep copy
-     *        of this <code>CachedRowSet</code> object and is
-     *        completely independent of this  <code>CachedRowSet</code> object
+     *     of this <code>CachedRowSet</code> object and is
+     *     completely independent of this  <code>CachedRowSet</code> object
      * @throws SQLException if an error occurs in generating the copy of
-     *        the of this <code>CachedRowSet</code> object
+     *     the of this <code>CachedRowSet</code> object
      * @see #createCopy
      * @see #createShared
      * @see #createCopySchema
@@ -1445,7 +1445,7 @@
      * @return <code>true</code> if deleted rows are visible;
      *         <code>false</code> otherwise
      * @throws SQLException if a rowset implementation is unable to
-     *          to determine whether rows marked for deletion are visible
+     * to determine whether rows marked for deletion are visible
      * @see #setShowDeleted
      */
     public boolean getShowDeleted() throws SQLException;
@@ -1467,7 +1467,7 @@
      * @param b <code>true</code> if deleted rows should be shown;
      *              <code>false</code> otherwise
      * @exception SQLException if a rowset implementation is unable to
-     *          to reset whether deleted rows should be visible
+     * to reset whether deleted rows should be visible
      * @see #getShowDeleted
      */
     public void setShowDeleted(boolean b) throws SQLException;
@@ -1523,9 +1523,12 @@
      * set to false, the changes will <b>not</b> be committed until one of the
      * <code>CachedRowSet</code> interface transaction methods is called.
      *
+     * @deprecated Because this field is final (it is part of an interface),
+     *  its value cannot be changed.
      * @see #commit
      * @see #rollback
      */
+    @Deprecated
     public static final boolean COMMIT_ON_ACCEPT_CHANGES = true;
 
     /**
@@ -1562,10 +1565,10 @@
      * @param startRow the position in the <code>ResultSet</code> from where to start
      *                populating the records in this <code>CachedRowSet</code>
      * @param rs the <code>ResultSet</code> object containing the data
-     *          to be read into this <code>CachedRowSet</code> object
+     * to be read into this <code>CachedRowSet</code> object
      * @throws SQLException if a null <code>ResultSet</code> object is supplied
-     *          or this <code>CachedRowSet</code> object cannot
-     *          retrieve the associated <code>ResultSetMetaData</code> object
+     * or this <code>CachedRowSet</code> object cannot
+     * retrieve the associated <code>ResultSetMetaData</code> object
      * @see #execute
      * @see #populate(ResultSet)
      * @see java.sql.ResultSet
@@ -1620,3 +1623,4 @@
     public boolean previousPage() throws SQLException;
 
 }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/sql/rowset/RowSetFactory.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javax.sql.rowset;
+
+import java.sql.SQLException;
+
+/**
+ * An interface that defines the implementation of a factory that is used
+ * to obtain different types of {@code RowSet} implementations.
+ *
+ * @author Lance Andersen
+ * @since 1.7
+ */
+public interface RowSetFactory{
+
+    /**
+     * <p>Creates a new instance of a CachedRowSet.</p>
+     *
+     * @return A new instance of a CachedRowSet.
+     *
+     * @throws SQLException if a CachedRowSet cannot
+     *   be created.
+     *
+     * @since 1.7
+     */
+    public CachedRowSet createCachedRowSet() throws SQLException;
+
+    /**
+     * <p>Creates a new instance of a FilteredRowSet.</p>
+     *
+     * @return A new instance of a FilteredRowSet.
+     *
+     * @throws SQLException if a FilteredRowSet cannot
+     *   be created.
+     *
+     * @since 1.7
+     */
+    public FilteredRowSet createFilteredRowSet() throws SQLException;
+
+    /**
+     * <p>Creates a new instance of a JdbcRowSet.</p>
+     *
+     * @return A new instance of a JdbcRowSet.
+     *
+     * @throws SQLException if a JdbcRowSet cannot
+     *   be created.
+     *
+     * @since 1.7
+     */
+    public  JdbcRowSet createJdbcRowSet() throws SQLException;
+
+    /**
+     * <p>Creates a new instance of a JoinRowSet.</p>
+     *
+     * @return A new instance of a JoinRowSet.
+     *
+     * @throws SQLException if a JoinRowSet cannot
+     *   be created.
+     *
+     * @since 1.7
+     */
+    public  JoinRowSet createJoinRowSet() throws SQLException;
+
+    /**
+     * <p>Creates a new instance of a WebRowSet.</p>
+     *
+     * @return A new instance of a WebRowSet.
+     *
+     * @throws SQLException if a WebRowSet cannot
+     *   be created.
+     *
+     * @since 1.7
+     */
+    public  WebRowSet createWebRowSet() throws SQLException;
+
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/javax/sql/rowset/RowSetProvider.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,305 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javax.sql.rowset;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.sql.SQLException;
+import java.util.ServiceLoader;
+import javax.sql.rowset.RowSetFactory;
+
+/**
+ * A factory API that enables applications to obtain a
+ * {@code RowSetFactory} implementation  that can be used to create different
+ * types of {@code RowSet} implementations.
+ * <p>
+ * Example:
+ * </p>
+ * <pre>
+ * RowSetFactory aFactory = RowSetProvider.newFactory();
+ * CachedRowSet crs = aFactory.createCachedRowSet();
+ * ...
+ * RowSetFactory rsf = RowSetProvider.newFactory("com.sun.rowset.RowSetFactoryImpl", null);
+ * WebRowSet wrs = rsf.createWebRowSet();
+ * </pre>
+ *<p>
+ * Tracing of this class may be enabled by setting the System property
+ * {@code javax.sql.rowset.RowSetFactory.debug} to any value but {@code false}.
+ * </p>
+ *
+ * @author Lance Andersen
+ * @since 1.7
+ */
+public class RowSetProvider {
+
+    private static final String ROWSET_DEBUG_PROPERTY = "javax.sql.rowset.RowSetProvider.debug";
+    private static final String ROWSET_FACTORY_IMPL = "com.sun.rowset.RowSetFactoryImpl";
+    private static final String ROWSET_FACTORY_NAME = "javax.sql.rowset.RowSetFactory";
+    /**
+     * Internal debug flag.
+     */
+    private static boolean debug = true;
+
+
+    static {
+        // Check to see if the debug property is set
+        String val = getSystemProperty(ROWSET_DEBUG_PROPERTY);
+        // Allow simply setting the prop to turn on debug
+        debug = val != null && !"false".equals(val);
+    }
+
+
+    protected RowSetProvider () {
+    }
+
+    /**
+     * <p>Creates a new instance of a <code>RowSetFactory</code>
+     * implementation.  This method uses the following
+     * look up order to determine
+     * the <code>RowSetFactory</code> implementation class to load:</p>
+     * <ul>
+     * <li>
+     * The System property {@code javax.sql.rowset.RowsetFactory}.  For example:
+     * <ul>
+     * <li>
+     * -Djavax.sql.rowset.RowsetFactory=com.sun.rowset.RowSetFactoryImpl
+     * </li>
+     * </ul>
+     * <li>
+     * The ServiceLocator API. The ServiceLocator API will look
+     * for a classname in the file
+     * {@code META-INF/services/javax.sql.rowset.RowSetFactory}
+     * in jars available to the runtime. For example, to have the the RowSetFactory
+     * implementation {@code com.sun.rowset.RowSetFactoryImpl } loaded, the
+     * entry in {@code META-INF/services/javax.sql.rowset.RowSetFactory} would be:
+     *  <ul>
+     * <li>
+     * {@code com.sun.rowset.RowSetFactoryImpl }
+     * </li>
+     * </ul>
+     * </li>
+     * <li>
+     * Platform default <code>RowSetFactory</code> instance.
+     * </li>
+     * </ul>
+     *
+     * <p>Once an application has obtained a reference to a {@code RowSetFactory},
+     * it can use the factory to obtain RowSet instances.</p>
+     *
+     * @return New instance of a <code>RowSetFactory</code>
+     *
+     * @throws SQLException if the default factory class cannot be loaded,
+     * instantiated. The cause will be set to actual Exception
+     *
+     * @see ServiceLoader
+     * @since 1.7
+     */
+    public static RowSetFactory newFactory()
+            throws SQLException {
+        // Use the system property first
+        RowSetFactory factory = null;
+        String factoryClassName = null;
+        try {
+            trace("Checking for Rowset System Property...");
+            factoryClassName = getSystemProperty(ROWSET_FACTORY_NAME);
+            if (factoryClassName != null) {
+                trace("Found system property, value=" + factoryClassName);
+                factory = (RowSetFactory) getFactoryClass(factoryClassName, null, true).newInstance();
+            }
+        } catch (ClassNotFoundException e) {
+            throw new SQLException(
+                    "RowSetFactory: " + factoryClassName + " not found", e);
+        } catch (Exception e) {
+            throw new SQLException(
+                    "RowSetFactory: " + factoryClassName + " could not be instantiated: " + e,
+                    e);
+        }
+
+        // Check to see if we found the RowSetFactory via a System property
+        if (factory == null) {
+            // If the RowSetFactory is not found via a System Property, now
+            // look it up via the ServiceLoader API and if not found, use the
+            // Java SE default.
+            factory = loadViaServiceLoader();
+            factory =
+                    factory == null ? newFactory(ROWSET_FACTORY_IMPL, null) : factory;
+        }
+        return (factory);
+    }
+
+    /**
+     * <p>Creates  a new instance of a <code>RowSetFactory</code> from the
+     * specified factory class name.
+     * This function is useful when there are multiple providers in the classpath.
+     * It gives more control to the application as it can specify which provider
+     * should be loaded.</p>
+     *
+     * <p>Once an application has obtained a reference to a <code>RowSetFactory</code>
+     * it can use the factory to obtain RowSet instances.</p>
+     *
+     * @param factoryClassName fully qualified factory class name that
+     * provides  an implementation of <code>javax.sql.rowset.RowSetFactory</code>.
+     *
+     * @param cl <code>ClassLoader</code> used to load the factory
+     * class. If <code>null</code> current <code>Thread</code>'s context
+     * classLoader is used to load the factory class.
+     *
+     * @return New instance of a <code>RowSetFactory</code>
+     *
+     * @throws SQLException if <code>factoryClassName</code> is
+     * <code>null</code>, or the factory class cannot be loaded, instantiated.
+     *
+     * @see #newFactory()
+     *
+     * @since 1.7
+     */
+    public static RowSetFactory newFactory(String factoryClassName, ClassLoader cl)
+            throws SQLException {
+
+        trace("***In newInstance()");
+        try {
+            Class providerClass = getFactoryClass(factoryClassName, cl, false);
+            RowSetFactory instance = (RowSetFactory) providerClass.newInstance();
+            if (debug) {
+                trace("Created new instance of " + providerClass +
+                        " using ClassLoader: " + cl);
+            }
+            return instance;
+        } catch (ClassNotFoundException x) {
+            throw new SQLException(
+                    "Provider " + factoryClassName + " not found", x);
+        } catch (Exception x) {
+            throw new SQLException(
+                    "Provider " + factoryClassName + " could not be instantiated: " + x,
+                    x);
+        }
+    }
+
+    /*
+     * Returns the class loader to be used.
+     * @return The ClassLoader to use.
+     *
+     */
+    static private ClassLoader getContextClassLoader() throws SecurityException {
+        return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
+
+            public Object run() {
+                ClassLoader cl = null;
+
+                cl = Thread.currentThread().getContextClassLoader();
+
+                if (cl == null) {
+                    cl = ClassLoader.getSystemClassLoader();
+                }
+
+                return cl;
+            }
+        });
+    }
+
+    /**
+     * Attempt to load a class using the class loader supplied. If that fails
+     * and fall back is enabled, the current (i.e. bootstrap) class loader is
+     * tried.
+     *
+     * If the class loader supplied is <code>null</code>, first try using the
+     * context class loader followed by the current class loader.
+     *  @return The class which was loaded
+     */
+    static private Class getFactoryClass(String factoryClassName, ClassLoader cl,
+            boolean doFallback) throws ClassNotFoundException {
+        try {
+            if (cl == null) {
+                cl = getContextClassLoader();
+                if (cl == null) {
+                    throw new ClassNotFoundException();
+                } else {
+                    return cl.loadClass(factoryClassName);
+                }
+            } else {
+                return cl.loadClass(factoryClassName);
+            }
+        } catch (ClassNotFoundException e) {
+            if (doFallback) {
+                // Use current class loader
+                return Class.forName(factoryClassName, true, RowSetFactory.class.getClassLoader());
+            } else {
+                throw e;
+            }
+        }
+    }
+
+    /**
+     * Use the ServiceLoader mechanism to load  the default RowSetFactory
+     * @return default RowSetFactory Implementation
+     */
+    static private RowSetFactory loadViaServiceLoader() {
+        RowSetFactory theFactory = null;
+        trace("***in loadViaServiceLoader()");
+        for (RowSetFactory factory : ServiceLoader.load(javax.sql.rowset.RowSetFactory.class)) {
+            trace(" Loading done by the java.util.ServiceLoader :" + factory.getClass().getName());
+            theFactory = factory;
+            break;
+        }
+        return theFactory;
+
+    }
+
+    /**
+     * Returns the requested System Property.  If a {@code SecurityException}
+     * occurs, just return NULL
+     * @param propName - System property to retreive
+     * @return The System property value or NULL if the property does not exist
+     * or a {@code SecurityException} occurs.
+     */
+    static private String getSystemProperty(final String propName) {
+        String property = null;
+        try {
+            property = (String) AccessController.doPrivileged(new PrivilegedAction() {
+
+                public Object run() {
+                    return System.getProperty(propName);
+                }
+            });
+        } catch (SecurityException se) {
+            if (debug) {
+                se.printStackTrace();
+            }
+        }
+        return property;
+    }
+
+    /**
+     * Debug routine which will output tracing if the System Property
+     * -Djavax.sql.rowset.RowSetFactory.debug is set
+     * @param msg - The debug message to display
+     */
+    private static void trace(String msg) {
+        if (debug) {
+            System.err.println("###RowSets: " + msg);
+        }
+    }
+}
--- a/src/share/classes/javax/sql/rowset/package.html	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/sql/rowset/package.html	Fri Sep 24 16:41:32 2010 -0700
@@ -5,7 +5,7 @@
   <meta http-equiv="Content-Type"
  content="text/html; charset=iso-8859-1">
 <!--
-Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -78,7 +78,7 @@
 data structure as defined in the JDBC 3.0 specification.
 <p>
 <li><a href="CachedRowSet.html">
-<b><code>CachedRowSet</code><sup><font size=-2>TM></font></sup</b></a> 
+<b><code>CachedRowSet</code>&trade;</b></a>
  - A <tt>CachedRowSet</tt> object is a JavaBeans<sup><font size=-2>TM</font></sup>
  component that is scrollable, updatable, serializable, and generally disconnected from
  the source of its data. A <tt>CachedRowSet</tt> object
@@ -148,7 +148,12 @@
 on <a href="spi/SyncProvider.html"><code>SyncProvider</code></a> implementations.
 <p>
 <ul>
-<li><b>3.1 Role of the <code>BaseRowSet</code> Class</b>
+<li><b>3.1 Constructor</b>
+<p>
+    All <code>RowSet</code> implementations <strong>must</strong> provide a
+no-argument constructor.
+</li>
+<li><b>3.2 Role of the <code>BaseRowSet</code> Class</b>
 <p>
 A compliant JDBC <code>RowSet</code> implementation <b>must</b> implement one or more 
 standard interfaces specified in this package and and <b>may</b> extend the 
@@ -215,7 +220,7 @@
     </table>
     </blockquote>
 <p>
-<li><b>3.2 Connected RowSet Requirements</b> 
+<li><b>3.3 Connected RowSet Requirements</b>
 <p>
 The <code>JdbcRowSet</code> describes a <code>RowSet</code> object that <b>must</b> always
 be connected to the originating data source. Implementations of the <code>JdbcRowSet</code>
@@ -229,7 +234,7 @@
 <p>
 
 <li>
-<b>3.3 Disconnected RowSet Requirements</b> 
+<b>3.4 Disconnected RowSet Requirements</b>
 <p> 
 A disconnected <code>RowSet</code> object, such as a <code>CachedRowSet</code> object, 
 <b>should</b> delegate  
@@ -244,7 +249,7 @@
 therefore ensure that no 
 extraneous references remain on the <code>Connection</code> object.
 <p>
-<li><b>3.4 Role of RowSetMetaDataImpl</b>
+<li><b>3.5 Role of RowSetMetaDataImpl</b>
 <p>
 The <code>RowsetMetaDataImpl</code> class is a utility class that provides an implementation of the
 <a href="../RowSetMetaData.html">RowSetMetaData</a> interface, supplying standard setter
@@ -252,7 +257,7 @@
 <code>RowSet</code> objects. All implementations are free to use this standard
 implementation but are not required to do so.
 <p>
-<li><b>3.5 RowSetWarning Class</b>
+<li><b>3.6 RowSetWarning Class</b>
 <p>
 The <code>RowSetWarning</code> class provides warnings that can be set
 on <code>RowSet</code> implementations.
@@ -270,7 +275,7 @@
 
 
 <P>
-<li><b>3.6 The Joinable Interface</b>
+<li><b>3.7 The Joinable Interface</b>
 <P>
 The <code>Joinable</code> interface provides both connected and disconnected 
 <code>RowSet</code> objects with the capability to be added to a 
@@ -278,7 +283,14 @@
 A <code>RowSet</code> object that has  implemented the <code>Joinable</code> 
 interface can set a match column, retrieve a match column, or unset a match column.
 A <code>JoinRowSet</code> object can then use the <code>RowSet</code> object's
-match column as a basis for adding the <code>RowSet</code> object. 
+match column as a basis for adding the <code>RowSet</code> object.
+</li>
+
+<li><b>3.8 The RowSetFactory Interface</b>
+    <p>
+        A <code>RowSetFactory</code> implementation <strong>must</strong>
+        be provided.
+</li>
 </ul>
 
 <h3><a name="relspec">4.0 Related Specifications</a></h3>
--- a/src/share/classes/javax/sql/rowset/spi/SyncFactory.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/sql/rowset/spi/SyncFactory.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -25,13 +25,6 @@
 
 package javax.sql.rowset.spi;
 
-import java.util.Map;
-import java.util.Hashtable;
-import java.util.Enumeration;
-import java.util.Vector;
-import java.util.Properties;
-import java.util.Collection;
-import java.util.StringTokenizer;
 import java.util.logging.*;
 import java.util.*;
 
@@ -216,68 +209,64 @@
      * Having a private constructor guarantees that no more than
      * one <code>SyncProvider</code> object can exist at a time.
      */
-    private SyncFactory() {};
+    private SyncFactory() {
+    }
 
     /**
      * The standard property-id for a synchronization provider implementation
      * name.
      */
-    public static String ROWSET_SYNC_PROVIDER =
-        "rowset.provider.classname";
-
+    public static final String ROWSET_SYNC_PROVIDER =
+            "rowset.provider.classname";
     /**
      * The standard property-id for a synchronization provider implementation
      * vendor name.
      */
-    public static String ROWSET_SYNC_VENDOR =
-        "rowset.provider.vendor";
-
+    public static final String ROWSET_SYNC_VENDOR =
+            "rowset.provider.vendor";
     /**
      * The standard property-id for a synchronization provider implementation
      * version tag.
      */
-    public static String ROWSET_SYNC_PROVIDER_VERSION =
-        "rowset.provider.version";
-
+    public static final String ROWSET_SYNC_PROVIDER_VERSION =
+            "rowset.provider.version";
     /**
      * The standard resource file name.
      */
     private static String ROWSET_PROPERTIES = "rowset.properties";
-
     /**
      * The RI Optimistic Provider.
      */
     private static String default_provider =
-        "com.sun.rowset.providers.RIOptimisticProvider";
-
+            "com.sun.rowset.providers.RIOptimisticProvider";
+    /**
+     *  Permission required to invoke setJNDIContext and setLogger
+     */
+    private static final SQLPermission SET_SYNCFACTORY_PERMISSION =
+            new SQLPermission("setSyncFactory");
     /**
      * The initial JNDI context where <code>SyncProvider</code> implementations can
      * be stored and from which they can be invoked.
      */
     private static Context ic;
-
     /**
      * The <code>Logger</code> object to be used by the <code>SyncFactory</code>.
      */
     private static Logger rsLogger;
-
     /**
      *
      */
     private static Level rsLevel;
-
     /**
      * The registry of available <code>SyncProvider</code> implementations.
      * See section 2.0 of the class comment for <code>SyncFactory</code> for an
      * explanation of how a provider can be added to this registry.
      */
     private static Hashtable implementations;
-
     /**
      * Internal sync object used to maintain the SPI as a singleton
      */
     private static Object logSync = new Object();
-
     /**
      * Internal PrintWriter field for logging facility
      */
@@ -311,7 +300,7 @@
      * @see #setJNDIContext
      */
     public static synchronized void registerProvider(String providerID)
-        throws SyncFactoryException {
+            throws SyncFactoryException {
 
         ProviderImpl impl = new ProviderImpl();
         impl.setClassname(providerID);
@@ -325,29 +314,29 @@
      *
      * @return the <code>SyncFactory</code> instance
      */
-     public static SyncFactory getSyncFactory(){
+    public static SyncFactory getSyncFactory() {
 
-         // This method uses the Singleton Design Pattern
-         // with Double-Checked Locking Pattern for
-         // 1. Creating single instance of the SyncFactory
-         // 2. Make the class thread safe, so that at one time
-         //    only one thread enters the synchronized block
-         //    to instantiate.
+        // This method uses the Singleton Design Pattern
+        // with Double-Checked Locking Pattern for
+        // 1. Creating single instance of the SyncFactory
+        // 2. Make the class thread safe, so that at one time
+        //    only one thread enters the synchronized block
+        //    to instantiate.
 
-         // if syncFactory object is already there
-         // don't go into synchronized block and return
-         // that object.
-         // else go into synchronized block
+        // if syncFactory object is already there
+        // don't go into synchronized block and return
+        // that object.
+        // else go into synchronized block
 
-         if(syncFactory == null){
-             synchronized(SyncFactory.class) {
-                if(syncFactory == null){
+        if (syncFactory == null) {
+            synchronized (SyncFactory.class) {
+                if (syncFactory == null) {
                     syncFactory = new SyncFactory();
                 } //end if
-             } //end synchronized block
-         } //end if
-         return syncFactory;
-     }
+            } //end synchronized block
+        } //end if
+        return syncFactory;
+    }
 
     /**
      * Removes the designated currently registered synchronization provider from the
@@ -358,13 +347,12 @@
      * unregister a SyncProvider implementation that was not registered.
      */
     public static synchronized void unregisterProvider(String providerID)
-        throws SyncFactoryException {
+            throws SyncFactoryException {
         initMapIfNecessary();
         if (implementations.containsKey(providerID)) {
             implementations.remove(providerID);
         }
     }
-
     private static String colon = ":";
     private static String strFileSep = "/";
 
@@ -395,7 +383,7 @@
                  * Dependent on application
                  */
                 String strRowsetProperties = System.getProperty("rowset.properties");
-                if ( strRowsetProperties != null) {
+                if (strRowsetProperties != null) {
                     // Load user's implementation of SyncProvider
                     // here. -Drowset.properties=/abc/def/pqr.txt
                     ROWSET_PROPERTIES = strRowsetProperties;
@@ -407,8 +395,8 @@
                  * Always available
                  */
                 ROWSET_PROPERTIES = "javax" + strFileSep + "sql" +
-                    strFileSep + "rowset" + strFileSep +
-                    "rowset.properties";
+                        strFileSep + "rowset" + strFileSep +
+                        "rowset.properties";
                 // properties.load(
                 //                ClassLoader.getSystemResourceAsStream(ROWSET_PROPERTIES));
 
@@ -417,7 +405,7 @@
                 properties.load(cl.getResourceAsStream(ROWSET_PROPERTIES));
                 parseProperties(properties);
 
-                // removed else, has properties should sum together
+            // removed else, has properties should sum together
 
             } catch (FileNotFoundException e) {
                 throw new SyncFactoryException("Cannot locate properties file: " + e);
@@ -447,18 +435,15 @@
             }
         }
     }
-
     /**
      * The internal boolean switch that indicates whether a JNDI
      * context has been established or not.
      */
     private static boolean jndiCtxEstablished = false;
-
     /**
      * The internal debug switch.
      */
     private static boolean debug = false;
-
     /**
      * Internal registry count for the number of providers contained in the
      * registry.
@@ -475,9 +460,9 @@
         String key = null;
         String[] propertyNames = null;
 
-        for (Enumeration e = p.propertyNames(); e.hasMoreElements() ;) {
+        for (Enumeration e = p.propertyNames(); e.hasMoreElements();) {
 
-            String str = (String)e.nextElement();
+            String str = (String) e.nextElement();
 
             int w = str.length();
 
@@ -491,7 +476,7 @@
                     propertyNames = getPropertyNames(false);
                 } else {
                     // property index has been set.
-                    propertyNames = getPropertyNames(true, str.substring(w-1));
+                    propertyNames = getPropertyNames(true, str.substring(w - 1));
                 }
 
                 key = p.getProperty(propertyNames[0]);
@@ -515,17 +500,17 @@
      * overloaded property names that contain indexes.
      */
     private static String[] getPropertyNames(boolean append,
-                                             String propertyIndex) {
+            String propertyIndex) {
         String dot = ".";
         String[] propertyNames =
-            new String[] {SyncFactory.ROWSET_SYNC_PROVIDER,
-                              SyncFactory.ROWSET_SYNC_VENDOR,
-                              SyncFactory.ROWSET_SYNC_PROVIDER_VERSION};
+                new String[]{SyncFactory.ROWSET_SYNC_PROVIDER,
+            SyncFactory.ROWSET_SYNC_VENDOR,
+            SyncFactory.ROWSET_SYNC_PROVIDER_VERSION};
         if (append) {
             for (int i = 0; i < propertyNames.length; i++) {
                 propertyNames[i] = propertyNames[i] +
-                    dot +
-                    propertyIndex;
+                        dot +
+                        propertyIndex;
             }
             return propertyNames;
         } else {
@@ -549,15 +534,21 @@
      *
      * @param providerID the unique identifier of the provider
      * @return a <code>SyncProvider</code> implementation
-     * @throws SyncFactoryException If the SyncProvider cannot be found or
+     * @throws SyncFactoryException If the SyncProvider cannot be found,
+     * the providerID is {@code null}, or
      * some error was encountered when trying to invoke this provider.
      */
     public static SyncProvider getInstance(String providerID)
-        throws SyncFactoryException {
+            throws SyncFactoryException {
+
+        if(providerID == null) {
+            throw new SyncFactoryException("The providerID cannot be null");
+        }
+
         initMapIfNecessary(); // populate HashTable
         initJNDIContext();    // check JNDI context for any additional bindings
 
-        ProviderImpl impl = (ProviderImpl)implementations.get(providerID);
+        ProviderImpl impl = (ProviderImpl) implementations.get(providerID);
 
         if (impl == null) {
             // Requested SyncProvider is unavailable. Return default provider.
@@ -575,11 +566,10 @@
              * this SyncFactory and try to laod the SyncProvider class from
              * there.
              **/
-
             c = Class.forName(providerID, true, cl);
 
             if (c != null) {
-                return (SyncProvider)c.newInstance();
+                return (SyncProvider) c.newInstance();
             } else {
                 return new com.sun.rowset.providers.RIOptimisticProvider();
             }
@@ -592,6 +582,7 @@
             throw new SyncFactoryException("ClassNotFoundException: " + e.getMessage());
         }
     }
+
     /**
      * Returns an Enumeration of currently registered synchronization
      * providers.  A <code>RowSet</code> implementation may use any provider in
@@ -605,7 +596,7 @@
      * providers that are registered with this Factory
      */
     public static Enumeration<SyncProvider> getRegisteredProviders()
-        throws SyncFactoryException {
+            throws SyncFactoryException {
         initMapIfNecessary();
         // return a collection of classnames
         // of type SyncProvider
@@ -618,10 +609,26 @@
      * <code>SyncProvider</code> implementations can log their events to
      * this object and the application can retrieve a handle to this
      * object using the <code>getLogger</code> method.
+     * <p>
+     * This method checks to see that there is an {@code SQLPermission}
+     * object  which grants the permission {@code setSyncFactory}
+     * before allowing the method to succeed.  If a
+     * {@code SecurityManager} exists and its
+     * {@code checkPermission} method denies calling {@code setLogger},
+     * this method throws a
+     * {@code java.lang.SecurityException}.
      *
      * @param logger A Logger object instance
+     * @throws java.lang.SecurityException if a security manager exists and its
+     *   {@code checkPermission} method denies calling {@code setLogger}
+     * @see SecurityManager#checkPermission
      */
     public static void setLogger(Logger logger) {
+
+        SecurityManager sec = System.getSecurityManager();
+        if (sec != null) {
+            sec.checkPermission(SET_SYNCFACTORY_PERMISSION);
+        }
         rsLogger = logger;
     }
 
@@ -631,14 +638,28 @@
      * <code>SyncProvider</code> implementations can log their events
      * to this object and the application can retrieve a handle to this
      * object using the <code>getLogger</code> method.
+     * <p>
+     * This method checks to see that there is an {@code SQLPermission}
+     * object  which grants the permission {@code setSyncFactory}
+     * before allowing the method to succeed.  If a
+     * {@code SecurityManager} exists and its
+     * {@code checkPermission} method denies calling {@code setLogger},
+     * this method throws a
+     * {@code java.lang.SecurityException}.
      *
      * @param logger a Logger object instance
      * @param level a Level object instance indicating the degree of logging
      * required
+     * @throws java.lang.SecurityException if a security manager exists and its
+     *   {@code checkPermission} method denies calling {@code setLogger}
+     * @see SecurityManager#checkPermission
      */
     public static void setLogger(Logger logger, Level level) {
         // singleton
-
+        SecurityManager sec = System.getSecurityManager();
+        if (sec != null) {
+            sec.checkPermission(SET_SYNCFACTORY_PERMISSION);
+        }
         rsLogger = logger;
         rsLogger.setLevel(level);
     }
@@ -651,27 +672,42 @@
      */
     public static Logger getLogger() throws SyncFactoryException {
         // only one logger per session
-        if(rsLogger == null){
-           throw new SyncFactoryException("(SyncFactory) : No logger has been set");
+        if (rsLogger == null) {
+            throw new SyncFactoryException("(SyncFactory) : No logger has been set");
         }
         return rsLogger;
     }
 
-   /**
-    * Sets the initial JNDI context from which SyncProvider implementations
-    * can be retrieved from a JNDI namespace
-    *
-    * @param ctx a valid JNDI context
-    * @throws SyncFactoryException if the supplied JNDI context is null
-    */
+    /**
+     * Sets the initial JNDI context from which SyncProvider implementations
+     * can be retrieved from a JNDI namespace
+     * <p>
+     *  This method checks to see that there is an {@code SQLPermission}
+     * object  which grants the permission {@code setSyncFactory}
+     * before allowing the method to succeed.  If a
+     * {@code SecurityManager} exists and its
+     * {@code checkPermission} method denies calling {@code setJNDIContext},
+     * this method throws a
+     * {@code java.lang.SecurityException}.
+     *
+     * @param ctx a valid JNDI context
+     * @throws SyncFactoryException if the supplied JNDI context is null
+     * @throws java.lang.SecurityException if a security manager exists and its
+     *  {@code checkPermission} method denies calling {@code setJNDIContext}
+     * @see SecurityManager#checkPermission
+     */
     public static void setJNDIContext(javax.naming.Context ctx)
-        throws SyncFactoryException {
+            throws SyncFactoryException {
+        SecurityManager sec = System.getSecurityManager();
+        if (sec != null) {
+            sec.checkPermission(SET_SYNCFACTORY_PERMISSION);
+        }
         if (ctx == null) {
             throw new SyncFactoryException("Invalid JNDI context supplied");
         }
         ic = ctx;
         jndiCtxEstablished = true;
-   }
+    }
 
     /**
      * Controls JNDI context intialization.
@@ -689,7 +725,7 @@
                 throw new SyncFactoryException("SPI: NamingException: " + e.getExplanation());
             } catch (Exception e) {
                 e.printStackTrace();
-        throw new SyncFactoryException("SPI: Exception: " + e.getMessage());
+                throw new SyncFactoryException("SPI: Exception: " + e.getMessage());
             }
         }
     }
@@ -720,7 +756,7 @@
      * bindings have been enumerated.
      */
     private static void enumerateBindings(NamingEnumeration bindings,
-        Properties properties) throws NamingException {
+            Properties properties) throws NamingException {
 
         boolean syncProviderObj = false; // move to parameters ?
 
@@ -729,21 +765,21 @@
             Object elementObj = null;
             String element = null;
             while (bindings.hasMore()) {
-                bd = (Binding)bindings.next();
+                bd = (Binding) bindings.next();
                 element = bd.getName();
                 elementObj = bd.getObject();
 
                 if (!(ic.lookup(element) instanceof Context)) {
-                     // skip directories/sub-contexts
-                     if (ic.lookup(element) instanceof SyncProvider) {
+                    // skip directories/sub-contexts
+                    if (ic.lookup(element) instanceof SyncProvider) {
                         syncProviderObj = true;
-                     }
+                    }
                 }
 
                 if (syncProviderObj) {
-                    SyncProvider sync = (SyncProvider)elementObj;
+                    SyncProvider sync = (SyncProvider) elementObj;
                     properties.put(SyncFactory.ROWSET_SYNC_PROVIDER,
-                        sync.getProviderID());
+                            sync.getProviderID());
                     syncProviderObj = false; // reset
                 }
 
@@ -756,142 +792,136 @@
     }
 }
 
-   /**
-     * Internal class that defines the lazy reference construct for each registered
-     * SyncProvider implementation.
-     */
-   class ProviderImpl extends SyncProvider {
-        private String className = null;
-        private String vendorName = null;
-        private String ver = null;
-        private int index;
+/**
+ * Internal class that defines the lazy reference construct for each registered
+ * SyncProvider implementation.
+ */
+class ProviderImpl extends SyncProvider {
+
+    private String className = null;
+    private String vendorName = null;
+    private String ver = null;
+    private int index;
 
-        public void setClassname(String classname) {
-            className = classname;
-        }
-
-        public String getClassname() {
-            return className;
-        }
+    public void setClassname(String classname) {
+        className = classname;
+    }
 
-        public void setVendor(String vendor) {
-            vendorName = vendor;
-        }
+    public String getClassname() {
+        return className;
+    }
 
-        public String getVendor() {
-            return vendorName;
-        }
+    public void setVendor(String vendor) {
+        vendorName = vendor;
+    }
 
-        public void setVersion(String providerVer) {
-            ver = providerVer;
-        }
+    public String getVendor() {
+        return vendorName;
+    }
 
-        public String getVersion() {
-            return ver;
-        }
+    public void setVersion(String providerVer) {
+        ver = providerVer;
+    }
 
-        public void setIndex(int i) {
-            index = i;
-        }
+    public String getVersion() {
+        return ver;
+    }
 
-        public int getIndex() {
-            return index;
-        }
+    public void setIndex(int i) {
+        index = i;
+    }
 
-        public int getDataSourceLock() throws SyncProviderException {
+    public int getIndex() {
+        return index;
+    }
 
-           int dsLock = 0;
-            try
-            {
-               dsLock = SyncFactory.getInstance(className).getDataSourceLock();
-            } catch(SyncFactoryException sfEx) {
+    public int getDataSourceLock() throws SyncProviderException {
 
-                 throw new SyncProviderException(sfEx.getMessage());
-             }
+        int dsLock = 0;
+        try {
+            dsLock = SyncFactory.getInstance(className).getDataSourceLock();
+        } catch (SyncFactoryException sfEx) {
 
-            return dsLock;
+            throw new SyncProviderException(sfEx.getMessage());
         }
 
-        public int getProviderGrade() {
+        return dsLock;
+    }
 
-           int grade = 0;
+    public int getProviderGrade() {
 
-           try
-           {
-              grade =  SyncFactory.getInstance(className).getProviderGrade();
-           } catch(SyncFactoryException sfEx) {
-               //
-           }
+        int grade = 0;
 
-           return grade;
-        }
-
-        public String getProviderID() {
-            return className;
+        try {
+            grade = SyncFactory.getInstance(className).getProviderGrade();
+        } catch (SyncFactoryException sfEx) {
+            //
         }
 
-        /*
-        public javax.sql.RowSetInternal getRowSetInternal() {
-          try
-           {
-              return SyncFactory.getInstance(className).getRowSetInternal();
-           } catch(SyncFactoryException sfEx) {
-               //
-           }
-        }
-        */
+        return grade;
+    }
+
+    public String getProviderID() {
+        return className;
+    }
 
-        public javax.sql.RowSetReader getRowSetReader() {
-
-        RowSetReader rsReader = null;;
+    /*
+    public javax.sql.RowSetInternal getRowSetInternal() {
+    try
+    {
+    return SyncFactory.getInstance(className).getRowSetInternal();
+    } catch(SyncFactoryException sfEx) {
+    //
+    }
+    }
+     */
+    public javax.sql.RowSetReader getRowSetReader() {
 
-        try
-        {
-           rsReader = SyncFactory.getInstance(className).getRowSetReader();
-         } catch(SyncFactoryException sfEx) {
-               //
-         }
+        RowSetReader rsReader = null;
 
-         return rsReader;
-
+        try {
+            rsReader = SyncFactory.getInstance(className).getRowSetReader();
+        } catch (SyncFactoryException sfEx) {
+            //
         }
 
-        public javax.sql.RowSetWriter getRowSetWriter() {
+        return rsReader;
+
+    }
+
+    public javax.sql.RowSetWriter getRowSetWriter() {
 
         RowSetWriter rsWriter = null;
-        try
-           {
-            rsWriter =  SyncFactory.getInstance(className).getRowSetWriter();
-           } catch(SyncFactoryException sfEx) {
-               //
-           }
-
-           return rsWriter;
-        }
-        public void setDataSourceLock(int param)
-        throws SyncProviderException {
-
-         try
-           {
-              SyncFactory.getInstance(className).setDataSourceLock(param);
-           } catch(SyncFactoryException sfEx) {
-
-               throw new SyncProviderException(sfEx.getMessage());
-           }
+        try {
+            rsWriter = SyncFactory.getInstance(className).getRowSetWriter();
+        } catch (SyncFactoryException sfEx) {
+            //
         }
 
-        public int supportsUpdatableView() {
+        return rsWriter;
+    }
+
+    public void setDataSourceLock(int param)
+            throws SyncProviderException {
+
+        try {
+            SyncFactory.getInstance(className).setDataSourceLock(param);
+        } catch (SyncFactoryException sfEx) {
+
+            throw new SyncProviderException(sfEx.getMessage());
+        }
+    }
+
+    public int supportsUpdatableView() {
 
         int view = 0;
 
-        try
-         {
-           view = SyncFactory.getInstance(className).supportsUpdatableView();
-         } catch(SyncFactoryException sfEx) {
-               //
-         }
+        try {
+            view = SyncFactory.getInstance(className).supportsUpdatableView();
+        } catch (SyncFactoryException sfEx) {
+            //
+        }
 
-         return view;
-       }
-
+        return view;
     }
+}
--- a/src/share/classes/javax/sql/rowset/spi/SyncProvider.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/sql/rowset/spi/SyncProvider.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2010, Oracle and/or its affiliates. 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
@@ -344,7 +344,7 @@
      * source without checking the validity of any data.
      *
      */
-    public static int GRADE_NONE = 1;
+    public static final int GRADE_NONE = 1;
 
     /**
      * Indicates a low level optimistic synchronization grade with
@@ -354,7 +354,7 @@
      * returning this grade will check only rows that have changed.
      *
      */
-    public static int GRADE_CHECK_MODIFIED_AT_COMMIT = 2;
+    public static final int GRADE_CHECK_MODIFIED_AT_COMMIT = 2;
 
     /**
      * Indicates a high level optimistic synchronization grade with
@@ -364,7 +364,7 @@
      * returning this grade will check all rows, including rows that have not
      * changed.
      */
-    public static int GRADE_CHECK_ALL_AT_COMMIT = 3;
+    public static final int GRADE_CHECK_ALL_AT_COMMIT = 3;
 
     /**
      * Indicates a pessimistic synchronization grade with
@@ -374,7 +374,7 @@
      * implementation returning this grade will lock the row in the originating
      * data source.
      */
-    public static int GRADE_LOCK_WHEN_MODIFIED = 4;
+    public static final int GRADE_LOCK_WHEN_MODIFIED = 4;
 
     /**
      * Indicates the most pessimistic synchronization grade with
@@ -384,47 +384,47 @@
      * table affected by the original statement used to populate a
      * <code>RowSet</code> object.
      */
-    public static int GRADE_LOCK_WHEN_LOADED = 5;
+    public static final int GRADE_LOCK_WHEN_LOADED = 5;
 
     /**
      * Indicates that no locks remain on the originating data source. This is the default
      * lock setting for all <code>SyncProvider</code> implementations unless
      * otherwise directed by a <code>RowSet</code> object.
      */
-    public static int DATASOURCE_NO_LOCK = 1;
+    public static final int DATASOURCE_NO_LOCK = 1;
 
     /**
      * Indicates that a lock is placed on the rows that are touched by the original
      * SQL statement used to populate the <code>RowSet</code> object
      * that is using this <code>SyncProvider</code> object.
      */
-    public static int DATASOURCE_ROW_LOCK = 2;
+    public static final int DATASOURCE_ROW_LOCK = 2;
 
     /**
      * Indicates that a lock is placed on all tables that are touched by the original
      * SQL statement used to populate the <code>RowSet</code> object
      * that is using this <code>SyncProvider</code> object.
      */
-    public static int DATASOURCE_TABLE_LOCK = 3;
+    public static final int DATASOURCE_TABLE_LOCK = 3;
 
     /**
      * Indicates that a lock is placed on the entire data source that is the source of
      * data for the <code>RowSet</code> object
      * that is using this <code>SyncProvider</code> object.
      */
-    public static int DATASOURCE_DB_LOCK = 4;
+    public static final int DATASOURCE_DB_LOCK = 4;
 
     /**
      * Indicates that a <code>SyncProvider</code> implementation
      * supports synchronization between a <code>RowSet</code> object and
      * the SQL <code>VIEW</code> used to populate it.
      */
-    public static int UPDATABLE_VIEW_SYNC = 5;
+    public static final int UPDATABLE_VIEW_SYNC = 5;
 
     /**
      * Indicates that a <code>SyncProvider</code> implementation
      * does <B>not</B> support synchronization between a <code>RowSet</code>
      * object and the SQL <code>VIEW</code> used to populate it.
      */
-    public static int NONUPDATABLE_VIEW_SYNC = 6;
+    public static final int NONUPDATABLE_VIEW_SYNC = 6;
 }
--- a/src/share/classes/javax/swing/JColorChooser.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/swing/JColorChooser.java	Fri Sep 24 16:41:32 2010 -0700
@@ -27,13 +27,11 @@
 
 import java.awt.*;
 import java.awt.event.*;
-import java.beans.*;
 import java.io.*;
 import java.util.*;
 
 import javax.swing.colorchooser.*;
 import javax.swing.plaf.ColorChooserUI;
-import javax.swing.event.*;
 import javax.accessibility.*;
 
 import sun.swing.SwingUtilities2;
@@ -95,7 +93,7 @@
 
     private ColorSelectionModel selectionModel;
 
-    private JComponent previewPanel;
+    private JComponent previewPanel = ColorChooserComponentFactory.getPreviewPanel();
 
     private AbstractColorChooserPanel[] chooserPanels = new AbstractColorChooserPanel[0];
 
--- a/src/share/classes/javax/swing/JDialog.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/swing/JDialog.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. 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
@@ -26,12 +26,7 @@
 
 import java.awt.*;
 import java.awt.event.*;
-import java.beans.PropertyChangeListener;
-import java.util.Locale;
-import java.util.Vector;
-import java.io.Serializable;
 import javax.accessibility.*;
-import java.applet.Applet;
 
 /**
  * The main class for creating a dialog window. You can use this class
@@ -45,30 +40,30 @@
  *
  * <p>
  *
- * The <code>JDialog</code> component contains a <code>JRootPane</code>
+ * The {@code JDialog} component contains a {@code JRootPane}
  * as its only child.
- * The <code>contentPane</code> should be the parent of any children of the
- * <code>JDialog</code>.
- * As a convenience <code>add</code> and its variants, <code>remove</code> and
- * <code>setLayout</code> have been overridden to forward to the
- * <code>contentPane</code> as necessary. This means you can write:
+ * The {@code contentPane} should be the parent of any children of the
+ * {@code JDialog}.
+ * As a convenience {@code add} and its variants, {@code remove} and
+ * {@code setLayout} have been overridden to forward to the
+ * {@code contentPane} as necessary. This means you can write:
  * <pre>
  *       dialog.add(child);
  * </pre>
  * And the child will be added to the contentPane.
- * The <code>contentPane</code> is always non-<code>null</code>.
- * Attempting to set it to <code>null</code> generates an exception.
- * The default <code>contentPane</code> has a <code>BorderLayout</code>
+ * The {@code contentPane} is always non-{@code null}.
+ * Attempting to set it to {@code null} generates an exception.
+ * The default {@code contentPane} has a {@code BorderLayout}
  * manager set on it.
  * Refer to {@link javax.swing.RootPaneContainer}
- * for details on adding, removing and setting the <code>LayoutManager</code>
- * of a <code>JDialog</code>.
+ * for details on adding, removing and setting the {@code LayoutManager}
+ * of a {@code JDialog}.
  * <p>
- * Please see the <code>JRootPane</code> documentation for a complete
- * description of the <code>contentPane</code>, <code>glassPane</code>,
- * and <code>layeredPane</code> components.
+ * Please see the {@code JRootPane} documentation for a complete
+ * description of the {@code contentPane}, {@code glassPane},
+ * and {@code layeredPane} components.
  * <p>
- * In a multi-screen environment, you can create a <code>JDialog</code>
+ * In a multi-screen environment, you can create a {@code JDialog}
  * on a different screen device than its owner.  See {@link java.awt.Frame} for
  * more information.
  * <p>
@@ -83,7 +78,7 @@
  * appropriate for short term storage or RMI between applications running
  * the same version of Swing.  As of 1.4, support for long term storage
  * of all JavaBeans<sup><font size="-2">TM</font></sup>
- * has been added to the <code>java.beans</code> package.
+ * has been added to the {@code java.beans} package.
  * Please see {@link java.beans.XMLEncoder}.
  *
  * @see JOptionPane
@@ -120,9 +115,9 @@
     protected JRootPane rootPane;
 
     /**
-     * If true then calls to <code>add</code> and <code>setLayout</code>
-     * will be forwarded to the <code>contentPane</code>. This is initially
-     * false, but is set to true when the <code>JDialog</code> is constructed.
+     * If true then calls to {@code add} and {@code setLayout}
+     * will be forwarded to the {@code contentPane}. This is initially
+     * false, but is set to true when the {@code JDialog} is constructed.
      *
      * @see #isRootPaneCheckingEnabled
      * @see #setRootPaneCheckingEnabled
@@ -131,26 +126,26 @@
     protected boolean rootPaneCheckingEnabled = false;
 
     /**
-     * The <code>TransferHandler</code> for this dialog.
+     * The {@code TransferHandler} for this dialog.
      */
     private TransferHandler transferHandler;
 
     /**
      * Creates a modeless dialog without a title and without a specified
-     * <code>Frame</code> owner.  A shared, hidden frame will be
+     * {@code Frame} owner.  A shared, hidden frame will be
      * set as the owner of the dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      * <p>
      * NOTE: This constructor does not allow you to create an unowned
-     * <code>JDialog</code>. To create an unowned <code>JDialog</code>
-     * you must use either the <code>JDialog(Window)</code> or
-     * <code>JDialog(Dialog)</code> constructor with an argument of
-     * <code>null</code>.
+     * {@code JDialog}. To create an unowned {@code JDialog}
+     * you must use either the {@code JDialog(Window)} or
+     * {@code JDialog(Dialog)} constructor with an argument of
+     * {@code null}.
      *
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
      */
@@ -160,22 +155,22 @@
 
     /**
      * Creates a modeless dialog without a title with the
-     * specified <code>Frame</code> as its owner.  If <code>owner</code>
-     * is <code>null</code>, a shared, hidden frame will be set as the
+     * specified {@code Frame} as its owner.  If {@code owner}
+     * is {@code null}, a shared, hidden frame will be set as the
      * owner of the dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      * <p>
      * NOTE: This constructor does not allow you to create an unowned
-     * <code>JDialog</code>. To create an unowned <code>JDialog</code>
-     * you must use either the <code>JDialog(Window)</code> or
-     * <code>JDialog(Dialog)</code> constructor with an argument of
-     * <code>null</code>.
+     * {@code JDialog}. To create an unowned {@code JDialog}
+     * you must use either the {@code JDialog(Window)} or
+     * {@code JDialog(Dialog)} constructor with an argument of
+     * {@code null}.
      *
-     * @param owner the <code>Frame</code> from which the dialog is displayed
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     * @param owner the {@code Frame} from which the dialog is displayed
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
      */
@@ -184,25 +179,25 @@
     }
 
     /**
-     * Creates a dialog with the specified owner <code>Frame</code>, modality
-     * and an empty title. If <code>owner</code> is <code>null</code>,
+     * Creates a dialog with the specified owner {@code Frame}, modality
+     * and an empty title. If {@code owner} is {@code null},
      * a shared, hidden frame will be set as the owner of the dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      * <p>
      * NOTE: This constructor does not allow you to create an unowned
-     * <code>JDialog</code>. To create an unowned <code>JDialog</code>
-     * you must use either the <code>JDialog(Window)</code> or
-     * <code>JDialog(Dialog)</code> constructor with an argument of
-     * <code>null</code>.
+     * {@code JDialog}. To create an unowned {@code JDialog}
+     * you must use either the {@code JDialog(Window)} or
+     * {@code JDialog(Dialog)} constructor with an argument of
+     * {@code null}.
      *
-     * @param owner the <code>Frame</code> from which the dialog is displayed
+     * @param owner the {@code Frame} from which the dialog is displayed
      * @param modal specifies whether dialog blocks user input to other top-level
-     *     windows when shown. If <code>true</code>, the modality type property is set to
-     *     <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless.
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     *     windows when shown. If {@code true}, the modality type property is set to
+     *     {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless.
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
      */
@@ -212,24 +207,24 @@
 
     /**
      * Creates a modeless dialog with the specified title and
-     * with the specified owner frame.  If <code>owner</code>
-     * is <code>null</code>, a shared, hidden frame will be set as the
+     * with the specified owner frame.  If {@code owner}
+     * is {@code null}, a shared, hidden frame will be set as the
      * owner of the dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      * <p>
      * NOTE: This constructor does not allow you to create an unowned
-     * <code>JDialog</code>. To create an unowned <code>JDialog</code>
-     * you must use either the <code>JDialog(Window)</code> or
-     * <code>JDialog(Dialog)</code> constructor with an argument of
-     * <code>null</code>.
+     * {@code JDialog}. To create an unowned {@code JDialog}
+     * you must use either the {@code JDialog(Window)} or
+     * {@code JDialog(Dialog)} constructor with an argument of
+     * {@code null}.
      *
-     * @param owner the <code>Frame</code> from which the dialog is displayed
-     * @param title  the <code>String</code> to display in the dialog's
+     * @param owner the {@code Frame} from which the dialog is displayed
+     * @param title  the {@code String} to display in the dialog's
      *                  title bar
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
      */
@@ -238,31 +233,31 @@
     }
 
     /**
-     * Creates a dialog with the specified title, owner <code>Frame</code>
-     * and modality. If <code>owner</code> is <code>null</code>,
+     * Creates a dialog with the specified title, owner {@code Frame}
+     * and modality. If {@code owner} is {@code null},
      * a shared, hidden frame will be set as the owner of this dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      * <p>
-     * NOTE: Any popup components (<code>JComboBox</code>,
-     * <code>JPopupMenu</code>, <code>JMenuBar</code>)
+     * NOTE: Any popup components ({@code JComboBox},
+     * {@code JPopupMenu}, {@code JMenuBar})
      * created within a modal dialog will be forced to be lightweight.
      * <p>
      * NOTE: This constructor does not allow you to create an unowned
-     * <code>JDialog</code>. To create an unowned <code>JDialog</code>
-     * you must use either the <code>JDialog(Window)</code> or
-     * <code>JDialog(Dialog)</code> constructor with an argument of
-     * <code>null</code>.
+     * {@code JDialog}. To create an unowned {@code JDialog}
+     * you must use either the {@code JDialog(Window)} or
+     * {@code JDialog(Dialog)} constructor with an argument of
+     * {@code null}.
      *
-     * @param owner the <code>Frame</code> from which the dialog is displayed
-     * @param title  the <code>String</code> to display in the dialog's
+     * @param owner the {@code Frame} from which the dialog is displayed
+     * @param title  the {@code String} to display in the dialog's
      *     title bar
      * @param modal specifies whether dialog blocks user input to other top-level
-     *     windows when shown. If <code>true</code>, the modality type property is set to
-     *     <code>DEFAULT_MODALITY_TYPE</code> otherwise the dialog is modeless
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     *     windows when shown. If {@code true}, the modality type property is set to
+     *     {@code DEFAULT_MODALITY_TYPE} otherwise the dialog is modeless
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      *
      * @see java.awt.Dialog.ModalityType
      * @see java.awt.Dialog.ModalityType#MODELESS
@@ -285,35 +280,35 @@
 
     /**
      * Creates a dialog with the specified title,
-     * owner <code>Frame</code>, modality and <code>GraphicsConfiguration</code>.
-     * If <code>owner</code> is <code>null</code>,
+     * owner {@code Frame}, modality and {@code GraphicsConfiguration}.
+     * If {@code owner} is {@code null},
      * a shared, hidden frame will be set as the owner of this dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      * <p>
-     * NOTE: Any popup components (<code>JComboBox</code>,
-     * <code>JPopupMenu</code>, <code>JMenuBar</code>)
+     * NOTE: Any popup components ({@code JComboBox},
+     * {@code JPopupMenu}, {@code JMenuBar})
      * created within a modal dialog will be forced to be lightweight.
      * <p>
      * NOTE: This constructor does not allow you to create an unowned
-     * <code>JDialog</code>. To create an unowned <code>JDialog</code>
-     * you must use either the <code>JDialog(Window)</code> or
-     * <code>JDialog(Dialog)</code> constructor with an argument of
-     * <code>null</code>.
+     * {@code JDialog}. To create an unowned {@code JDialog}
+     * you must use either the {@code JDialog(Window)} or
+     * {@code JDialog(Dialog)} constructor with an argument of
+     * {@code null}.
      *
-     * @param owner the <code>Frame</code> from which the dialog is displayed
-     * @param title  the <code>String</code> to display in the dialog's
+     * @param owner the {@code Frame} from which the dialog is displayed
+     * @param title  the {@code String} to display in the dialog's
      *     title bar
      * @param modal specifies whether dialog blocks user input to other top-level
-     *     windows when shown. If <code>true</code>, the modality type property is set to
-     *     <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless.
-     * @param gc the <code>GraphicsConfiguration</code>
-     *     of the target screen device.  If <code>gc</code> is
-     *     <code>null</code>, the same
-     *     <code>GraphicsConfiguration</code> as the owning Frame is used.
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     *     windows when shown. If {@code true}, the modality type property is set to
+     *     {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless.
+     * @param gc the {@code GraphicsConfiguration}
+     *     of the target screen device.  If {@code gc} is
+     *     {@code null}, the same
+     *     {@code GraphicsConfiguration} as the owning Frame is used.
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.Dialog.ModalityType
      * @see java.awt.Dialog.ModalityType#MODELESS
      * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
@@ -337,15 +332,15 @@
 
     /**
      * Creates a modeless dialog without a title with the
-     * specified <code>Dialog</code> as its owner.
+     * specified {@code Dialog} as its owner.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      *
-     * @param owner the owner <code>Dialog</code> from which the dialog is displayed
-     *     or <code>null</code> if this dialog has no owner
-     * @exception HeadlessException <code>if GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     * @param owner the owner {@code Dialog} from which the dialog is displayed
+     *     or {@code null} if this dialog has no owner
+     * @throws HeadlessException {@code if GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
      */
@@ -354,18 +349,18 @@
     }
 
     /**
-     * Creates a dialog with the specified owner <code>Dialog</code> and modality.
+     * Creates a dialog with the specified owner {@code Dialog} and modality.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      *
-     * @param owner the owner <code>Dialog</code> from which the dialog is displayed
-     *     or <code>null</code> if this dialog has no owner
+     * @param owner the owner {@code Dialog} from which the dialog is displayed
+     *     or {@code null} if this dialog has no owner
      * @param modal specifies whether dialog blocks user input to other top-level
-     *     windows when shown. If <code>true</code>, the modality type property is set to
-     *     <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless.
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     *     windows when shown. If {@code true}, the modality type property is set to
+     *     {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless.
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.Dialog.ModalityType
      * @see java.awt.Dialog.ModalityType#MODELESS
      * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
@@ -383,14 +378,14 @@
      * with the specified owner dialog.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      *
-     * @param owner the owner <code>Dialog</code> from which the dialog is displayed
-     *     or <code>null</code> if this dialog has no owner
-     * @param title  the <code>String</code> to display in the dialog's
+     * @param owner the owner {@code Dialog} from which the dialog is displayed
+     *     or {@code null} if this dialog has no owner
+     * @param title  the {@code String} to display in the dialog's
      *                  title bar
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
      */
@@ -400,20 +395,20 @@
 
     /**
      * Creates a dialog with the specified title, modality
-     * and the specified owner <code>Dialog</code>.
+     * and the specified owner {@code Dialog}.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      *
-     * @param owner the owner <code>Dialog</code> from which the dialog is displayed
-     *     or <code>null</code> if this dialog has no owner
-     * @param title  the <code>String</code> to display in the dialog's
+     * @param owner the owner {@code Dialog} from which the dialog is displayed
+     *     or {@code null} if this dialog has no owner
+     * @param title  the {@code String} to display in the dialog's
      *     title bar
      * @param modal specifies whether dialog blocks user input to other top-level
-     *     windows when shown. If <code>true</code>, the modality type property is set to
-     *     <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     *     windows when shown. If {@code true}, the modality type property is set to
+     *     {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.Dialog.ModalityType
      * @see java.awt.Dialog.ModalityType#MODELESS
      * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
@@ -428,30 +423,30 @@
     }
 
     /**
-     * Creates a dialog with the specified title, owner <code>Dialog</code>,
-     * modality and <code>GraphicsConfiguration</code>.
+     * Creates a dialog with the specified title, owner {@code Dialog},
+     * modality and {@code GraphicsConfiguration}.
      *
      * <p>
-     * NOTE: Any popup components (<code>JComboBox</code>,
-     * <code>JPopupMenu</code>, <code>JMenuBar</code>)
+     * NOTE: Any popup components ({@code JComboBox},
+     * {@code JPopupMenu}, {@code JMenuBar})
      * created within a modal dialog will be forced to be lightweight.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      *
-     * @param owner the owner <code>Dialog</code> from which the dialog is displayed
-     *     or <code>null</code> if this dialog has no owner
-     * @param title  the <code>String</code> to display in the dialog's
+     * @param owner the owner {@code Dialog} from which the dialog is displayed
+     *     or {@code null} if this dialog has no owner
+     * @param title  the {@code String} to display in the dialog's
      *     title bar
      * @param modal specifies whether dialog blocks user input to other top-level
-     *     windows when shown. If <code>true</code>, the modality type property is set to
-     *     <code>DEFAULT_MODALITY_TYPE</code>, otherwise the dialog is modeless
-     * @param gc the <code>GraphicsConfiguration</code>
-     *     of the target screen device.  If <code>gc</code> is
-     *     <code>null</code>, the same
-     *     <code>GraphicsConfiguration</code> as the owning Dialog is used.
-     * @exception HeadlessException if <code>GraphicsEnvironment.isHeadless()</code>
-     *     returns <code>true</code>.
+     *     windows when shown. If {@code true}, the modality type property is set to
+     *     {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless
+     * @param gc the {@code GraphicsConfiguration}
+     *     of the target screen device.  If {@code gc} is
+     *     {@code null}, the same
+     *     {@code GraphicsConfiguration} as the owning Dialog is used.
+     * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
+     *     returns {@code true}.
      * @see java.awt.Dialog.ModalityType
      * @see java.awt.Dialog.ModalityType#MODELESS
      * @see java.awt.Dialog#DEFAULT_MODALITY_TYPE
@@ -468,16 +463,22 @@
     }
 
     /**
-     * Creates a modeless dialog with the specified owner <code>Window</code> and
+     * Creates a modeless dialog with the specified owner {@code Window} and
      * an empty title.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
+     *
+     * @param owner the {@code Window} from which the dialog is displayed or
+     *     {@code null} if this dialog has no owner
      *
-     * @param owner the <code>Window</code> from which the dialog is displayed or
-     *     <code>null</code> if this dialog has no owner
-     * @exception HeadlessException when
-     *    <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
+     * @throws IllegalArgumentException
+     *     if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog}
+     *     or {@link java.awt.Frame Frame}
+     * @throws IllegalArgumentException
+     *     if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device
+     * @throws HeadlessException
+     *     when {@code GraphicsEnvironment.isHeadless()} returns {@code true}
      *
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
@@ -489,19 +490,28 @@
     }
 
     /**
-     * Creates a dialog with the specified owner <code>Window</code>, modality
+     * Creates a dialog with the specified owner {@code Window}, modality
      * and an empty title.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      *
-     * @param owner the <code>Window</code> from which the dialog is displayed or
-     *     <code>null</code> if this dialog has no owner
+     * @param owner the {@code Window} from which the dialog is displayed or
+     *     {@code null} if this dialog has no owner
      * @param modalityType specifies whether dialog blocks input to other
-     *     windows when shown. <code>null</code> value and unsupported modality
-     *     types are equivalent to <code>MODELESS</code>
-     * @exception HeadlessException when
-     *    <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
+     *     windows when shown. {@code null} value and unsupported modality
+     *     types are equivalent to {@code MODELESS}
+     *
+     * @throws IllegalArgumentException
+     *     if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog}
+     *     or {@link java.awt.Frame Frame}
+     * @throws IllegalArgumentException
+     *     if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device
+     * @throws HeadlessException
+     *     when {@code GraphicsEnvironment.isHeadless()} returns {@code true}
+     * @throws SecurityException
+     *     if the calling thread does not have permission to create modal dialogs
+     *     with the given {@code modalityType}
      *
      * @see java.awt.Dialog.ModalityType
      * @see java.awt.Dialog#setModal
@@ -517,17 +527,23 @@
 
     /**
      * Creates a modeless dialog with the specified title and owner
-     * <code>Window</code>.
+     * {@code Window}.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
+     *
+     * @param owner the {@code Window} from which the dialog is displayed or
+     *     {@code null} if this dialog has no owner
+     * @param title the {@code String} to display in the dialog's
+     *     title bar or {@code null} if the dialog has no title
      *
-     * @param owner the <code>Window</code> from which the dialog is displayed or
-     *     <code>null</code> if this dialog has no owner
-     * @param title the <code>String</code> to display in the dialog's
-     *     title bar or <code>null</code> if the dialog has no title
-     * @exception java.awt.HeadlessException when
-     *     <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
+     * @throws IllegalArgumentException
+     *     if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog}
+     *     or {@link java.awt.Frame Frame}
+     * @throws IllegalArgumentException
+     *     if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device
+     * @throws HeadlessException
+     *     when {@code GraphicsEnvironment.isHeadless()} returns {@code true}
      *
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @see JComponent#getDefaultLocale
@@ -539,21 +555,30 @@
     }
 
     /**
-     * Creates a dialog with the specified title, owner <code>Window</code> and
+     * Creates a dialog with the specified title, owner {@code Window} and
      * modality.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
+     *
+     * @param owner the {@code Window} from which the dialog is displayed or
+     *     {@code null} if this dialog has no owner
+     * @param title the {@code String} to display in the dialog's
+     *     title bar or {@code null} if the dialog has no title
+     * @param modalityType specifies whether dialog blocks input to other
+     *     windows when shown. {@code null} value and unsupported modality
+     *     types are equivalent to {@code MODELESS}
      *
-     * @param owner the <code>Window</code> from which the dialog is displayed or
-     *     <code>null</code> if this dialog has no owner
-     * @param title the <code>String</code> to display in the dialog's
-     *     title bar or <code>null</code> if the dialog has no title
-     * @param modalityType specifies whether dialog blocks input to other
-     *     windows when shown. <code>null</code> value and unsupported modality
-     *     types are equivalent to <code>MODELESS</code>
-     * @exception java.awt.HeadlessException when
-     *     <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
+     * @throws IllegalArgumentException
+     *     if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog}
+     *     or {@link java.awt.Frame Frame}
+     * @throws IllegalArgumentException
+     *     if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device
+     * @throws HeadlessException
+     *     when {@code GraphicsEnvironment.isHeadless()} returns {@code true}
+     * @throws SecurityException
+     *     if the calling thread does not have permission to create modal dialogs
+     *     with the given {@code modalityType}
      *
      * @see java.awt.Dialog.ModalityType
      * @see java.awt.Dialog#setModal
@@ -569,29 +594,38 @@
     }
 
     /**
-     * Creates a dialog with the specified title, owner <code>Window</code>,
-     * modality and <code>GraphicsConfiguration</code>.
+     * Creates a dialog with the specified title, owner {@code Window},
+     * modality and {@code GraphicsConfiguration}.
      * <p>
-     * NOTE: Any popup components (<code>JComboBox</code>,
-     * <code>JPopupMenu</code>, <code>JMenuBar</code>)
+     * NOTE: Any popup components ({@code JComboBox},
+     * {@code JPopupMenu}, {@code JMenuBar})
      * created within a modal dialog will be forced to be lightweight.
      * <p>
      * This constructor sets the component's locale property to the value
-     * returned by <code>JComponent.getDefaultLocale</code>.
+     * returned by {@code JComponent.getDefaultLocale}.
      *
-     * @param owner the <code>Window</code> from which the dialog is displayed or
-     *     <code>null</code> if this dialog has no owner
-     * @param title the <code>String</code> to display in the dialog's
-     *     title bar or <code>null</code> if the dialog has no title
+     * @param owner the {@code Window} from which the dialog is displayed or
+     *     {@code null} if this dialog has no owner
+     * @param title the {@code String} to display in the dialog's
+     *     title bar or {@code null} if the dialog has no title
      * @param modalityType specifies whether dialog blocks input to other
-     *     windows when shown. <code>null</code> value and unsupported modality
-     *     types are equivalent to <code>MODELESS</code>
-     * @param gc the <code>GraphicsConfiguration</code> of the target screen device;
-     *     if <code>null</code>, the <code>GraphicsConfiguration</code> from the owning
-     *     window is used; if <code>owner</code> is also <code>null</code>, the
-     *     system default <code>GraphicsConfiguration</code> is assumed
-     * @exception java.awt.HeadlessException when
-     *    <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
+     *     windows when shown. {@code null} value and unsupported modality
+     *     types are equivalent to {@code MODELESS}
+     * @param gc the {@code GraphicsConfiguration} of the target screen device;
+     *     if {@code null}, the {@code GraphicsConfiguration} from the owning
+     *     window is used; if {@code owner} is also {@code null}, the
+     *     system default {@code GraphicsConfiguration} is assumed
+     *
+     * @throws IllegalArgumentException
+     *     if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog}
+     *     or {@link java.awt.Frame Frame}
+     * @throws IllegalArgumentException
+     *     if the {@code owner}'s {@code GraphicsConfiguration} is not from a screen device
+     * @throws HeadlessException
+     *     when {@code GraphicsEnvironment.isHeadless()} returns {@code true}
+     * @throws SecurityException
+     *     if the calling thread does not have permission to create modal dialogs
+     *     with the given {@code modalityType}
      *
      * @see java.awt.Dialog.ModalityType
      * @see java.awt.Dialog#setModal
@@ -608,7 +642,7 @@
     }
 
     /**
-     * Called by the constructors to init the <code>JDialog</code> properly.
+     * Called by the constructors to init the {@code JDialog} properly.
      */
     protected void dialogInit() {
         enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);
@@ -628,7 +662,7 @@
 
     /**
      * Called by the constructor methods to create the default
-     * <code>rootPane</code>.
+     * {@code rootPane}.
      */
     protected JRootPane createRootPane() {
         JRootPane rp = new JRootPane();
@@ -642,7 +676,7 @@
 
     /**
      * Handles window events depending on the state of the
-     * <code>defaultCloseOperation</code> property.
+     * {@code defaultCloseOperation} property.
      *
      * @see #setDefaultCloseOperation
      */
@@ -671,26 +705,26 @@
      * You must specify one of the following choices:
      * <p>
      * <ul>
-     * <li><code>DO_NOTHING_ON_CLOSE</code>
-     * (defined in <code>WindowConstants</code>):
+     * <li>{@code DO_NOTHING_ON_CLOSE}
+     * (defined in {@code WindowConstants}):
      * Don't do anything; require the
-     * program to handle the operation in the <code>windowClosing</code>
-     * method of a registered <code>WindowListener</code> object.
+     * program to handle the operation in the {@code windowClosing}
+     * method of a registered {@code WindowListener} object.
      *
-     * <li><code>HIDE_ON_CLOSE</code>
-     * (defined in <code>WindowConstants</code>):
+     * <li>{@code HIDE_ON_CLOSE}
+     * (defined in {@code WindowConstants}):
      * Automatically hide the dialog after
-     * invoking any registered <code>WindowListener</code>
+     * invoking any registered {@code WindowListener}
      * objects.
      *
-     * <li><code>DISPOSE_ON_CLOSE</code>
-     * (defined in <code>WindowConstants</code>):
+     * <li>{@code DISPOSE_ON_CLOSE}
+     * (defined in {@code WindowConstants}):
      * Automatically hide and dispose the
-     * dialog after invoking any registered <code>WindowListener</code>
+     * dialog after invoking any registered {@code WindowListener}
      * objects.
      * </ul>
      * <p>
-     * The value is set to <code>HIDE_ON_CLOSE</code> by default. Changes
+     * The value is set to {@code HIDE_ON_CLOSE} by default. Changes
      * to the value of this property cause the firing of a property
      * change event, with property name "defaultCloseOperation".
      * <p>
@@ -779,9 +813,9 @@
     }
 
     /**
-     * Gets the <code>transferHandler</code> property.
+     * Gets the {@code transferHandler} property.
      *
-     * @return the value of the <code>transferHandler</code> property
+     * @return the value of the {@code transferHandler} property
      *
      * @see TransferHandler
      * @see #setTransferHandler
@@ -792,10 +826,10 @@
     }
 
     /**
-     * Calls <code>paint(g)</code>.  This method was overridden to
+     * Calls {@code paint(g)}.  This method was overridden to
      * prevent an unnecessary call to clear the background.
      *
-     * @param g  the <code>Graphics</code> context in which to paint
+     * @param g  the {@code Graphics} context in which to paint
      */
     public void update(Graphics g) {
         paint(g);
@@ -827,10 +861,10 @@
 
 
     /**
-     * Returns whether calls to <code>add</code> and
-     * <code>setLayout</code> are forwarded to the <code>contentPane</code>.
+     * Returns whether calls to {@code add} and
+     * {@code setLayout} are forwarded to the {@code contentPane}.
      *
-     * @return true if <code>add</code> and <code>setLayout</code>
+     * @return true if {@code add} and {@code setLayout}
      *         are fowarded; false otherwise
      *
      * @see #addImpl
@@ -844,12 +878,12 @@
 
 
     /**
-     * Sets whether calls to <code>add</code> and
-     * <code>setLayout</code> are forwarded to the <code>contentPane</code>.
+     * Sets whether calls to {@code add} and
+     * {@code setLayout} are forwarded to the {@code contentPane}.
      *
-     * @param enabled  true if <code>add</code> and <code>setLayout</code>
+     * @param enabled  true if {@code add} and {@code setLayout}
      *        are forwarded, false if they should operate directly on the
-     *        <code>JDialog</code>.
+     *        {@code JDialog}.
      *
      * @see #addImpl
      * @see #setLayout
@@ -864,20 +898,20 @@
     }
 
     /**
-     * Adds the specified child <code>Component</code>.
+     * Adds the specified child {@code Component}.
      * This method is overridden to conditionally forward calls to the
-     * <code>contentPane</code>.
-     * By default, children are added to the <code>contentPane</code> instead
+     * {@code contentPane}.
+     * By default, children are added to the {@code contentPane} instead
      * of the frame, refer to {@link javax.swing.RootPaneContainer} for
      * details.
      *
      * @param comp the component to be enhanced
      * @param constraints the constraints to be respected
      * @param index the index
-     * @exception IllegalArgumentException if <code>index</code> is invalid
-     * @exception IllegalArgumentException if adding the container's parent
+     * @throws IllegalArgumentException if {@code index} is invalid
+     * @throws IllegalArgumentException if adding the container's parent
      *                  to itself
-     * @exception IllegalArgumentException if adding a window to a container
+     * @throws IllegalArgumentException if adding a window to a container
      *
      * @see #setRootPaneCheckingEnabled
      * @see javax.swing.RootPaneContainer
@@ -894,13 +928,13 @@
 
     /**
      * Removes the specified component from the container. If
-     * <code>comp</code> is not the <code>rootPane</code>, this will forward
-     * the call to the <code>contentPane</code>. This will do nothing if
-     * <code>comp</code> is not a child of the <code>JDialog</code> or
-     * <code>contentPane</code>.
+     * {@code comp} is not the {@code rootPane}, this will forward
+     * the call to the {@code contentPane}. This will do nothing if
+     * {@code comp} is not a child of the {@code JDialog} or
+     * {@code contentPane}.
      *
      * @param comp the component to be removed
-     * @throws NullPointerException if <code>comp</code> is null
+     * @throws NullPointerException if {@code comp} is null
      * @see #add
      * @see javax.swing.RootPaneContainer
      */
@@ -914,13 +948,13 @@
 
 
     /**
-     * Sets the <code>LayoutManager</code>.
+     * Sets the {@code LayoutManager}.
      * Overridden to conditionally forward the call to the
-     * <code>contentPane</code>.
+     * {@code contentPane}.
      * Refer to {@link javax.swing.RootPaneContainer} for
      * more information.
      *
-     * @param manager the <code>LayoutManager</code>
+     * @param manager the {@code LayoutManager}
      * @see #setRootPaneCheckingEnabled
      * @see javax.swing.RootPaneContainer
      */
@@ -935,7 +969,7 @@
 
 
     /**
-     * Returns the <code>rootPane</code> object for this dialog.
+     * Returns the {@code rootPane} object for this dialog.
      *
      * @see #setRootPane
      * @see RootPaneContainer#getRootPane
@@ -946,10 +980,10 @@
 
 
     /**
-     * Sets the <code>rootPane</code> property.
+     * Sets the {@code rootPane} property.
      * This method is called by the constructor.
      *
-     * @param root the <code>rootPane</code> object for this dialog
+     * @param root the {@code rootPane} object for this dialog
      *
      * @see #getRootPane
      *
@@ -976,9 +1010,9 @@
 
 
     /**
-     * Returns the <code>contentPane</code> object for this dialog.
+     * Returns the {@code contentPane} object for this dialog.
      *
-     * @return the <code>contentPane</code> property
+     * @return the {@code contentPane} property
      *
      * @see #setContentPane
      * @see RootPaneContainer#getContentPane
@@ -989,19 +1023,19 @@
 
 
    /**
-     * Sets the <code>contentPane</code> property.
+     * Sets the {@code contentPane} property.
      * This method is called by the constructor.
      * <p>
-     * Swing's painting architecture requires an opaque <code>JComponent</code>
+     * Swing's painting architecture requires an opaque {@code JComponent}
      * in the containment hiearchy. This is typically provided by the
      * content pane. If you replace the content pane it is recommended you
-     * replace it with an opaque <code>JComponent</code>.
+     * replace it with an opaque {@code JComponent}.
      * @see JRootPane
      *
-     * @param contentPane the <code>contentPane</code> object for this dialog
+     * @param contentPane the {@code contentPane} object for this dialog
      *
-     * @exception java.awt.IllegalComponentStateException (a runtime
-     *            exception) if the content pane parameter is <code>null</code>
+     * @throws java.awt.IllegalComponentStateException (a runtime
+     *            exception) if the content pane parameter is {@code null}
      * @see #getContentPane
      * @see RootPaneContainer#setContentPane
      *
@@ -1015,9 +1049,9 @@
     }
 
     /**
-     * Returns the <code>layeredPane</code> object for this dialog.
+     * Returns the {@code layeredPane} object for this dialog.
      *
-     * @return the <code>layeredPane</code> property
+     * @return the {@code layeredPane} property
      *
      * @see #setLayeredPane
      * @see RootPaneContainer#getLayeredPane
@@ -1027,12 +1061,12 @@
     }
 
     /**
-     * Sets the <code>layeredPane</code> property.
+     * Sets the {@code layeredPane} property.
      * This method is called by the constructor.
      *
-     * @param layeredPane the new <code>layeredPane</code> property
+     * @param layeredPane the new {@code layeredPane} property
      *
-     * @exception java.awt.IllegalComponentStateException (a runtime
+     * @throws java.awt.IllegalComponentStateException (a runtime
      *            exception) if the layered pane parameter is null
      * @see #getLayeredPane
      * @see RootPaneContainer#setLayeredPane
@@ -1046,9 +1080,9 @@
     }
 
     /**
-     * Returns the <code>glassPane</code> object for this dialog.
+     * Returns the {@code glassPane} object for this dialog.
      *
-     * @return the <code>glassPane</code> property
+     * @return the {@code glassPane} property
      *
      * @see #setGlassPane
      * @see RootPaneContainer#getGlassPane
@@ -1058,10 +1092,10 @@
     }
 
     /**
-     * Sets the <code>glassPane</code> property.
+     * Sets the {@code glassPane} property.
      * This method is called by the constructor.
      *
-     * @param glassPane the <code>glassPane</code> object for this dialog
+     * @param glassPane the {@code glassPane} object for this dialog
      * @see #getGlassPane
      * @see RootPaneContainer#setGlassPane
      *
@@ -1085,7 +1119,7 @@
 
     /**
      * Repaints the specified rectangle of this component within
-     * <code>time</code> milliseconds.  Refer to <code>RepaintManager</code>
+     * {@code time} milliseconds.  Refer to {@code RepaintManager}
      * for details on how the repaint is handled.
      *
      * @param     time   maximum time in milliseconds before update
@@ -1107,15 +1141,15 @@
     }
 
     /**
-     * Provides a hint as to whether or not newly created <code>JDialog</code>s
+     * Provides a hint as to whether or not newly created {@code JDialog}s
      * should have their Window decorations (such as borders, widgets to
      * close the window, title...) provided by the current look
-     * and feel. If <code>defaultLookAndFeelDecorated</code> is true,
-     * the current <code>LookAndFeel</code> supports providing window
+     * and feel. If {@code defaultLookAndFeelDecorated} is true,
+     * the current {@code LookAndFeel} supports providing window
      * decorations, and the current window manager supports undecorated
-     * windows, then newly created <code>JDialog</code>s will have their
-     * Window decorations provided by the current <code>LookAndFeel</code>.
-     * Otherwise, newly created <code>JDialog</code>s will have their
+     * windows, then newly created {@code JDialog}s will have their
+     * Window decorations provided by the current {@code LookAndFeel}.
+     * Otherwise, newly created {@code JDialog}s will have their
      * Window decorations provided by the current window manager.
      * <p>
      * You can get the same effect on a single JDialog by doing the following:
@@ -1139,7 +1173,7 @@
     }
 
     /**
-     * Returns true if newly created <code>JDialog</code>s should have their
+     * Returns true if newly created {@code JDialog}s should have their
      * Window decorations provided by the current look and feel. This is only
      * a hint, as certain look and feels may not support this feature.
      *
@@ -1156,14 +1190,14 @@
     }
 
     /**
-     * Returns a string representation of this <code>JDialog</code>.
+     * Returns a string representation of this {@code JDialog}.
      * This method
      * is intended to be used only for debugging purposes, and the
      * content and format of the returned string may vary between
      * implementations. The returned string may be empty but may not
-     * be <code>null</code>.
+     * be {@code null}.
      *
-     * @return  a string representation of this <code>JDialog</code>.
+     * @return  a string representation of this {@code JDialog}.
      */
     protected String paramString() {
         String defaultCloseOperationString;
@@ -1210,7 +1244,7 @@
 
     /**
      * This class implements accessibility support for the
-     * <code>JDialog</code> class.  It provides an implementation of the
+     * {@code JDialog} class.  It provides an implementation of the
      * Java Accessibility API appropriate to dialog user-interface
      * elements.
      */
--- a/src/share/classes/javax/swing/plaf/basic/BasicBorders.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/swing/plaf/basic/BasicBorders.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2010, Oracle and/or its affiliates. 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
@@ -36,8 +36,6 @@
 import java.awt.Rectangle;
 import java.awt.Color;
 import java.awt.Graphics;
-import java.io.Serializable;
-
 
 /**
  * Factory object that can vend Borders appropriate for the basic L & F.
@@ -431,6 +429,9 @@
 
         public void paintBorder(Component c, Graphics g, int x, int y,
                                 int width, int height) {
+            if (!(c instanceof BasicSplitPaneDivider)) {
+                return;
+            }
             Component          child;
             Rectangle          cBounds;
             JSplitPane         splitPane = ((BasicSplitPaneDivider)c).
@@ -510,6 +511,9 @@
 
         public void paintBorder(Component c, Graphics g, int x, int y,
                                 int width, int height) {
+            if (!(c instanceof JSplitPane)) {
+                return;
+            }
             // The only tricky part with this border is that the divider is
             // not positioned at the top (for horizontal) or left (for vert),
             // so this border draws to where the divider is:
--- a/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java	Fri Sep 24 16:41:32 2010 -0700
@@ -142,11 +142,8 @@
         if (previewPanel == null) {
             previewPanel = ColorChooserComponentFactory.getPreviewPanel();
         }
-        else {
-            Dimension size = new BorderLayout().minimumLayoutSize(previewPanel);
-            if ((size.width == 0) && (size.height == 0)) {
-                previewPanel = null;
-            }
+        else if (JPanel.class.equals(previewPanel.getClass()) && (0 == previewPanel.getComponentCount())) {
+            previewPanel = null;
         }
         this.previewPanel = previewPanel;
         if (previewPanel != null) {
@@ -215,9 +212,10 @@
     }
 
     private void selectionChanged(ColorSelectionModel model) {
-        if (this.previewPanel != null) {
-            this.previewPanel.setForeground(model.getSelectedColor());
-            this.previewPanel.repaint();
+        JComponent previewPanel = this.chooser.getPreviewPanel();
+        if (previewPanel != null) {
+            previewPanel.setForeground(model.getSelectedColor());
+            previewPanel.repaint();
         }
         AbstractColorChooserPanel[] panels = this.chooser.getChooserPanels();
         if (panels != null) {
--- a/src/share/classes/javax/swing/plaf/metal/MetalBorders.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/swing/plaf/metal/MetalBorders.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2010, Oracle and/or its affiliates. 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
@@ -33,14 +33,11 @@
 
 import java.awt.Component;
 import java.awt.Insets;
-import java.awt.Dimension;
-import java.awt.Rectangle;
 import java.awt.Color;
 import java.awt.Dialog;
 import java.awt.Frame;
 import java.awt.Graphics;
 import java.awt.Window;
-import java.io.Serializable;
 
 import sun.swing.StringUIClientPropertyKey;
 
@@ -81,6 +78,9 @@
         protected static Insets borderInsets = new Insets( 3, 3, 3, 3 );
 
         public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
+            if (!(c instanceof AbstractButton)) {
+                return;
+            }
             if (MetalLookAndFeel.usingOcean()) {
                 paintOceanBorder(c, g, x, y, w, h);
                 return;
@@ -473,8 +473,8 @@
             if (c instanceof JInternalFrame) {
                 Object obj = ((JInternalFrame) c).getClientProperty(
                               "JInternalFrame.messageType");
-                if (obj != null && (obj instanceof Integer)) {
-                    messageType = ((Integer) obj).intValue();
+                if (obj instanceof Integer) {
+                    messageType = (Integer) obj;
                 }
             }
 
@@ -533,7 +533,7 @@
             if (MetalLookAndFeel.usingOcean()) {
                 // Only paint a border if we're not next to a horizontal
                 // toolbar
-                if (!MetalToolBarUI.doesMenuBarBorderToolBar((JMenuBar)c)) {
+                if ((c instanceof JMenuBar) && !MetalToolBarUI.doesMenuBarBorderToolBar((JMenuBar)c)) {
                     g.setColor(MetalLookAndFeel.getControl());
                     g.drawLine(0, h - 2, w, h - 2);
                     g.setColor(UIManager.getColor("MenuBar.borderColor"));
@@ -564,6 +564,9 @@
         protected static Insets borderInsets = new Insets( 2, 2, 2, 2 );
 
         public void paintBorder( Component c, Graphics g, int x, int y, int w, int h ) {
+            if (!(c instanceof JMenuItem)) {
+                return;
+            }
             JMenuItem b = (JMenuItem) c;
             ButtonModel model = b.getModel();
 
@@ -687,6 +690,9 @@
 
         public void paintBorder( Component c, Graphics g, int x, int y, int w, int h )
         {
+            if (!(c instanceof JToolBar)) {
+                return;
+            }
             g.translate( x, y );
 
             if ( ((JToolBar) c).isFloatable() )
@@ -729,6 +735,9 @@
                 newInsets.top = newInsets.left = newInsets.bottom = newInsets.right = 2;
             }
 
+            if (!(c instanceof JToolBar)) {
+                return newInsets;
+            }
             if ( ((JToolBar) c).isFloatable() ) {
                 if ( ((JToolBar) c).getOrientation() == HORIZONTAL ) {
                     if (c.getComponentOrientation().isLeftToRight()) {
@@ -827,6 +836,9 @@
         public void paintBorder(Component c, Graphics g, int x, int y,
                           int w, int h) {
 
+            if (!(c instanceof JScrollPane)) {
+                return;
+            }
             JScrollPane scroll = (JScrollPane)c;
             JComponent colHeader = scroll.getColumnHeader();
             int colHeaderHeight = 0;
--- a/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, Oracle and/or its affiliates. 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
@@ -914,6 +914,7 @@
             UIResource {
         public SynthScrollableTabButton(int direction) {
             super(direction);
+            setName("TabbedPane.button");
         }
     }
 }
--- a/src/share/classes/sun/font/FontUtilities.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/font/FontUtilities.java	Fri Sep 24 16:41:32 2010 -0700
@@ -373,8 +373,7 @@
      */
     public static FontUIResource getCompositeFontUIResource(Font font) {
 
-        FontUIResource fuir =
-            new FontUIResource(font.getName(),font.getStyle(),font.getSize());
+        FontUIResource fuir = new FontUIResource(font);
         Font2D font2D = FontUtilities.getFont2D(font);
 
         if (!(font2D instanceof PhysicalFont)) {
--- a/src/share/classes/sun/java2d/cmm/CMSManager.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/java2d/cmm/CMSManager.java	Fri Sep 24 16:41:32 2010 -0700
@@ -100,12 +100,12 @@
         public long loadProfile(byte[] data) {
             System.err.print(cName + ".loadProfile");
             long profileID = tcmm.loadProfile(data);
-            System.err.println("(ID=" + profileID + ")");
+            System.err.printf("(ID=%x)\n", profileID);
             return profileID;
         }
 
         public void freeProfile(long profileID) {
-            System.err.println(cName + ".freeProfile(ID=" + profileID + ")");
+            System.err.printf(cName + ".freeProfile(ID=%x)\n", profileID);
             tcmm.freeProfile(profileID);
         }
 
@@ -123,8 +123,8 @@
         }
 
         public int getTagSize(long profileID, int tagSignature) {
-            System.err.print(cName + ".getTagSize(ID=" + profileID +
-                               ", TagSig=" + tagSignature + ")");
+            System.err.printf(cName + ".getTagSize(ID=%x, TagSig=%s)",
+                              profileID, signatureToString(tagSignature));
             int size = tcmm.getTagSize(profileID, tagSignature);
             System.err.println("=" + size);
             return size;
@@ -132,8 +132,8 @@
 
         public void getTagData(long profileID, int tagSignature,
                                byte[] data) {
-            System.err.print(cName + ".getTagData(ID=" + profileID +
-                             ", TagSig=" + tagSignature + ")");
+            System.err.printf(cName + ".getTagData(ID=%x, TagSig=%s)",
+                              profileID, signatureToString(tagSignature));
             System.err.println(" requested " + data.length + " byte(s)");
             tcmm.getTagData(profileID, tagSignature, data);
         }
@@ -158,5 +158,13 @@
             System.err.println(cName + ".createTransform(ColorTransform[])");
             return tcmm.createTransform(transforms);
         }
+
+        private static String signatureToString(int sig) {
+            return String.format("%c%c%c%c",
+                                 (char)(0xff & (sig >> 24)),
+                                 (char)(0xff & (sig >> 16)),
+                                 (char)(0xff & (sig >>  8)),
+                                 (char)(0xff & (sig      )));
+        }
     }
 }
--- a/src/share/classes/sun/java2d/cmm/lcms/LCMS.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/java2d/cmm/lcms/LCMS.java	Fri Sep 24 16:41:32 2010 -0700
@@ -53,7 +53,8 @@
     public static native long getProfileID(ICC_Profile profile);
 
     public static native long createNativeTransform(
-        long[] profileIDs, int renderType, Object disposerRef);
+        long[] profileIDs, int renderType, int inFormatter, int outFormatter,
+        Object disposerRef);
 
    /**
      * Constructs ColorTransform object corresponding to an ICC_profile
--- a/src/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java	Fri Sep 24 16:41:32 2010 -0700
@@ -55,11 +55,17 @@
 
 public class LCMSTransform implements ColorTransform {
     long ID;
+    private int inFormatter;
+    private int outFormatter;
+
     ICC_Profile[] profiles;
     long [] profileIDs;
     int renderType;
     int transformType;
 
+    private int numInComponents = -1;
+    private int numOutComponents = -1;
+
     private Object disposerReferent = new Object();
 
     /* the class initializer */
@@ -80,6 +86,14 @@
         this.renderType = (renderType == ColorTransform.Any)?
                               ICC_Profile.icPerceptual : renderType;
         this.transformType = transformType;
+
+        /* Note that ICC_Profile.getNumComponents() is quite expensive
+         * (it may results in a reading of the profile header).
+         * So, here we cache the number of components of input and
+         * output profiles for further usage.
+         */
+        numInComponents = profiles[0].getNumComponents();
+        numOutComponents = profiles[profiles.length - 1].getNumComponents();
     }
 
     public LCMSTransform (ColorTransform[] transforms) {
@@ -99,26 +113,51 @@
             j += curTrans.profiles.length;
         }
         renderType = ((LCMSTransform)transforms[0]).renderType;
-        ID = LCMS.createNativeTransform(profileIDs, renderType,
-                                        disposerReferent);
+
+        /* Note that ICC_Profile.getNumComponents() is quite expensive
+         * (it may results in a reading of the profile header).
+         * So, here we cache the number of components of input and
+         * output profiles for further usage.
+         */
+        numInComponents = profiles[0].getNumComponents();
+        numOutComponents = profiles[profiles.length - 1].getNumComponents();
     }
 
     public int getNumInComponents() {
-        return profiles[0].getNumComponents();
+        return numInComponents;
     }
 
     public int getNumOutComponents() {
-        return profiles[profiles.length - 1].getNumComponents();
+        return numOutComponents;
+    }
+
+    private synchronized void doTransform(LCMSImageLayout in,
+                                          LCMSImageLayout out) {
+        // update native transfrom if needed
+        if (ID == 0L ||
+            inFormatter != in.pixelType ||
+            outFormatter != out.pixelType) {
+
+            if (ID != 0L) {
+                // Disposer will destroy forgotten transform
+                disposerReferent = new Object();
+            }
+            inFormatter = in.pixelType;
+            outFormatter = out.pixelType;
+
+            ID = LCMS.createNativeTransform(profileIDs, renderType,
+                                            inFormatter, outFormatter,
+                                            disposerReferent);
+        }
+
+        LCMS.colorConvert(this, in, out);
     }
 
     public void colorConvert(BufferedImage src, BufferedImage dst) {
         if (LCMSImageLayout.isSupported(src) &&
             LCMSImageLayout.isSupported(dst))
         {
-            synchronized(this) {
-                LCMS.colorConvert(this, new LCMSImageLayout(src),
-                                  new LCMSImageLayout(dst));
-            }
+            doTransform(new LCMSImageLayout(src), new LCMSImageLayout(dst));
             return;
         }
         LCMSImageLayout srcIL, dstIL;
@@ -204,9 +243,8 @@
                     }
                 }
                 // color convert srcLine to dstLine
-                synchronized (this) {
-                    LCMS.colorConvert(this, srcIL, dstIL);
-                }
+                doTransform(srcIL, dstIL);
+
                 // convert dst scanline
                 pixel = null;
                 idx = 0;
@@ -263,9 +301,8 @@
                     }
                 }
                 // color convert srcLine to dstLine
-                synchronized(this) {
-                    LCMS.colorConvert(this, srcIL, dstIL);
-                }
+                doTransform(srcIL, dstIL);
+
                 // convert dst scanline
                 pixel = null;
                 idx = 0;
@@ -377,9 +414,7 @@
             }
 
             // color convert srcLine to dstLine
-            synchronized(this) {
-                LCMS.colorConvert(this, srcIL, dstIL);
-            }
+            doTransform(srcIL, dstIL);
 
             // store dst scanline
             xd = dst.getMinX();
@@ -470,9 +505,7 @@
                 }
 
                 // color convert srcLine to dstLine
-                synchronized(this) {
-                    LCMS.colorConvert(this, srcIL, dstIL);
-                }
+                doTransform(srcIL, dstIL);
 
                 // store dst scanline
                 xd = dst.getMinX();
@@ -513,9 +546,8 @@
                 }
 
                 // color convert srcLine to dstLine
-                synchronized(this) {
-                    LCMS.colorConvert(this, srcIL, dstIL);
-                }
+                doTransform(srcIL, dstIL);
+
                 // store dst scanline
                 xd = dst.getMinX();
                 idx = 0;
@@ -550,9 +582,7 @@
             LCMSImageLayout.CHANNELS_SH(getNumOutComponents()) |
             LCMSImageLayout.BYTES_SH(2), getNumOutComponents()*2);
 
-        synchronized(this) {
-            LCMS.colorConvert(this, srcIL, dstIL);
-        }
+        doTransform(srcIL, dstIL);
 
         return dst;
     }
@@ -572,9 +602,7 @@
             LCMSImageLayout.CHANNELS_SH(getNumOutComponents()) |
             LCMSImageLayout.BYTES_SH(1), getNumOutComponents());
 
-        synchronized(this) {
-            LCMS.colorConvert(this, srcIL, dstIL);
-        }
+        doTransform(srcIL, dstIL);
 
         return dst;
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/net/sdp/SdpSupport.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.net.sdp;
+
+import java.io.IOException;
+import java.io.FileDescriptor;
+import java.security.AccessController;
+
+import sun.misc.SharedSecrets;
+import sun.misc.JavaIOFileDescriptorAccess;
+
+
+/**
+ * This class defines methods for creating SDP sockets or "converting" existing
+ * file descriptors, referencing (unbound) TCP sockets, to SDP.
+ */
+
+public final class SdpSupport {
+    private static final String os = AccessController
+        .doPrivileged(new sun.security.action.GetPropertyAction("os.name"));
+    private static final boolean isSupported = (os.equals("SunOS") || (os.equals("Linux")));
+    private static final JavaIOFileDescriptorAccess fdAccess =
+        SharedSecrets.getJavaIOFileDescriptorAccess();
+
+    private SdpSupport() { }
+
+    /**
+     * Creates a SDP socket, returning file descriptor referencing the socket.
+     */
+    public static FileDescriptor createSocket() throws IOException {
+        if (!isSupported)
+            throw new UnsupportedOperationException("SDP not supported on this platform");
+        int fdVal = create0();
+        FileDescriptor fd = new FileDescriptor();
+        fdAccess.set(fd, fdVal);
+        return fd;
+    }
+
+    /**
+     * Converts an existing file descriptor, that references an unbound TCP socket,
+     * to SDP.
+     */
+    public static void convertSocket(FileDescriptor fd) throws IOException {
+        if (!isSupported)
+            throw new UnsupportedOperationException("SDP not supported on this platform");
+        int fdVal = fdAccess.get(fd);
+        convert0(fdVal);
+    }
+
+    private static native int create0() throws IOException;
+
+    private static native void convert0(int fd) throws IOException;
+
+    static {
+        AccessController.doPrivileged(
+            new sun.security.action.LoadLibraryAction("net"));
+    }
+}
--- a/src/share/classes/sun/nio/ch/FileChannelImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/nio/ch/FileChannelImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -545,6 +545,8 @@
                                          long position, long count)
         throws IOException
     {
+        if (!src.readable)
+            throw new NonReadableChannelException();
         synchronized (src.positionLock) {
             long pos = src.position();
             long max = Math.min(count, src.size() - pos);
--- a/src/share/classes/sun/nio/ch/IOUtil.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/nio/ch/IOUtil.java	Fri Sep 24 16:41:32 2010 -0700
@@ -319,7 +319,12 @@
 
     static native boolean randomBytes(byte[] someBytes);
 
-    static native void initPipe(int[] fda, boolean blocking);
+    /**
+     * Returns two file descriptors for a pipe encoded in a long.
+     * The read end of the pipe is returned in the high 32 bits,
+     * while the write end is returned in the low 32 bits.
+     */
+    static native long makePipe(boolean blocking);
 
     static native boolean drain(int fd) throws IOException;
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/nio/ch/Secrets.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.nio.ch;
+
+import java.nio.channels.SocketChannel;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.spi.SelectorProvider;
+import java.io.FileDescriptor;
+import java.io.IOException;
+
+/**
+ * Provides access to implementation private constructors and methods.
+ */
+
+public final class Secrets {
+    private Secrets() { }
+
+    private static SelectorProvider provider() {
+        SelectorProvider p = SelectorProvider.provider();
+        if (!(p instanceof SelectorProviderImpl))
+            throw new UnsupportedOperationException();
+        return p;
+    }
+
+    public static SocketChannel newSocketChannel(FileDescriptor fd) {
+        try {
+            return new SocketChannelImpl(provider(), fd, false);
+        } catch (IOException ioe) {
+            throw new AssertionError(ioe);
+        }
+    }
+
+    public static ServerSocketChannel newServerSocketChannel(FileDescriptor fd) {
+        try {
+            return new ServerSocketChannelImpl(provider(), fd, false);
+        } catch (IOException ioe) {
+            throw new AssertionError(ioe);
+        }
+    }
+}
--- a/src/share/classes/sun/nio/ch/ServerSocketChannelImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/nio/ch/ServerSocketChannelImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -80,21 +80,24 @@
     // -- End of fields protected by stateLock
 
 
-    public ServerSocketChannelImpl(SelectorProvider sp) throws IOException {
+    ServerSocketChannelImpl(SelectorProvider sp) throws IOException {
         super(sp);
         this.fd =  Net.serverSocket(true);
         this.fdVal = IOUtil.fdVal(fd);
         this.state = ST_INUSE;
     }
 
-    public ServerSocketChannelImpl(SelectorProvider sp, FileDescriptor fd)
+    ServerSocketChannelImpl(SelectorProvider sp,
+                            FileDescriptor fd,
+                            boolean bound)
         throws IOException
     {
         super(sp);
         this.fd =  fd;
         this.fdVal = IOUtil.fdVal(fd);
         this.state = ST_INUSE;
-        localAddress = Net.localAddress(fd);
+        if (bound)
+            localAddress = Net.localAddress(fd);
     }
 
     public ServerSocket socket() {
--- a/src/share/classes/sun/nio/ch/SocketChannelImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/nio/ch/SocketChannelImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -103,6 +103,19 @@
         this.state = ST_UNCONNECTED;
     }
 
+    SocketChannelImpl(SelectorProvider sp,
+                      FileDescriptor fd,
+                      boolean bound)
+        throws IOException
+    {
+        super(sp);
+        this.fd = fd;
+        this.fdVal = IOUtil.fdVal(fd);
+        this.state = ST_UNCONNECTED;
+        if (bound)
+            this.localAddress = Net.localAddress(fd);
+    }
+
     // Constructor for sockets obtained from server sockets
     //
     SocketChannelImpl(SelectorProvider sp,
--- a/src/share/classes/sun/security/tools/policytool/PolicyTool.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/security/tools/policytool/PolicyTool.java	Fri Sep 24 16:41:32 2010 -0700
@@ -4231,7 +4231,10 @@
     super("SQLPermission",
         "java.sql.SQLPermission",
         new String[]    {
-                "setLog"
+                "setLog",
+                "callAbort",
+                "setSyncFactory",
+                "setNetworkTimeout",
                 },
         null);
     }
--- a/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUI.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUI.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2010, Oracle and/or its affiliates. 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
@@ -551,6 +551,9 @@
 
         public void paintBorder(Component c, Graphics g, int x, int y,
                                 int width, int height) {
+            if (!(c instanceof JComponent)) {
+                return;
+            }
             JComponent jc = (JComponent)c;
             SynthContext context = getContext(jc);
             SynthStyle style = context.getStyle();
--- a/src/share/classes/sun/util/LocaleServiceProviderPool.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/util/LocaleServiceProviderPool.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -28,18 +28,20 @@
 import java.security.AccessController;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
-import java.util.Arrays;
+import java.util.ArrayList;
 import java.util.HashSet;
-import java.util.Iterator;
+import java.util.IllformedLocaleException;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Locale;
+import java.util.Locale.Builder;
 import java.util.Map;
+import java.util.ResourceBundle.Control;
 import java.util.ServiceLoader;
-import java.util.ServiceConfigurationError;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.spi.LocaleServiceProvider;
+
 import sun.util.logging.PlatformLogger;
 import sun.util.resources.LocaleData;
 import sun.util.resources.OpenListResourceBundle;
@@ -90,6 +92,16 @@
     private Set<Locale> providerLocales = null;
 
     /**
+     * Special locale for ja_JP with Japanese calendar
+     */
+    private static Locale locale_ja_JP_JP = new Locale("ja", "JP", "JP");
+
+    /**
+     * Special locale for th_TH with Thai numbering system
+     */
+    private static Locale locale_th_TH_TH = new Locale("th", "TH", "TH");
+
+    /**
      * A factory method that returns a singleton instance
      */
     public static LocaleServiceProviderPool getPool(Class<? extends LocaleServiceProvider> providerClass) {
@@ -153,14 +165,20 @@
                 java.util.spi.CurrencyNameProvider.class,
                 java.util.spi.LocaleNameProvider.class,
                 java.util.spi.TimeZoneNameProvider.class };
-            Set<Locale> all = new HashSet<Locale>(Arrays.asList(
-                    LocaleData.getAvailableLocales())
-            );
+
+            // Normalize locales for look up
+            Locale[] allLocales = LocaleData.getAvailableLocales();
+            Set<Locale> all = new HashSet<Locale>(allLocales.length);
+            for (Locale locale : allLocales) {
+                all.add(getLookupLocale(locale));
+            }
+
             for (Class providerClass : providerClasses) {
                 LocaleServiceProviderPool pool =
                     LocaleServiceProviderPool.getPool(providerClass);
                 all.addAll(pool.getProviderLocales());
             }
+
             allAvailableLocales = all.toArray(new Locale[0]);
         }
     }
@@ -196,7 +214,8 @@
     }
 
     /**
-     * Returns an array of available locales from providers.
+     * Returns an array of available locales (already normalized
+     * for service lookup) from providers.
      * Note that this method does not return a defensive copy.
      *
      * @return list of the provider locales
@@ -208,7 +227,7 @@
                 for (LocaleServiceProvider lsp : providers) {
                     Locale[] locales = lsp.getAvailableLocales();
                     for (Locale locale: locales) {
-                        providerLocales.add(locale);
+                        providerLocales.add(getLookupLocale(locale));
                     }
                 }
             }
@@ -227,15 +246,19 @@
     }
 
     /**
-     * Returns an array of available locales supported by the JRE.
+     * Returns an array of available locales (already normalized for
+     * service lookup) supported by the JRE.
      * Note that this method does not return a defensive copy.
      *
      * @return list of the available JRE locales
      */
     private synchronized List<Locale> getJRELocales() {
         if (availableJRELocales == null) {
-            availableJRELocales =
-                Arrays.asList(LocaleData.getAvailableLocales());
+            Locale[] allLocales = LocaleData.getAvailableLocales();
+            availableJRELocales = new ArrayList<Locale>(allLocales.length);
+            for (Locale locale : allLocales) {
+                availableJRELocales.add(getLookupLocale(locale));
+            }
         }
         return availableJRELocales;
     }
@@ -249,7 +272,7 @@
      */
     private boolean isJRESupported(Locale locale) {
         List<Locale> locales = getJRELocales();
-        return locales.contains(locale);
+        return locales.contains(getLookupLocale(locale));
     }
 
     /**
@@ -325,7 +348,7 @@
                 bundleKey = key;
             }
             Locale bundleLocale = (bundle != null ? bundle.getLocale() : null);
-            Locale requested = locale;
+            List<Locale> lookupLocales = getLookupLocales(locale);
             P lsp;
             S providersObj = null;
 
@@ -333,21 +356,30 @@
             // to the requested locale than the bundle we've found (for
             // localized names), or Java runtime's supported locale
             // (for localized objects)
-            while ((locale = findProviderLocale(locale, bundleLocale)) != null) {
-
-                lsp = (P)findProvider(locale);
-
-                if (lsp != null) {
-                    providersObj = getter.getObject(lsp, requested, key, params);
-                    if (providersObj != null) {
-                        return providersObj;
-                    } else if (isObjectProvider) {
-                        config(
-                            "A locale sensitive service provider returned null for a localized objects,  which should not happen.  provider: " + lsp + " locale: " + requested);
+            Set<Locale> provLoc = getProviderLocales();
+            for (int i = 0; i < lookupLocales.size(); i++) {
+                Locale current = lookupLocales.get(i);
+                if (bundleLocale != null) {
+                    if (current.equals(bundleLocale)) {
+                        break;
+                    }
+                } else {
+                    if (isJRESupported(current)) {
+                        break;
                     }
                 }
-
-                locale = getParentLocale(locale);
+                if (provLoc.contains(current)) {
+                    lsp = (P)findProvider(current);
+                    if (lsp != null) {
+                        providersObj = getter.getObject(lsp, locale, key, params);
+                        if (providersObj != null) {
+                            return providersObj;
+                        } else if (isObjectProvider) {
+                            config(
+                                "A locale sensitive service provider returned null for a localized objects,  which should not happen.  provider: " + lsp + " locale: " + locale);
+                        }
+                    }
+                }
             }
 
             // look up the JRE bundle and its parent chain.  Only
@@ -361,7 +393,7 @@
                 } else {
                     lsp = (P)findProvider(bundleLocale);
                     if (lsp != null) {
-                        providersObj = getter.getObject(lsp, requested, key, params);
+                        providersObj = getter.getObject(lsp, locale, key, params);
                         if (providersObj != null) {
                             return providersObj;
                         }
@@ -399,6 +431,8 @@
             for (LocaleServiceProvider lsp : providers) {
                 Locale[] locales = lsp.getAvailableLocales();
                 for (Locale available: locales) {
+                    // normalize
+                    available = getLookupLocale(available);
                     if (locale.equals(available)) {
                         LocaleServiceProvider providerInCache =
                             providersCache.put(locale, lsp);
@@ -414,66 +448,51 @@
     }
 
     /**
-     * Returns the provider's locale that is the most appropriate
-     * within the range
-     *
-     * @param start the given locale that is used as the starting one
-     * @param end the given locale that is used as the end one (exclusive),
-     *     or null if it reaching any of the JRE supported locale should
-     *     terminate the look up.
-     * @return the most specific locale within the range, or null
-     *     if no provider locale found in that range.
+     * Returns a list of candidate locales for service look up.
+     * @param locale the input locale
+     * @return the list of candiate locales for the given locale
      */
-    private Locale findProviderLocale(Locale start, Locale end) {
-        Set<Locale> provLoc = getProviderLocales();
-        Locale current = start;
-
-        while (current != null) {
-            if (end != null) {
-                if (current.equals(end)) {
-                    current = null;
-                    break;
-                }
-            } else {
-                if (isJRESupported(current)) {
-                    current = null;
-                    break;
-                }
-            }
-
-            if (provLoc.contains(current)) {
-                break;
-            }
-
-            current = getParentLocale(current);
-        }
-
-        return current;
+    private static List<Locale> getLookupLocales(Locale locale) {
+        // Note: We currently use the default implementation of
+        // ResourceBundle.Control.getCandidateLocales. The result
+        // returned by getCandidateLocales are already normalized
+        // (no extensions) for service look up.
+        List<Locale> lookupLocales = new Control(){}.getCandidateLocales("", locale);
+        return lookupLocales;
     }
 
     /**
-     * Returns the parent locale.
+     * Returns an instance of Locale used for service look up.
+     * The result Locale has no extensions except for ja_JP_JP
+     * and th_TH_TH
      *
      * @param locale the locale
-     * @return the parent locale
+     * @return the locale used for service look up
      */
-    private static Locale getParentLocale(Locale locale) {
-        String variant = locale.getVariant();
-        if (variant != "") {
-            int underscoreIndex = variant.lastIndexOf('_');
-            if (underscoreIndex != (-1)) {
-                return new Locale(locale.getLanguage(), locale.getCountry(),
-                                  variant.substring(0, underscoreIndex));
-            } else {
-                return new Locale(locale.getLanguage(), locale.getCountry());
+    private static Locale getLookupLocale(Locale locale) {
+        Locale lookupLocale = locale;
+        Set<Character> extensions = locale.getExtensionKeys();
+        if (!extensions.isEmpty()
+                && !locale.equals(locale_ja_JP_JP)
+                && !locale.equals(locale_th_TH_TH)) {
+            // remove extensions
+            Builder locbld = new Builder();
+            try {
+                locbld.setLocale(locale);
+                locbld.clearExtensions();
+                lookupLocale = locbld.build();
+            } catch (IllformedLocaleException e) {
+                // A Locale with non-empty extensions
+                // should have well-formed fields except
+                // for ja_JP_JP and th_TH_TH. Therefore,
+                // it should never enter in this catch clause.
+                config("A locale(" + locale + ") has non-empty extensions, but has illformed fields.");
+
+                // Fallback - script field will be lost.
+                lookupLocale = new Locale(locale.getLanguage(), locale.getCountry(), locale.getVariant());
             }
-        } else if (locale.getCountry() != "") {
-            return new Locale(locale.getLanguage());
-        } else if (locale.getLanguage() != "") {
-            return Locale.ROOT;
-        } else {
-            return null;
         }
+        return lookupLocale;
     }
 
     /**
--- a/src/share/classes/sun/util/calendar/ZoneInfoFile.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/util/calendar/ZoneInfoFile.java	Fri Sep 24 16:41:32 2010 -0700
@@ -30,6 +30,7 @@
 import  java.io.FileNotFoundException;
 import  java.io.IOException;
 import  java.lang.ref.SoftReference;
+import  java.nio.file.FileSystems;
 import  java.security.AccessController;
 import  java.security.PrivilegedAction;
 import  java.security.PrivilegedActionException;
@@ -472,17 +473,18 @@
 
     private static Map<String, ZoneInfo> zoneInfoObjects = null;
 
-    private static final String ziDir;
-    static {
-        String zi = (String) AccessController.doPrivileged(
-                         new sun.security.action.GetPropertyAction("java.home"))
-                    + File.separator + "lib" + File.separator + "zi";
-        try {
-            zi = new File(zi).getCanonicalPath();
-        } catch (Exception e) {
-        }
-        ziDir = zi;
-    }
+    private static final String ziDir = AccessController.doPrivileged(
+        new PrivilegedAction<String>() {
+            public String run() {
+                String zi = System.getProperty("java.home") +
+                    File.separator + "lib" + File.separator + "zi";
+                try {
+                    zi = FileSystems.getDefault().getPath(zi).toRealPath(true).toString();
+                } catch(Exception e) {
+                }
+                return zi;
+            }
+        });
 
     /**
      * Converts the given time zone ID to a platform dependent path
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/AsciiUtil.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009, International Business Machines Corporation and         *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+public final class AsciiUtil {
+    public static boolean caseIgnoreMatch(String s1, String s2) {
+        if (s1 == s2) {
+            return true;
+        }
+        int len = s1.length();
+        if (len != s2.length()) {
+            return false;
+        }
+        int i = 0;
+        while (i < len) {
+            char c1 = s1.charAt(i);
+            char c2 = s2.charAt(i);
+            if (c1 != c2 && toLower(c1) != toLower(c2)) {
+                break;
+            }
+            i++;
+        }
+        return (i == len);
+    }
+
+    public static int caseIgnoreCompare(String s1, String s2) {
+        if (s1 == s2) {
+            return 0;
+        }
+        return AsciiUtil.toLowerString(s1).compareTo(AsciiUtil.toLowerString(s2));
+    }
+
+
+    public static char toUpper(char c) {
+        if (c >= 'a' && c <= 'z') {
+            c -= 0x20;
+        }
+        return c;
+    }
+
+    public static char toLower(char c) {
+        if (c >= 'A' && c <= 'Z') {
+            c += 0x20;
+        }
+        return c;
+    }
+
+    public static String toLowerString(String s) {
+        int idx = 0;
+        for (; idx < s.length(); idx++) {
+            char c = s.charAt(idx);
+            if (c >= 'A' && c <= 'Z') {
+                break;
+            }
+        }
+        if (idx == s.length()) {
+            return s;
+        }
+        StringBuilder buf = new StringBuilder(s.substring(0, idx));
+        for (; idx < s.length(); idx++) {
+            buf.append(toLower(s.charAt(idx)));
+        }
+        return buf.toString();
+    }
+
+    public static String toUpperString(String s) {
+        int idx = 0;
+        for (; idx < s.length(); idx++) {
+            char c = s.charAt(idx);
+            if (c >= 'a' && c <= 'z') {
+                break;
+            }
+        }
+        if (idx == s.length()) {
+            return s;
+        }
+        StringBuilder buf = new StringBuilder(s.substring(0, idx));
+        for (; idx < s.length(); idx++) {
+            buf.append(toUpper(s.charAt(idx)));
+        }
+        return buf.toString();
+    }
+
+    public static String toTitleString(String s) {
+        if (s.length() == 0) {
+            return s;
+        }
+        int idx = 0;
+        char c = s.charAt(idx);
+        if (!(c >= 'a' && c <= 'z')) {
+            for (idx = 1; idx < s.length(); idx++) {
+                if (c >= 'A' && c <= 'Z') {
+                    break;
+                }
+            }
+        }
+        if (idx == s.length()) {
+            return s;
+        }
+        StringBuilder buf = new StringBuilder(s.substring(0, idx));
+        if (idx == 0) {
+            buf.append(toUpper(s.charAt(idx)));
+            idx++;
+        }
+        for (; idx < s.length(); idx++) {
+            buf.append(toLower(s.charAt(idx)));
+        }
+        return buf.toString();
+    }
+
+    public static boolean isAlpha(char c) {
+        return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
+    }
+
+    public static boolean isAlphaString(String s) {
+        boolean b = true;
+        for (int i = 0; i < s.length(); i++) {
+            if (!isAlpha(s.charAt(i))) {
+                b = false;
+                break;
+            }
+        }
+        return b;
+    }
+
+    public static boolean isNumeric(char c) {
+        return (c >= '0' && c <= '9');
+    }
+
+    public static boolean isNumericString(String s) {
+        boolean b = true;
+        for (int i = 0; i < s.length(); i++) {
+            if (!isNumeric(s.charAt(i))) {
+                b = false;
+                break;
+            }
+        }
+        return b;
+    }
+
+    public static boolean isAlphaNumeric(char c) {
+        return isAlpha(c) || isNumeric(c);
+    }
+
+    public static boolean isAlphaNumericString(String s) {
+        boolean b = true;
+        for (int i = 0; i < s.length(); i++) {
+            if (!isAlphaNumeric(s.charAt(i))) {
+                b = false;
+                break;
+            }
+        }
+        return b;
+    }
+
+    public static class CaseInsensitiveKey {
+        private String _key;
+        private int _hash;
+
+        public CaseInsensitiveKey(String key) {
+            _key = key;
+            _hash = AsciiUtil.toLowerString(key).hashCode();
+        }
+
+        public boolean equals(Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (o instanceof CaseInsensitiveKey) {
+                return AsciiUtil.caseIgnoreMatch(_key, ((CaseInsensitiveKey)o)._key);
+            }
+            return false;
+        }
+
+        public int hashCode() {
+            return _hash;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/BaseLocale.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,253 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009-2010, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+
+package sun.util.locale;
+
+
+public final class BaseLocale {
+
+    public static final String SEP = "_";
+
+    private static final Cache CACHE = new Cache();
+    public static final BaseLocale ROOT = BaseLocale.getInstance("", "", "", "");
+
+    private String _language = "";
+    private String _script = "";
+    private String _region = "";
+    private String _variant = "";
+
+    private transient volatile int _hash = 0;
+
+    private BaseLocale(String language, String script, String region, String variant) {
+        if (language != null) {
+            _language = AsciiUtil.toLowerString(language).intern();
+        }
+        if (script != null) {
+            _script = AsciiUtil.toTitleString(script).intern();
+        }
+        if (region != null) {
+            _region = AsciiUtil.toUpperString(region).intern();
+        }
+        if (variant != null) {
+            _variant = variant.intern();
+        }
+    }
+
+    public static BaseLocale getInstance(String language, String script, String region, String variant) {
+        // JDK uses deprecated ISO639.1 language codes for he, yi and id
+        if (AsciiUtil.caseIgnoreMatch(language, "he")) {
+            language = "iw";
+        } else if (AsciiUtil.caseIgnoreMatch(language, "yi")) {
+            language = "ji";
+        } else if (AsciiUtil.caseIgnoreMatch(language, "id")) {
+            language = "in";
+        }
+
+        Key key = new Key(language, script, region, variant);
+        BaseLocale baseLocale = CACHE.get(key);
+        return baseLocale;
+    }
+
+    public String getLanguage() {
+        return _language;
+    }
+
+    public String getScript() {
+        return _script;
+    }
+
+    public String getRegion() {
+        return _region;
+    }
+
+    public String getVariant() {
+        return _variant;
+    }
+
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!(obj instanceof BaseLocale)) {
+            return false;
+        }
+        BaseLocale other = (BaseLocale)obj;
+        return hashCode() == other.hashCode()
+                && _language.equals(other._language)
+                && _script.equals(other._script)
+                && _region.equals(other._region)
+                && _variant.equals(other._variant);
+    }
+
+    public String toString() {
+        StringBuilder buf = new StringBuilder();
+        if (_language.length() > 0) {
+            buf.append("language=");
+            buf.append(_language);
+        }
+        if (_script.length() > 0) {
+            if (buf.length() > 0) {
+                buf.append(", ");
+            }
+            buf.append("script=");
+            buf.append(_script);
+        }
+        if (_region.length() > 0) {
+            if (buf.length() > 0) {
+                buf.append(", ");
+            }
+            buf.append("region=");
+            buf.append(_region);
+        }
+        if (_variant.length() > 0) {
+            if (buf.length() > 0) {
+                buf.append(", ");
+            }
+            buf.append("variant=");
+            buf.append(_variant);
+        }
+        return buf.toString();
+    }
+
+    public int hashCode() {
+        int h = _hash;
+        if (h == 0) {
+            // Generating a hash value from language, script, region and variant
+            for (int i = 0; i < _language.length(); i++) {
+                h = 31*h + _language.charAt(i);
+            }
+            for (int i = 0; i < _script.length(); i++) {
+                h = 31*h + _script.charAt(i);
+            }
+            for (int i = 0; i < _region.length(); i++) {
+                h = 31*h + _region.charAt(i);
+            }
+            for (int i = 0; i < _variant.length(); i++) {
+                h = 31*h + _variant.charAt(i);
+            }
+            _hash = h;
+        }
+        return h;
+    }
+
+    private static class Key implements Comparable<Key> {
+        private String _lang = "";
+        private String _scrt = "";
+        private String _regn = "";
+        private String _vart = "";
+
+        private volatile int _hash; // Default to 0
+
+        public Key(String language, String script, String region, String variant) {
+            if (language != null) {
+                _lang = language;
+            }
+            if (script != null) {
+                _scrt = script;
+            }
+            if (region != null) {
+                _regn = region;
+            }
+            if (variant != null) {
+                _vart = variant;
+            }
+        }
+
+        public boolean equals(Object obj) {
+            return (this == obj) ||
+                    (obj instanceof Key)
+                    && AsciiUtil.caseIgnoreMatch(((Key)obj)._lang, this._lang)
+                    && AsciiUtil.caseIgnoreMatch(((Key)obj)._scrt, this._scrt)
+                    && AsciiUtil.caseIgnoreMatch(((Key)obj)._regn, this._regn)
+                    && ((Key)obj)._vart.equals(_vart); // variant is case sensitive in JDK!
+        }
+
+        public int compareTo(Key other) {
+            int res = AsciiUtil.caseIgnoreCompare(this._lang, other._lang);
+            if (res == 0) {
+                res = AsciiUtil.caseIgnoreCompare(this._scrt, other._scrt);
+                if (res == 0) {
+                    res = AsciiUtil.caseIgnoreCompare(this._regn, other._regn);
+                    if (res == 0) {
+                        res = this._vart.compareTo(other._vart);
+                    }
+                }
+            }
+            return res;
+        }
+
+        public int hashCode() {
+            int h = _hash;
+            if (h == 0) {
+                // Generating a hash value from language, script, region and variant
+                for (int i = 0; i < _lang.length(); i++) {
+                    h = 31*h + AsciiUtil.toLower(_lang.charAt(i));
+                }
+                for (int i = 0; i < _scrt.length(); i++) {
+                    h = 31*h + AsciiUtil.toLower(_scrt.charAt(i));
+                }
+                for (int i = 0; i < _regn.length(); i++) {
+                    h = 31*h + AsciiUtil.toLower(_regn.charAt(i));
+                }
+                for (int i = 0; i < _vart.length(); i++) {
+                    h = 31*h + _vart.charAt(i);
+                }
+                _hash = h;
+            }
+            return h;
+        }
+
+        public static Key normalize(Key key) {
+            String lang = AsciiUtil.toLowerString(key._lang).intern();
+            String scrt = AsciiUtil.toTitleString(key._scrt).intern();
+            String regn = AsciiUtil.toUpperString(key._regn).intern();
+            String vart = key._vart.intern(); // preserve upper/lower cases
+
+            return new Key(lang, scrt, regn, vart);
+        }
+    }
+
+    private static class Cache extends LocaleObjectCache<Key, BaseLocale> {
+
+        public Cache() {
+        }
+
+        protected Key normalizeKey(Key key) {
+            return Key.normalize(key);
+        }
+
+        protected BaseLocale createObject(Key key) {
+            return new BaseLocale(key._lang, key._scrt, key._regn, key._vart);
+        }
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/Extension.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009-2010, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+
+public class Extension {
+    private char _key;
+    protected String _value;
+
+    protected Extension(char key) {
+        _key = key;
+    }
+
+    Extension(char key, String value) {
+        _key = key;
+        _value = value;
+    }
+
+    public char getKey() {
+        return _key;
+    }
+
+    public String getValue() {
+        return _value;
+    }
+
+    public String getID() {
+        return _key + LanguageTag.SEP + _value;
+    }
+
+    public String toString() {
+        return getID();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/InternalLocaleBuilder.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,705 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009-2010, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public final class InternalLocaleBuilder {
+
+    private String _language = "";
+    private String _script = "";
+    private String _region = "";
+    private String _variant = "";
+
+    private static final CaseInsensitiveChar PRIVUSE_KEY = new CaseInsensitiveChar(LanguageTag.PRIVATEUSE.charAt(0));
+
+    private HashMap<CaseInsensitiveChar, String> _extensions;
+    private HashSet<CaseInsensitiveString> _uattributes;
+    private HashMap<CaseInsensitiveString, String> _ukeywords;
+
+
+    public InternalLocaleBuilder() {
+    }
+
+    public InternalLocaleBuilder setLanguage(String language) throws LocaleSyntaxException {
+        if (language == null || language.length() == 0) {
+            _language = "";
+        } else {
+            if (!LanguageTag.isLanguage(language)) {
+                throw new LocaleSyntaxException("Ill-formed language: " + language, 0);
+            }
+            _language = language;
+        }
+        return this;
+    }
+
+    public InternalLocaleBuilder setScript(String script) throws LocaleSyntaxException {
+        if (script == null || script.length() == 0) {
+            _script = "";
+        } else {
+            if (!LanguageTag.isScript(script)) {
+                throw new LocaleSyntaxException("Ill-formed script: " + script, 0);
+            }
+            _script = script;
+        }
+        return this;
+    }
+
+    public InternalLocaleBuilder setRegion(String region) throws LocaleSyntaxException {
+        if (region == null || region.length() == 0) {
+            _region = "";
+        } else {
+            if (!LanguageTag.isRegion(region)) {
+                throw new LocaleSyntaxException("Ill-formed region: " + region, 0);
+            }
+            _region = region;
+        }
+        return this;
+    }
+
+    public InternalLocaleBuilder setVariant(String variant) throws LocaleSyntaxException {
+        if (variant == null || variant.length() == 0) {
+            _variant = "";
+        } else {
+            // normalize separators to "_"
+            String var = variant.replaceAll(LanguageTag.SEP, BaseLocale.SEP);
+            int errIdx = checkVariants(var, BaseLocale.SEP);
+            if (errIdx != -1) {
+                throw new LocaleSyntaxException("Ill-formed variant: " + variant, errIdx);
+            }
+            _variant = var;
+        }
+        return this;
+    }
+
+    public InternalLocaleBuilder addUnicodeLocaleAttribute(String attribute) throws LocaleSyntaxException {
+        if (!UnicodeLocaleExtension.isAttribute(attribute)) {
+            throw new LocaleSyntaxException("Ill-formed Unicode locale attribute: " + attribute);
+        }
+        // Use case insensitive string to prevent duplication
+        if (_uattributes == null) {
+            _uattributes = new HashSet<CaseInsensitiveString>(4);
+        }
+        _uattributes.add(new CaseInsensitiveString(attribute));
+        return this;
+    }
+
+    public InternalLocaleBuilder removeUnicodeLocaleAttribute(String attribute) throws LocaleSyntaxException {
+        if (attribute == null || !UnicodeLocaleExtension.isAttribute(attribute)) {
+            throw new LocaleSyntaxException("Ill-formed Unicode locale attribute: " + attribute);
+        }
+        if (_uattributes != null) {
+            _uattributes.remove(new CaseInsensitiveString(attribute));
+        }
+        return this;
+    }
+
+    public InternalLocaleBuilder setUnicodeLocaleKeyword(String key, String type) throws LocaleSyntaxException {
+        if (!UnicodeLocaleExtension.isKey(key)) {
+            throw new LocaleSyntaxException("Ill-formed Unicode locale keyword key: " + key);
+        }
+
+        CaseInsensitiveString cikey = new CaseInsensitiveString(key);
+        if (type == null) {
+            if (_ukeywords != null) {
+                // null type is used for remove the key
+                _ukeywords.remove(cikey);
+            }
+        } else {
+            if (type.length() != 0) {
+                // normalize separator to "-"
+                String tp = type.replaceAll(BaseLocale.SEP, LanguageTag.SEP);
+                // validate
+                StringTokenIterator itr = new StringTokenIterator(tp, LanguageTag.SEP);
+                while (!itr.isDone()) {
+                    String s = itr.current();
+                    if (!UnicodeLocaleExtension.isTypeSubtag(s)) {
+                        throw new LocaleSyntaxException("Ill-formed Unicode locale keyword type: " + type, itr.currentStart());
+                    }
+                    itr.next();
+                }
+            }
+            if (_ukeywords == null) {
+                _ukeywords = new HashMap<CaseInsensitiveString, String>(4);
+            }
+            _ukeywords.put(cikey, type);
+        }
+        return this;
+    }
+
+    public InternalLocaleBuilder setExtension(char singleton, String value) throws LocaleSyntaxException {
+        // validate key
+        boolean isBcpPrivateuse = LanguageTag.isPrivateusePrefixChar(singleton);
+        if (!isBcpPrivateuse && !LanguageTag.isExtensionSingletonChar(singleton)) {
+            throw new LocaleSyntaxException("Ill-formed extension key: " + singleton);
+        }
+
+        boolean remove = (value == null || value.length() == 0);
+        CaseInsensitiveChar key = new CaseInsensitiveChar(singleton);
+
+        if (remove) {
+            if (UnicodeLocaleExtension.isSingletonChar(key.value())) {
+                // clear entire Unicode locale extension
+                if (_uattributes != null) {
+                    _uattributes.clear();
+                }
+                if (_ukeywords != null) {
+                    _ukeywords.clear();
+                }
+            } else {
+                if (_extensions != null && _extensions.containsKey(key)) {
+                    _extensions.remove(key);
+                }
+            }
+        } else {
+            // validate value
+            String val = value.replaceAll(BaseLocale.SEP, LanguageTag.SEP);
+            StringTokenIterator itr = new StringTokenIterator(val, LanguageTag.SEP);
+            while (!itr.isDone()) {
+                String s = itr.current();
+                boolean validSubtag;
+                if (isBcpPrivateuse) {
+                    validSubtag = LanguageTag.isPrivateuseSubtag(s);
+                } else {
+                    validSubtag = LanguageTag.isExtensionSubtag(s);
+                }
+                if (!validSubtag) {
+                    throw new LocaleSyntaxException("Ill-formed extension value: " + s, itr.currentStart());
+                }
+                itr.next();
+            }
+
+            if (UnicodeLocaleExtension.isSingletonChar(key.value())) {
+                setUnicodeLocaleExtension(val);
+            } else {
+                if (_extensions == null) {
+                    _extensions = new HashMap<CaseInsensitiveChar, String>(4);
+                }
+                _extensions.put(key, val);
+            }
+        }
+        return this;
+    }
+
+    /*
+     * Set extension/private subtags in a single string representation
+     */
+    public InternalLocaleBuilder setExtensions(String subtags) throws LocaleSyntaxException {
+        if (subtags == null || subtags.length() == 0) {
+            clearExtensions();
+            return this;
+        }
+        subtags = subtags.replaceAll(BaseLocale.SEP, LanguageTag.SEP);
+        StringTokenIterator itr = new StringTokenIterator(subtags, LanguageTag.SEP);
+
+        List<String> extensions = null;
+        String privateuse = null;
+
+        int parsed = 0;
+        int start;
+
+        // Make a list of extension subtags
+        while (!itr.isDone()) {
+            String s = itr.current();
+            if (LanguageTag.isExtensionSingleton(s)) {
+                start = itr.currentStart();
+                String singleton = s;
+                StringBuilder sb = new StringBuilder(singleton);
+
+                itr.next();
+                while (!itr.isDone()) {
+                    s = itr.current();
+                    if (LanguageTag.isExtensionSubtag(s)) {
+                        sb.append(LanguageTag.SEP).append(s);
+                        parsed = itr.currentEnd();
+                    } else {
+                        break;
+                    }
+                    itr.next();
+                }
+
+                if (parsed < start) {
+                    throw new LocaleSyntaxException("Incomplete extension '" + singleton + "'", start);
+                }
+
+                if (extensions == null) {
+                    extensions = new ArrayList<String>(4);
+                }
+                extensions.add(sb.toString());
+            } else {
+                break;
+            }
+        }
+        if (!itr.isDone()) {
+            String s = itr.current();
+            if (LanguageTag.isPrivateusePrefix(s)) {
+                start = itr.currentStart();
+                StringBuilder sb = new StringBuilder(s);
+
+                itr.next();
+                while (!itr.isDone()) {
+                    s = itr.current();
+                    if (!LanguageTag.isPrivateuseSubtag(s)) {
+                        break;
+                    }
+                    sb.append(LanguageTag.SEP).append(s);
+                    parsed = itr.currentEnd();
+
+                    itr.next();
+                }
+                if (parsed <= start) {
+                    throw new LocaleSyntaxException("Incomplete privateuse:" + subtags.substring(start), start);
+                } else {
+                    privateuse = sb.toString();
+                }
+            }
+        }
+
+        if (!itr.isDone()) {
+            throw new LocaleSyntaxException("Ill-formed extension subtags:" + subtags.substring(itr.currentStart()), itr.currentStart());
+        }
+
+        return setExtensions(extensions, privateuse);
+    }
+
+    /*
+     * Set a list of BCP47 extensions and private use subtags
+     * BCP47 extensions are already validated and well-formed, but may contain duplicates
+     */
+    private InternalLocaleBuilder setExtensions(List<String> bcpExtensions, String privateuse) {
+        clearExtensions();
+
+        if (bcpExtensions != null && bcpExtensions.size() > 0) {
+            HashSet<CaseInsensitiveChar> processedExntensions = new HashSet<CaseInsensitiveChar>(bcpExtensions.size());
+            for (String bcpExt : bcpExtensions) {
+                CaseInsensitiveChar key = new CaseInsensitiveChar(bcpExt.charAt(0));
+                // ignore duplicates
+                if (!processedExntensions.contains(key)) {
+                    // each extension string contains singleton, e.g. "a-abc-def"
+                    if (UnicodeLocaleExtension.isSingletonChar(key.value())) {
+                        setUnicodeLocaleExtension(bcpExt.substring(2));
+                    } else {
+                        if (_extensions == null) {
+                            _extensions = new HashMap<CaseInsensitiveChar, String>(4);
+                        }
+                        _extensions.put(key, bcpExt.substring(2));
+                    }
+                }
+            }
+        }
+        if (privateuse != null && privateuse.length() > 0) {
+            // privateuse string contains prefix, e.g. "x-abc-def"
+            if (_extensions == null) {
+                _extensions = new HashMap<CaseInsensitiveChar, String>(1);
+            }
+            _extensions.put(new CaseInsensitiveChar(privateuse.charAt(0)), privateuse.substring(2));
+        }
+
+        return this;
+    }
+
+    /*
+     * Reset Builder's internal state with the given language tag
+     */
+    public InternalLocaleBuilder setLanguageTag(LanguageTag langtag) {
+        clear();
+        if (langtag.getExtlangs().size() > 0) {
+            _language = langtag.getExtlangs().get(0);
+        } else {
+            String language = langtag.getLanguage();
+            if (!language.equals(LanguageTag.UNDETERMINED)) {
+                _language = language;
+            }
+        }
+        _script = langtag.getScript();
+        _region = langtag.getRegion();
+
+        List<String> bcpVariants = langtag.getVariants();
+        if (bcpVariants.size() > 0) {
+            StringBuilder var = new StringBuilder(bcpVariants.get(0));
+            for (int i = 1; i < bcpVariants.size(); i++) {
+                var.append(BaseLocale.SEP).append(bcpVariants.get(i));
+            }
+            _variant = var.toString();
+        }
+
+        setExtensions(langtag.getExtensions(), langtag.getPrivateuse());
+
+        return this;
+    }
+
+    public InternalLocaleBuilder setLocale(BaseLocale base, LocaleExtensions extensions) throws LocaleSyntaxException {
+        String language = base.getLanguage();
+        String script = base.getScript();
+        String region = base.getRegion();
+        String variant = base.getVariant();
+
+        // Special backward compatibility support
+
+        // Exception 1 - ja_JP_JP
+        if (language.equals("ja") && region.equals("JP") && variant.equals("JP")) {
+            // When locale ja_JP_JP is created, ca-japanese is always there.
+            // The builder ignores the variant "JP"
+            assert("japanese".equals(extensions.getUnicodeLocaleType("ca")));
+            variant = "";
+        }
+        // Exception 2 - th_TH_TH
+        else if (language.equals("th") && region.equals("TH") && variant.equals("TH")) {
+            // When locale th_TH_TH is created, nu-thai is always there.
+            // The builder ignores the variant "TH"
+            assert("thai".equals(extensions.getUnicodeLocaleType("nu")));
+            variant = "";
+        }
+        // Exception 3 - no_NO_NY
+        else if (language.equals("no") && region.equals("NO") && variant.equals("NY")) {
+            // no_NO_NY is a valid locale and used by Java 6 or older versions.
+            // The build ignores the variant "NY" and change the language to "nn".
+            language = "nn";
+            variant = "";
+        }
+
+        // Validate base locale fields before updating internal state.
+        // LocaleExtensions always store validated/canonicalized values,
+        // so no checks are necessary.
+        if (language.length() > 0 && !LanguageTag.isLanguage(language)) {
+            throw new LocaleSyntaxException("Ill-formed language: " + language);
+        }
+
+        if (script.length() > 0 && !LanguageTag.isScript(script)) {
+            throw new LocaleSyntaxException("Ill-formed script: " + script);
+        }
+
+        if (region.length() > 0 && !LanguageTag.isRegion(region)) {
+            throw new LocaleSyntaxException("Ill-formed region: " + region);
+        }
+
+        if (variant.length() > 0) {
+            int errIdx = checkVariants(variant, BaseLocale.SEP);
+            if (errIdx != -1) {
+                throw new LocaleSyntaxException("Ill-formed variant: " + variant, errIdx);
+            }
+        }
+
+        // The input locale is validated at this point.
+        // Now, updating builder's internal fields.
+        _language = language;
+        _script = script;
+        _region = region;
+        _variant = variant;
+        clearExtensions();
+
+        Set<Character> extKeys = (extensions == null) ? null : extensions.getKeys();
+        if (extKeys != null) {
+            // map extensions back to builder's internal format
+            for (Character key : extKeys) {
+                Extension e = extensions.getExtension(key);
+                if (e instanceof UnicodeLocaleExtension) {
+                    UnicodeLocaleExtension ue = (UnicodeLocaleExtension)e;
+                    for (String uatr : ue.getUnicodeLocaleAttributes()) {
+                        if (_uattributes == null) {
+                            _uattributes = new HashSet<CaseInsensitiveString>(4);
+                        }
+                        _uattributes.add(new CaseInsensitiveString(uatr));
+                    }
+                    for (String ukey : ue.getUnicodeLocaleKeys()) {
+                        if (_ukeywords == null) {
+                            _ukeywords = new HashMap<CaseInsensitiveString, String>(4);
+                        }
+                        _ukeywords.put(new CaseInsensitiveString(ukey), ue.getUnicodeLocaleType(ukey));
+                    }
+                } else {
+                    if (_extensions == null) {
+                        _extensions = new HashMap<CaseInsensitiveChar, String>(4);
+                    }
+                    _extensions.put(new CaseInsensitiveChar(key.charValue()), e.getValue());
+                }
+            }
+        }
+        return this;
+    }
+
+    public InternalLocaleBuilder clear() {
+        _language = "";
+        _script = "";
+        _region = "";
+        _variant = "";
+        clearExtensions();
+        return this;
+    }
+
+    public InternalLocaleBuilder clearExtensions() {
+        if (_extensions != null) {
+            _extensions.clear();
+        }
+        if (_uattributes != null) {
+            _uattributes.clear();
+        }
+        if (_ukeywords != null) {
+            _ukeywords.clear();
+        }
+        return this;
+    }
+
+    public BaseLocale getBaseLocale() {
+        String language = _language;
+        String script = _script;
+        String region = _region;
+        String variant = _variant;
+
+        // Special private use subtag sequence identified by "lvariant" will be
+        // interpreted as Java variant.
+        if (_extensions != null) {
+            String privuse = _extensions.get(PRIVUSE_KEY);
+            if (privuse != null) {
+                StringTokenIterator itr = new StringTokenIterator(privuse, LanguageTag.SEP);
+                boolean sawPrefix = false;
+                int privVarStart = -1;
+                while (!itr.isDone()) {
+                    if (sawPrefix) {
+                        privVarStart = itr.currentStart();
+                        break;
+                    }
+                    if (AsciiUtil.caseIgnoreMatch(itr.current(), LanguageTag.PRIVUSE_VARIANT_PREFIX)) {
+                        sawPrefix = true;
+                    }
+                    itr.next();
+                }
+                if (privVarStart != -1) {
+                    StringBuilder sb = new StringBuilder(variant);
+                    if (sb.length() != 0) {
+                        sb.append(BaseLocale.SEP);
+                    }
+                    sb.append(privuse.substring(privVarStart).replaceAll(LanguageTag.SEP, BaseLocale.SEP));
+                    variant = sb.toString();
+                }
+            }
+        }
+
+        return BaseLocale.getInstance(language, script, region, variant);
+    }
+
+    public LocaleExtensions getLocaleExtensions() {
+        if ((_extensions == null || _extensions.size() == 0)
+                && (_uattributes == null || _uattributes.size() == 0)
+                && (_ukeywords == null || _ukeywords.size() == 0)) {
+            return LocaleExtensions.EMPTY_EXTENSIONS;
+        }
+
+        return new LocaleExtensions(_extensions, _uattributes, _ukeywords);
+    }
+
+    /*
+     * Remove special private use subtag sequence identified by "lvariant"
+     * and return the rest. Only used by LocaleExtensions
+     */
+    static String removePrivateuseVariant(String privuseVal) {
+        StringTokenIterator itr = new StringTokenIterator(privuseVal, LanguageTag.SEP);
+
+        // Note: privateuse value "abc-lvariant" is unchanged
+        // because no subtags after "lvariant".
+
+        int prefixStart = -1;
+        boolean sawPrivuseVar = false;
+        while (!itr.isDone()) {
+            if (prefixStart != -1) {
+                // Note: privateuse value "abc-lvariant" is unchanged
+                // because no subtags after "lvariant".
+                sawPrivuseVar = true;
+                break;
+            }
+            if (AsciiUtil.caseIgnoreMatch(itr.current(), LanguageTag.PRIVUSE_VARIANT_PREFIX)) {
+                prefixStart = itr.currentStart();
+            }
+            itr.next();
+        }
+        if (!sawPrivuseVar) {
+            return privuseVal;
+        }
+
+        assert(prefixStart == 0 || prefixStart > 1);
+        return (prefixStart == 0) ? null : privuseVal.substring(0, prefixStart -1);
+    }
+
+    /*
+     * Check if the given variant subtags separated by the given
+     * separator(s) are valid
+     */
+    private int checkVariants(String variants, String sep) {
+        StringTokenIterator itr = new StringTokenIterator(variants, sep);
+        while (!itr.isDone()) {
+            String s = itr.current();
+            if (!LanguageTag.isVariant(s)) {
+                return itr.currentStart();
+            }
+            itr.next();
+        }
+        return -1;
+    }
+
+    /*
+     * Private methods parsing Unicode Locale Extension subtags.
+     * Duplicated attributes/keywords will be ignored.
+     * The input must be a valid extension subtags (excluding singleton).
+     */
+    private void setUnicodeLocaleExtension(String subtags) {
+        // wipe out existing attributes/keywords
+        if (_uattributes != null) {
+            _uattributes.clear();
+        }
+        if (_ukeywords != null) {
+            _ukeywords.clear();
+        }
+
+        StringTokenIterator itr = new StringTokenIterator(subtags, LanguageTag.SEP);
+
+        // parse attributes
+        while (!itr.isDone()) {
+            if (!UnicodeLocaleExtension.isAttribute(itr.current())) {
+                break;
+            }
+            if (_uattributes == null) {
+                _uattributes = new HashSet<CaseInsensitiveString>(4);
+            }
+            _uattributes.add(new CaseInsensitiveString(itr.current()));
+            itr.next();
+        }
+
+        // parse keywords
+        CaseInsensitiveString key = null;
+        String type;
+        int typeStart = -1;
+        int typeEnd = -1;
+        while (!itr.isDone()) {
+            if (key != null) {
+                if (UnicodeLocaleExtension.isKey(itr.current())) {
+                    // next keyword - emit previous one
+                    assert(typeStart == -1 || typeEnd != -1);
+                    type = (typeStart == -1) ? "" : subtags.substring(typeStart, typeEnd);
+                    if (_ukeywords == null) {
+                        _ukeywords = new HashMap<CaseInsensitiveString, String>(4);
+                    }
+                    _ukeywords.put(key, type);
+
+                    // reset keyword info
+                    CaseInsensitiveString tmpKey = new CaseInsensitiveString(itr.current());
+                    key = _ukeywords.containsKey(tmpKey) ? null : tmpKey;
+                    typeStart = typeEnd = -1;
+                } else {
+                    if (typeStart == -1) {
+                        typeStart = itr.currentStart();
+                    }
+                    typeEnd = itr.currentEnd();
+                }
+            } else if (UnicodeLocaleExtension.isKey(itr.current())) {
+                // 1. first keyword or
+                // 2. next keyword, but previous one was duplicate
+                key = new CaseInsensitiveString(itr.current());
+                if (_ukeywords != null && _ukeywords.containsKey(key)) {
+                    // duplicate
+                    key = null;
+                }
+            }
+
+            if (!itr.hasNext()) {
+                if (key != null) {
+                    // last keyword
+                    assert(typeStart == -1 || typeEnd != -1);
+                    type = (typeStart == -1) ? "" : subtags.substring(typeStart, typeEnd);
+                    if (_ukeywords == null) {
+                        _ukeywords = new HashMap<CaseInsensitiveString, String>(4);
+                    }
+                    _ukeywords.put(key, type);
+                }
+                break;
+            }
+
+            itr.next();
+        }
+    }
+
+    static class CaseInsensitiveString {
+        private String _s;
+
+        CaseInsensitiveString(String s) {
+            _s = s;
+        }
+
+        public String value() {
+            return _s;
+        }
+
+        public int hashCode() {
+            return AsciiUtil.toLowerString(_s).hashCode();
+        }
+
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
+            }
+            if (!(obj instanceof CaseInsensitiveString)) {
+                return false;
+            }
+            return AsciiUtil.caseIgnoreMatch(_s, ((CaseInsensitiveString)obj).value());
+        }
+    }
+
+    static class CaseInsensitiveChar {
+        private char _c;
+
+        CaseInsensitiveChar(char c) {
+            _c = c;
+        }
+
+        public char value() {
+            return _c;
+        }
+
+        public int hashCode() {
+            return AsciiUtil.toLower(_c);
+        }
+
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
+            }
+            if (!(obj instanceof CaseInsensitiveChar)) {
+                return false;
+            }
+            return _c ==  AsciiUtil.toLower(((CaseInsensitiveChar)obj).value());
+        }
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/LanguageTag.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,726 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2010, International Business Machines Corporation and         *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class LanguageTag {
+    //
+    // static fields
+    //
+    public static final String SEP = "-";
+    public static final String PRIVATEUSE = "x";
+    public static String UNDETERMINED = "und";
+    public static final String PRIVUSE_VARIANT_PREFIX = "lvariant";
+
+    //
+    // Language subtag fields
+    //
+    private String _language = "";      // language subtag
+    private String _script = "";        // script subtag
+    private String _region = "";        // region subtag
+    private String _privateuse = "";    // privateuse
+
+    private List<String> _extlangs = Collections.emptyList();   // extlang subtags
+    private List<String> _variants = Collections.emptyList();   // variant subtags
+    private List<String> _extensions = Collections.emptyList(); // extensions
+
+    // Map contains grandfathered tags and its preferred mappings from
+    // http://www.ietf.org/rfc/rfc5646.txt
+    private static final Map<AsciiUtil.CaseInsensitiveKey, String[]> GRANDFATHERED =
+        new HashMap<AsciiUtil.CaseInsensitiveKey, String[]>();
+
+    static {
+        // grandfathered = irregular           ; non-redundant tags registered
+        //               / regular             ; during the RFC 3066 era
+        //
+        // irregular     = "en-GB-oed"         ; irregular tags do not match
+        //               / "i-ami"             ; the 'langtag' production and
+        //               / "i-bnn"             ; would not otherwise be
+        //               / "i-default"         ; considered 'well-formed'
+        //               / "i-enochian"        ; These tags are all valid,
+        //               / "i-hak"             ; but most are deprecated
+        //               / "i-klingon"         ; in favor of more modern
+        //               / "i-lux"             ; subtags or subtag
+        //               / "i-mingo"           ; combination
+        //               / "i-navajo"
+        //               / "i-pwn"
+        //               / "i-tao"
+        //               / "i-tay"
+        //               / "i-tsu"
+        //               / "sgn-BE-FR"
+        //               / "sgn-BE-NL"
+        //               / "sgn-CH-DE"
+        //
+        // regular       = "art-lojban"        ; these tags match the 'langtag'
+        //               / "cel-gaulish"       ; production, but their subtags
+        //               / "no-bok"            ; are not extended language
+        //               / "no-nyn"            ; or variant subtags: their meaning
+        //               / "zh-guoyu"          ; is defined by their registration
+        //               / "zh-hakka"          ; and all of these are deprecated
+        //               / "zh-min"            ; in favor of a more modern
+        //               / "zh-min-nan"        ; subtag or sequence of subtags
+        //               / "zh-xiang"
+
+        final String[][] entries = {
+          //{"tag",         "preferred"},
+            {"art-lojban",  "jbo"},
+            {"cel-gaulish", "xtg-x-cel-gaulish"},   // fallback
+            {"en-GB-oed",   "en-GB-x-oed"},         // fallback
+            {"i-ami",       "ami"},
+            {"i-bnn",       "bnn"},
+            {"i-default",   "en-x-i-default"},      // fallback
+            {"i-enochian",  "und-x-i-enochian"},    // fallback
+            {"i-hak",       "hak"},
+            {"i-klingon",   "tlh"},
+            {"i-lux",       "lb"},
+            {"i-mingo",     "see-x-i-mingo"},       // fallback
+            {"i-navajo",    "nv"},
+            {"i-pwn",       "pwn"},
+            {"i-tao",       "tao"},
+            {"i-tay",       "tay"},
+            {"i-tsu",       "tsu"},
+            {"no-bok",      "nb"},
+            {"no-nyn",      "nn"},
+            {"sgn-BE-FR",   "sfb"},
+            {"sgn-BE-NL",   "vgt"},
+            {"sgn-CH-DE",   "sgg"},
+            {"zh-guoyu",    "cmn"},
+            {"zh-hakka",    "hak"},
+            {"zh-min",      "nan-x-zh-min"},        // fallback
+            {"zh-min-nan",  "nan"},
+            {"zh-xiang",    "hsn"},
+        };
+        for (String[] e : entries) {
+            GRANDFATHERED.put(new AsciiUtil.CaseInsensitiveKey(e[0]), e);
+        }
+    }
+
+    private LanguageTag() {
+    }
+
+    /*
+     * BNF in RFC5464
+     *
+     * Language-Tag  = langtag             ; normal language tags
+     *               / privateuse          ; private use tag
+     *               / grandfathered       ; grandfathered tags
+     *
+     *
+     * langtag       = language
+     *                 ["-" script]
+     *                 ["-" region]
+     *                 *("-" variant)
+     *                 *("-" extension)
+     *                 ["-" privateuse]
+     *
+     * language      = 2*3ALPHA            ; shortest ISO 639 code
+     *                 ["-" extlang]       ; sometimes followed by
+     *                                     ; extended language subtags
+     *               / 4ALPHA              ; or reserved for future use
+     *               / 5*8ALPHA            ; or registered language subtag
+     *
+     * extlang       = 3ALPHA              ; selected ISO 639 codes
+     *                 *2("-" 3ALPHA)      ; permanently reserved
+     *
+     * script        = 4ALPHA              ; ISO 15924 code
+     *
+     * region        = 2ALPHA              ; ISO 3166-1 code
+     *               / 3DIGIT              ; UN M.49 code
+     *
+     * variant       = 5*8alphanum         ; registered variants
+     *               / (DIGIT 3alphanum)
+     *
+     * extension     = singleton 1*("-" (2*8alphanum))
+     *
+     *                                     ; Single alphanumerics
+     *                                     ; "x" reserved for private use
+     * singleton     = DIGIT               ; 0 - 9
+     *               / %x41-57             ; A - W
+     *               / %x59-5A             ; Y - Z
+     *               / %x61-77             ; a - w
+     *               / %x79-7A             ; y - z
+     *
+     * privateuse    = "x" 1*("-" (1*8alphanum))
+     *
+     */
+    public static LanguageTag parse(String languageTag, ParseStatus sts) {
+        if (sts == null) {
+            sts = new ParseStatus();
+        } else {
+            sts.reset();
+        }
+
+        StringTokenIterator itr;
+
+        // Check if the tag is grandfathered
+        String[] gfmap = GRANDFATHERED.get(new AsciiUtil.CaseInsensitiveKey(languageTag));
+        if (gfmap != null) {
+            // use preferred mapping
+            itr = new StringTokenIterator(gfmap[1], SEP);
+        } else {
+            itr = new StringTokenIterator(languageTag, SEP);
+        }
+
+        LanguageTag tag = new LanguageTag();
+
+        // langtag must start with either language or privateuse
+        if (tag.parseLanguage(itr, sts)) {
+            tag.parseExtlangs(itr, sts);
+            tag.parseScript(itr, sts);
+            tag.parseRegion(itr, sts);
+            tag.parseVariants(itr, sts);
+            tag.parseExtensions(itr, sts);
+        }
+        tag.parsePrivateuse(itr, sts);
+
+        if (!itr.isDone() && !sts.isError()) {
+            String s = itr.current();
+            sts._errorIndex = itr.currentStart();
+            if (s.length() == 0) {
+                sts._errorMsg = "Empty subtag";
+            } else {
+                sts._errorMsg = "Invalid subtag: " + s;
+            }
+        }
+
+        return tag;
+    }
+
+    //
+    // Language subtag parsers
+    //
+
+    private boolean parseLanguage(StringTokenIterator itr, ParseStatus sts) {
+        if (itr.isDone() || sts.isError()) {
+            return false;
+        }
+
+        boolean found = false;
+
+        String s = itr.current();
+        if (isLanguage(s)) {
+            found = true;
+            _language = s;
+            sts._parseLength = itr.currentEnd();
+            itr.next();
+        }
+
+        return found;
+    }
+
+    private boolean parseExtlangs(StringTokenIterator itr, ParseStatus sts) {
+        if (itr.isDone() || sts.isError()) {
+            return false;
+        }
+
+        boolean found = false;
+
+        while (!itr.isDone()) {
+            String s = itr.current();
+            if (!isExtlang(s)) {
+                break;
+            }
+            found = true;
+            if (_extlangs.isEmpty()) {
+                _extlangs = new ArrayList<String>(3);
+            }
+            _extlangs.add(s);
+            sts._parseLength = itr.currentEnd();
+            itr.next();
+
+            if (_extlangs.size() == 3) {
+                // Maximum 3 extlangs
+                break;
+            }
+        }
+
+        return found;
+    }
+
+    private boolean parseScript(StringTokenIterator itr, ParseStatus sts) {
+        if (itr.isDone() || sts.isError()) {
+            return false;
+        }
+
+        boolean found = false;
+
+        String s = itr.current();
+        if (isScript(s)) {
+            found = true;
+            _script = s;
+            sts._parseLength = itr.currentEnd();
+            itr.next();
+        }
+
+        return found;
+    }
+
+    private boolean parseRegion(StringTokenIterator itr, ParseStatus sts) {
+        if (itr.isDone() || sts.isError()) {
+            return false;
+        }
+
+        boolean found = false;
+
+        String s = itr.current();
+        if (isRegion(s)) {
+            found = true;
+            _region = s;
+            sts._parseLength = itr.currentEnd();
+            itr.next();
+        }
+
+        return found;
+    }
+
+    private boolean parseVariants(StringTokenIterator itr, ParseStatus sts) {
+        if (itr.isDone() || sts.isError()) {
+            return false;
+        }
+
+        boolean found = false;
+
+        while (!itr.isDone()) {
+            String s = itr.current();
+            if (!isVariant(s)) {
+                break;
+            }
+            found = true;
+            if (_variants.isEmpty()) {
+                _variants = new ArrayList<String>(3);
+            }
+            _variants.add(s);
+            sts._parseLength = itr.currentEnd();
+            itr.next();
+        }
+
+        return found;
+    }
+
+    private boolean parseExtensions(StringTokenIterator itr, ParseStatus sts) {
+        if (itr.isDone() || sts.isError()) {
+            return false;
+        }
+
+        boolean found = false;
+
+        while (!itr.isDone()) {
+            String s = itr.current();
+            if (isExtensionSingleton(s)) {
+                int start = itr.currentStart();
+                String singleton = s;
+                StringBuilder sb = new StringBuilder(singleton);
+
+                itr.next();
+                while (!itr.isDone()) {
+                    s = itr.current();
+                    if (isExtensionSubtag(s)) {
+                        sb.append(SEP).append(s);
+                        sts._parseLength = itr.currentEnd();
+                    } else {
+                        break;
+                    }
+                    itr.next();
+                }
+
+                if (sts._parseLength <= start) {
+                    sts._errorIndex = start;
+                    sts._errorMsg = "Incomplete extension '" + singleton + "'";
+                    break;
+                }
+
+                if (_extensions.size() == 0) {
+                    _extensions = new ArrayList<String>(4);
+                }
+                _extensions.add(sb.toString());
+                found = true;
+            } else {
+                break;
+            }
+        }
+        return found;
+    }
+
+    private boolean parsePrivateuse(StringTokenIterator itr, ParseStatus sts) {
+        if (itr.isDone() || sts.isError()) {
+            return false;
+        }
+
+        boolean found = false;
+
+        String s = itr.current();
+        if (isPrivateusePrefix(s)) {
+            int start = itr.currentStart();
+            StringBuilder sb = new StringBuilder(s);
+
+            itr.next();
+            while (!itr.isDone()) {
+                s = itr.current();
+                if (!isPrivateuseSubtag(s)) {
+                    break;
+                }
+                sb.append(SEP).append(s);
+                sts._parseLength = itr.currentEnd();
+
+                itr.next();
+            }
+
+            if (sts._parseLength <= start) {
+                // need at least 1 private subtag
+                sts._errorIndex = start;
+                sts._errorMsg = "Incomplete privateuse";
+            } else {
+                _privateuse = sb.toString();
+                found = true;
+            }
+        }
+
+        return found;
+    }
+
+    public static LanguageTag parseLocale(BaseLocale baseLocale, LocaleExtensions localeExtensions) {
+        LanguageTag tag = new LanguageTag();
+
+        String language = baseLocale.getLanguage();
+        String script = baseLocale.getScript();
+        String region = baseLocale.getRegion();
+        String variant = baseLocale.getVariant();
+
+        String privuseVar = null;   // store ill-formed variant subtags
+
+        if (language.length() == 0 || !isLanguage(language)) {
+            tag._language = UNDETERMINED;
+        } else {
+            // Convert a deprecated language code used by Java to
+            // a new code
+            if (language.equals("iw")) {
+                language = "he";
+            } else if (language.equals("ji")) {
+                language = "yi";
+            } else if (language.equals("in")) {
+                language = "id";
+            }
+            tag._language = language;
+        }
+
+        if (script.length() > 0 && isScript(script)) {
+            tag._script = canonicalizeScript(script);
+        }
+
+        if (region.length() > 0 && isRegion(region)) {
+            tag._region = canonicalizeRegion(region);
+        }
+
+        // Special handling for no_NO_NY - use nn_NO for language tag
+        if (tag._language.equals("no") && tag._region.equals("NO") && variant.equals("NY")) {
+            tag._language = "nn";
+            variant = "";
+        }
+
+        if (variant.length() > 0) {
+            List<String> variants = null;
+            StringTokenIterator varitr = new StringTokenIterator(variant, BaseLocale.SEP);
+            while (!varitr.isDone()) {
+                String var = varitr.current();
+                if (!isVariant(var)) {
+                    break;
+                }
+                if (variants == null) {
+                    variants = new ArrayList<String>();
+                }
+                variants.add(var);  // Do not canonicalize!
+                varitr.next();
+            }
+            if (variants != null) {
+                tag._variants = variants;
+            }
+            if (!varitr.isDone()) {
+                // ill-formed variant subtags
+                StringBuilder buf = new StringBuilder();
+                while (!varitr.isDone()) {
+                    String prvv = varitr.current();
+                    if (!isPrivateuseSubtag(prvv)) {
+                        // cannot use private use subtag - truncated
+                        break;
+                    }
+                    if (buf.length() > 0) {
+                        buf.append(SEP);
+                    }
+                    buf.append(prvv);
+                    varitr.next();
+                }
+                if (buf.length() > 0) {
+                    privuseVar = buf.toString();
+                }
+            }
+        }
+
+        List<String> extensions = null;
+        String privateuse = null;
+
+        Set<Character> locextKeys = localeExtensions.getKeys();
+        for (Character locextKey : locextKeys) {
+            Extension ext = localeExtensions.getExtension(locextKey);
+            if (isPrivateusePrefixChar(locextKey.charValue())) {
+                privateuse = ext.getValue();
+            } else {
+                if (extensions == null) {
+                    extensions = new ArrayList<String>();
+                }
+                extensions.add(locextKey.toString() + SEP + ext.getValue());
+            }
+        }
+
+        if (extensions != null) {
+            tag._extensions = extensions;
+        }
+
+        // append ill-formed variant subtags to private use
+        if (privuseVar != null) {
+            if (privateuse == null) {
+                privateuse = PRIVUSE_VARIANT_PREFIX + SEP + privuseVar;
+            } else {
+                privateuse = privateuse + SEP + PRIVUSE_VARIANT_PREFIX + SEP + privuseVar.replace(BaseLocale.SEP, SEP);
+            }
+        }
+
+        if (privateuse != null) {
+            tag._privateuse = privateuse;
+        } else if (tag._language.length() == 0) {
+            // use "und" if neither language nor privateuse is available
+            tag._language = UNDETERMINED;
+        }
+
+        return tag;
+    }
+
+    //
+    // Getter methods for language subtag fields
+    //
+
+    public String getLanguage() {
+        return _language;
+    }
+
+    public List<String> getExtlangs() {
+        return Collections.unmodifiableList(_extlangs);
+    }
+
+    public String getScript() {
+        return _script;
+    }
+
+    public String getRegion() {
+        return _region;
+    }
+
+    public List<String> getVariants() {
+        return Collections.unmodifiableList(_variants);
+    }
+
+    public List<String> getExtensions() {
+        return Collections.unmodifiableList(_extensions);
+    }
+
+    public String getPrivateuse() {
+        return _privateuse;
+    }
+
+    //
+    // Language subtag syntax checking methods
+    //
+
+    public static boolean isLanguage(String s) {
+        // language      = 2*3ALPHA            ; shortest ISO 639 code
+        //                 ["-" extlang]       ; sometimes followed by
+        //                                     ;   extended language subtags
+        //               / 4ALPHA              ; or reserved for future use
+        //               / 5*8ALPHA            ; or registered language subtag
+        return (s.length() >= 2) && (s.length() <= 8) && AsciiUtil.isAlphaString(s);
+    }
+
+    public static boolean isExtlang(String s) {
+        // extlang       = 3ALPHA              ; selected ISO 639 codes
+        //                 *2("-" 3ALPHA)      ; permanently reserved
+        return (s.length() == 3) && AsciiUtil.isAlphaString(s);
+    }
+
+    public static boolean isScript(String s) {
+        // script        = 4ALPHA              ; ISO 15924 code
+        return (s.length() == 4) && AsciiUtil.isAlphaString(s);
+    }
+
+    public static boolean isRegion(String s) {
+        // region        = 2ALPHA              ; ISO 3166-1 code
+        //               / 3DIGIT              ; UN M.49 code
+        return ((s.length() == 2) && AsciiUtil.isAlphaString(s))
+                || ((s.length() == 3) && AsciiUtil.isNumericString(s));
+    }
+
+    public static boolean isVariant(String s) {
+        // variant       = 5*8alphanum         ; registered variants
+        //               / (DIGIT 3alphanum)
+        int len = s.length();
+        if (len >= 5 && len <= 8) {
+            return AsciiUtil.isAlphaNumericString(s);
+        }
+        if (len == 4) {
+            return AsciiUtil.isNumeric(s.charAt(0))
+                    && AsciiUtil.isAlphaNumeric(s.charAt(1))
+                    && AsciiUtil.isAlphaNumeric(s.charAt(2))
+                    && AsciiUtil.isAlphaNumeric(s.charAt(3));
+        }
+        return false;
+    }
+
+    public static boolean isExtensionSingleton(String s) {
+        // singleton     = DIGIT               ; 0 - 9
+        //               / %x41-57             ; A - W
+        //               / %x59-5A             ; Y - Z
+        //               / %x61-77             ; a - w
+        //               / %x79-7A             ; y - z
+
+        return (s.length() == 1)
+                && AsciiUtil.isAlphaString(s)
+                && !AsciiUtil.caseIgnoreMatch(PRIVATEUSE, s);
+    }
+
+    public static boolean isExtensionSingletonChar(char c) {
+        return isExtensionSingleton(String.valueOf(c));
+    }
+
+    public static boolean isExtensionSubtag(String s) {
+        // extension     = singleton 1*("-" (2*8alphanum))
+        return (s.length() >= 2) && (s.length() <= 8) && AsciiUtil.isAlphaNumericString(s);
+    }
+
+    public static boolean isPrivateusePrefix(String s) {
+        // privateuse    = "x" 1*("-" (1*8alphanum))
+        return (s.length() == 1)
+                && AsciiUtil.caseIgnoreMatch(PRIVATEUSE, s);
+    }
+
+    public static boolean isPrivateusePrefixChar(char c) {
+        return (AsciiUtil.caseIgnoreMatch(PRIVATEUSE, String.valueOf(c)));
+    }
+
+    public static boolean isPrivateuseSubtag(String s) {
+        // privateuse    = "x" 1*("-" (1*8alphanum))
+        return (s.length() >= 1) && (s.length() <= 8) && AsciiUtil.isAlphaNumericString(s);
+    }
+
+    //
+    // Language subtag canonicalization methods
+    //
+
+    public static String canonicalizeLanguage(String s) {
+        return AsciiUtil.toLowerString(s);
+    }
+
+    public static String canonicalizeExtlang(String s) {
+        return AsciiUtil.toLowerString(s);
+    }
+
+    public static String canonicalizeScript(String s) {
+        return AsciiUtil.toTitleString(s);
+    }
+
+    public static String canonicalizeRegion(String s) {
+        return AsciiUtil.toUpperString(s);
+    }
+
+    public static String canonicalizeVariant(String s) {
+        return AsciiUtil.toLowerString(s);
+    }
+
+    public static String canonicalizeExtension(String s) {
+        return AsciiUtil.toLowerString(s);
+    }
+
+    public static String canonicalizeExtensionSingleton(String s) {
+        return AsciiUtil.toLowerString(s);
+    }
+
+    public static String canonicalizeExtensionSubtag(String s) {
+        return AsciiUtil.toLowerString(s);
+    }
+
+    public static String canonicalizePrivateuse(String s) {
+        return AsciiUtil.toLowerString(s);
+    }
+
+    public static String canonicalizePrivateuseSubtag(String s) {
+        return AsciiUtil.toLowerString(s);
+    }
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+
+        if (_language.length() > 0) {
+            sb.append(_language);
+
+            for (String extlang : _extlangs) {
+                sb.append(SEP).append(extlang);
+            }
+
+            if (_script.length() > 0) {
+                sb.append(SEP).append(_script);
+            }
+
+            if (_region.length() > 0) {
+                sb.append(SEP).append(_region);
+            }
+
+            for (String variant : _extlangs) {
+                sb.append(SEP).append(variant);
+            }
+
+            for (String extension : _extensions) {
+                sb.append(SEP).append(extension);
+            }
+        }
+        if (_privateuse.length() > 0) {
+            if (sb.length() > 0) {
+                sb.append(SEP);
+            }
+            sb.append(_privateuse);
+        }
+
+        return sb.toString();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/LocaleExtensions.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009-2010, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import sun.util.locale.InternalLocaleBuilder.CaseInsensitiveChar;
+import sun.util.locale.InternalLocaleBuilder.CaseInsensitiveString;
+
+
+public class LocaleExtensions {
+
+    private SortedMap<Character, Extension> _map;
+    private String _id;
+
+    private static final SortedMap<Character, Extension> EMPTY_MAP =
+        Collections.unmodifiableSortedMap(new TreeMap<Character, Extension>());
+
+    public static final LocaleExtensions EMPTY_EXTENSIONS;
+    public static final LocaleExtensions CALENDAR_JAPANESE;
+    public static final LocaleExtensions NUMBER_THAI;
+
+    static {
+        EMPTY_EXTENSIONS = new LocaleExtensions();
+        EMPTY_EXTENSIONS._id = "";
+        EMPTY_EXTENSIONS._map = EMPTY_MAP;
+
+        CALENDAR_JAPANESE = new LocaleExtensions();
+        CALENDAR_JAPANESE._id = "u-ca-japanese";
+        CALENDAR_JAPANESE._map = new TreeMap<Character, Extension>();
+        CALENDAR_JAPANESE._map.put(Character.valueOf(UnicodeLocaleExtension.SINGLETON), UnicodeLocaleExtension.CA_JAPANESE);
+
+        NUMBER_THAI = new LocaleExtensions();
+        NUMBER_THAI._id = "u-nu-thai";
+        NUMBER_THAI._map = new TreeMap<Character, Extension>();
+        NUMBER_THAI._map.put(Character.valueOf(UnicodeLocaleExtension.SINGLETON), UnicodeLocaleExtension.NU_THAI);
+    }
+
+    private LocaleExtensions() {
+    }
+
+    /*
+     * Package local constructor, only used by InternalLocaleBuilder.
+     */
+    LocaleExtensions(Map<CaseInsensitiveChar, String> extensions,
+            Set<CaseInsensitiveString> uattributes, Map<CaseInsensitiveString, String> ukeywords) {
+        boolean hasExtension = (extensions != null && extensions.size() > 0);
+        boolean hasUAttributes = (uattributes != null && uattributes.size() > 0);
+        boolean hasUKeywords = (ukeywords != null && ukeywords.size() > 0);
+
+        if (!hasExtension && !hasUAttributes && !hasUKeywords) {
+            _map = EMPTY_MAP;
+            _id = "";
+            return;
+        }
+
+        // Build extension map
+        _map = new TreeMap<Character, Extension>();
+        if (hasExtension) {
+            for (Entry<CaseInsensitiveChar, String> ext : extensions.entrySet()) {
+                char key = AsciiUtil.toLower(ext.getKey().value());
+                String value = ext.getValue();
+
+                if (LanguageTag.isPrivateusePrefixChar(key)) {
+                    // we need to exclude special variant in privuateuse, e.g. "x-abc-lvariant-DEF"
+                    value = InternalLocaleBuilder.removePrivateuseVariant(value);
+                    if (value == null) {
+                        continue;
+                    }
+                }
+
+                Extension e = new Extension(key, AsciiUtil.toLowerString(value));
+                _map.put(Character.valueOf(key), e);
+            }
+        }
+
+        if (hasUAttributes || hasUKeywords) {
+            TreeSet<String> uaset = null;
+            TreeMap<String, String> ukmap = null;
+
+            if (hasUAttributes) {
+                uaset = new TreeSet<String>();
+                for (CaseInsensitiveString cis : uattributes) {
+                    uaset.add(AsciiUtil.toLowerString(cis.value()));
+                }
+            }
+
+            if (hasUKeywords) {
+                ukmap = new TreeMap<String, String>();
+                for (Entry<CaseInsensitiveString, String> kwd : ukeywords.entrySet()) {
+                    String key = AsciiUtil.toLowerString(kwd.getKey().value());
+                    String type = AsciiUtil.toLowerString(kwd.getValue());
+                    ukmap.put(key, type);
+                }
+            }
+
+            UnicodeLocaleExtension ule = new UnicodeLocaleExtension(uaset, ukmap);
+            _map.put(Character.valueOf(UnicodeLocaleExtension.SINGLETON), ule);
+        }
+
+        if (_map.size() == 0) {
+            // this could happen when only privuateuse with special variant
+            _map = EMPTY_MAP;
+            _id = "";
+        } else {
+            _id = toID(_map);
+        }
+    }
+
+    public Set<Character> getKeys() {
+        return Collections.unmodifiableSet(_map.keySet());
+    }
+
+    public Extension getExtension(Character key) {
+        return _map.get(Character.valueOf(AsciiUtil.toLower(key.charValue())));
+    }
+
+    public String getExtensionValue(Character key) {
+        Extension ext = _map.get(Character.valueOf(AsciiUtil.toLower(key.charValue())));
+        if (ext == null) {
+            return null;
+        }
+        return ext.getValue();
+    }
+
+    public Set<String> getUnicodeLocaleAttributes() {
+        Extension ext = _map.get(Character.valueOf(UnicodeLocaleExtension.SINGLETON));
+        if (ext == null) {
+            return Collections.emptySet();
+        }
+        assert (ext instanceof UnicodeLocaleExtension);
+        return ((UnicodeLocaleExtension)ext).getUnicodeLocaleAttributes();
+    }
+
+    public Set<String> getUnicodeLocaleKeys() {
+        Extension ext = _map.get(Character.valueOf(UnicodeLocaleExtension.SINGLETON));
+        if (ext == null) {
+            return Collections.emptySet();
+        }
+        assert (ext instanceof UnicodeLocaleExtension);
+        return ((UnicodeLocaleExtension)ext).getUnicodeLocaleKeys();
+    }
+
+    public String getUnicodeLocaleType(String unicodeLocaleKey) {
+        Extension ext = _map.get(Character.valueOf(UnicodeLocaleExtension.SINGLETON));
+        if (ext == null) {
+            return null;
+        }
+        assert (ext instanceof UnicodeLocaleExtension);
+        return ((UnicodeLocaleExtension)ext).getUnicodeLocaleType(AsciiUtil.toLowerString(unicodeLocaleKey));
+    }
+
+    public boolean isEmpty() {
+        return _map.isEmpty();
+    }
+
+    public static boolean isValidKey(char c) {
+        return LanguageTag.isExtensionSingletonChar(c) || LanguageTag.isPrivateusePrefixChar(c);
+    }
+
+    public static boolean isValidUnicodeLocaleKey(String ukey) {
+        return UnicodeLocaleExtension.isKey(ukey);
+    }
+
+    private static String toID(SortedMap<Character, Extension> map) {
+        StringBuilder buf = new StringBuilder();
+        Extension privuse = null;
+        for (Entry<Character, Extension> entry : map.entrySet()) {
+            char singleton = entry.getKey().charValue();
+            Extension extension = entry.getValue();
+            if (LanguageTag.isPrivateusePrefixChar(singleton)) {
+                privuse = extension;
+            } else {
+                if (buf.length() > 0) {
+                    buf.append(LanguageTag.SEP);
+                }
+                buf.append(extension);
+            }
+        }
+        if (privuse != null) {
+            if (buf.length() > 0) {
+                buf.append(LanguageTag.SEP);
+            }
+            buf.append(privuse);
+        }
+        return buf.toString();
+    }
+
+
+    public String toString() {
+        return _id;
+    }
+
+    public String getID() {
+        return _id;
+    }
+
+    public int hashCode() {
+        return _id.hashCode();
+    }
+
+    public boolean equals(Object other) {
+        if (this == other) {
+            return true;
+        }
+        if (!(other instanceof LocaleExtensions)) {
+            return false;
+        }
+        return this._id.equals(((LocaleExtensions)other)._id);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/LocaleObjectCache.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009-2010, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.util.concurrent.ConcurrentHashMap;
+
+public abstract class LocaleObjectCache<K, V> {
+    private ConcurrentHashMap<K, CacheEntry<K, V>> _map;
+    private ReferenceQueue<V> _queue = new ReferenceQueue<V>();
+
+    public LocaleObjectCache() {
+        this(16, 0.75f, 16);
+    }
+
+    public LocaleObjectCache(int initialCapacity, float loadFactor, int concurrencyLevel) {
+        _map = new ConcurrentHashMap<K, CacheEntry<K, V>>(initialCapacity, loadFactor, concurrencyLevel);
+    }
+
+    public V get(K key) {
+        V value = null;
+
+        cleanStaleEntries();
+        CacheEntry<K, V> entry = _map.get(key);
+        if (entry != null) {
+            value = entry.get();
+        }
+        if (value == null) {
+            key = normalizeKey(key);
+            V newVal = createObject(key);
+            if (key == null || newVal == null) {
+                // subclass must return non-null key/value object
+                return null;
+            }
+
+            CacheEntry<K, V> newEntry = new CacheEntry<K, V>(key, newVal, _queue);
+
+            while (value == null) {
+                cleanStaleEntries();
+                entry = _map.putIfAbsent(key, newEntry);
+                if (entry == null) {
+                    value = newVal;
+                    break;
+                } else {
+                    value = entry.get();
+                }
+            }
+        }
+        return value;
+    }
+
+    @SuppressWarnings("unchecked")
+    private void cleanStaleEntries() {
+        CacheEntry<K, V> entry;
+        while ((entry = (CacheEntry<K, V>)_queue.poll()) != null) {
+            _map.remove(entry.getKey());
+        }
+    }
+
+    protected abstract V createObject(K key);
+
+    protected K normalizeKey(K key) {
+        return key;
+    }
+
+    private static class CacheEntry<K, V> extends SoftReference<V> {
+        private K _key;
+
+        CacheEntry(K key, V value, ReferenceQueue<V> queue) {
+            super(value, queue);
+            _key = key;
+        }
+
+        K getKey() {
+            return _key;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/LocaleSyntaxException.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009, International Business Machines Corporation and         *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+public class LocaleSyntaxException extends Exception {
+
+    private static final long serialVersionUID = 1L;
+
+    private int _index = -1;
+
+    public LocaleSyntaxException(String msg) {
+        this(msg, 0);
+    }
+
+    public LocaleSyntaxException(String msg, int errorIndex) {
+        super(msg);
+        _index = errorIndex;
+    }
+
+    public int getErrorIndex() {
+        return _index;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/ParseStatus.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2010, International Business Machines Corporation and         *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+public class ParseStatus {
+    int _parseLength = 0;
+    int _errorIndex = -1;
+    String _errorMsg = null;
+
+    public void reset() {
+        _parseLength = 0;
+        _errorIndex = -1;
+        _errorMsg = null;
+    }
+
+    public boolean isError() {
+        return (_errorIndex >= 0);
+    }
+
+    public int getErrorIndex() {
+        return _errorIndex;
+    }
+
+    public int getParseLength() {
+        return _parseLength;
+    }
+
+    public String getErrorMessage() {
+        return _errorMsg;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/StringTokenIterator.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ *******************************************************************************
+ * Copyright (C) 2009, International Business Machines Corporation and         *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+public class StringTokenIterator {
+    private String _text;
+    private String _dlms;
+
+    private String _token;
+    private int _start;
+    private int _end;
+    private boolean _done;
+
+    public StringTokenIterator(String text, String dlms) {
+        _text = text;
+        _dlms = dlms;
+        setStart(0);
+    }
+
+    public String first() {
+        setStart(0);
+        return _token;
+    }
+
+    public String current() {
+        return _token;
+    }
+
+    public int currentStart() {
+        return _start;
+    }
+
+    public int currentEnd() {
+        return _end;
+    }
+
+    public boolean isDone() {
+        return _done;
+    }
+
+    public String next() {
+        if (hasNext()) {
+            _start = _end + 1;
+            _end = nextDelimiter(_start);
+            _token = _text.substring(_start, _end);
+        } else {
+            _start = _end;
+            _token = null;
+            _done = true;
+        }
+        return _token;
+    }
+
+    public boolean hasNext() {
+        return (_end < _text.length());
+    }
+
+    public StringTokenIterator setStart(int offset) {
+        if (offset > _text.length()) {
+            throw new IndexOutOfBoundsException();
+        }
+        _start = offset;
+        _end = nextDelimiter(_start);
+        _token = _text.substring(_start, _end);
+        _done = false;
+        return this;
+    }
+
+    public StringTokenIterator setText(String text) {
+        _text = text;
+        setStart(0);
+        return this;
+    }
+
+    private int nextDelimiter(int start) {
+        int idx = start;
+        outer: while (idx < _text.length()) {
+            char c = _text.charAt(idx);
+            for (int i = 0; i < _dlms.length(); i++) {
+                if (c == _dlms.charAt(i)) {
+                    break outer;
+                }
+            }
+            idx++;
+        }
+        return idx;
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/util/locale/UnicodeLocaleExtension.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ *******************************************************************************
+ * Copyright (C) 2009-2010, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+package sun.util.locale;
+
+import java.util.Collections;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+public class UnicodeLocaleExtension extends Extension {
+    public static final char SINGLETON = 'u';
+
+    private static final SortedSet<String> EMPTY_SORTED_SET = new TreeSet<String>();
+    private static final SortedMap<String, String> EMPTY_SORTED_MAP = new TreeMap<String, String>();
+
+    private SortedSet<String> _attributes = EMPTY_SORTED_SET;
+    private SortedMap<String, String> _keywords = EMPTY_SORTED_MAP;
+
+    public static final UnicodeLocaleExtension CA_JAPANESE;
+    public static final UnicodeLocaleExtension NU_THAI;
+
+    static {
+        CA_JAPANESE = new UnicodeLocaleExtension();
+        CA_JAPANESE._keywords = new TreeMap<String, String>();
+        CA_JAPANESE._keywords.put("ca", "japanese");
+        CA_JAPANESE._value = "ca-japanese";
+
+        NU_THAI = new UnicodeLocaleExtension();
+        NU_THAI._keywords = new TreeMap<String, String>();
+        NU_THAI._keywords.put("nu", "thai");
+        NU_THAI._value = "nu-thai";
+    }
+
+    private UnicodeLocaleExtension() {
+        super(SINGLETON);
+    }
+
+    UnicodeLocaleExtension(SortedSet<String> attributes, SortedMap<String, String> keywords) {
+        this();
+        if (attributes != null && attributes.size() > 0) {
+            _attributes = attributes;
+        }
+        if (keywords != null && keywords.size() > 0) {
+            _keywords = keywords;
+        }
+
+        if (_attributes.size() > 0 || _keywords.size() > 0) {
+            StringBuilder sb = new StringBuilder();
+            for (String attribute : _attributes) {
+                sb.append(LanguageTag.SEP).append(attribute);
+            }
+            for (Entry<String, String> keyword : _keywords.entrySet()) {
+                String key = keyword.getKey();
+                String value = keyword.getValue();
+
+                sb.append(LanguageTag.SEP).append(key);
+                if (value.length() > 0) {
+                    sb.append(LanguageTag.SEP).append(value);
+                }
+            }
+            _value = sb.substring(1);   // skip leading '-'
+        }
+    }
+
+    public Set<String> getUnicodeLocaleAttributes() {
+        return Collections.unmodifiableSet(_attributes);
+    }
+
+    public Set<String> getUnicodeLocaleKeys() {
+        return Collections.unmodifiableSet(_keywords.keySet());
+    }
+
+    public String getUnicodeLocaleType(String unicodeLocaleKey) {
+        return _keywords.get(unicodeLocaleKey);
+    }
+
+    public static boolean isSingletonChar(char c) {
+        return (SINGLETON == AsciiUtil.toLower(c));
+    }
+
+    public static boolean isAttribute(String s) {
+        // 3*8alphanum
+        return (s.length() >= 3) && (s.length() <= 8) && AsciiUtil.isAlphaNumericString(s);
+    }
+
+    public static boolean isKey(String s) {
+        // 2alphanum
+        return (s.length() == 2) && AsciiUtil.isAlphaNumericString(s);
+    }
+
+    public static boolean isTypeSubtag(String s) {
+        // 3*8alphanum
+        return (s.length() >= 3) && (s.length() <= 8) && AsciiUtil.isAlphaNumericString(s);
+    }
+}
--- a/src/share/classes/sun/util/resources/LocaleData.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/util/resources/LocaleData.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -177,6 +177,11 @@
 
             for (Iterator<Locale> l = candidates.iterator(); l.hasNext(); ) {
                 String lstr = l.next().toString();
+                /* truncate extra segment introduced by Java 7 for script and extesions */
+                int idx = lstr.indexOf("_#");
+                if (idx >= 0) {
+                    lstr = lstr.substring(0, idx);
+                }
                 /* Every locale string in the locale string list returned from
                    the above getSupportedLocaleString is enclosed
                    within two white spaces so that we could check some locale
--- a/src/share/classes/sun/util/resources/LocaleNames.properties	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/util/resources/LocaleNames.properties	Fri Sep 24 16:41:32 2010 -0700
@@ -228,6 +228,157 @@
 zh=Chinese
 zu=Zulu
 
+# script names
+# key is ISO 15924 script code
+
+Arab=Arabic
+Armi=Imperial Aramaic
+Armn=Armenian
+Avst=Avestan
+Bali=Balinese
+Bamu=Bamum
+Bass=Bassa Vah
+Batk=Batak
+Beng=Bengali
+Blis=Blissymbols
+Bopo=Bopomofo
+Brah=Brahmi
+Brai=Braille
+Bugi=Buginese
+Buhd=Buhid
+Cakm=Chakma
+Cans=Unified Canadian Aboriginal Syllabics
+Cari=Carian
+Cham=Cham
+Cher=Cherokee
+Cirt=Cirth
+Copt=Coptic
+Cprt=Cypriot
+Cyrl=Cyrillic
+Cyrs=Old Church Slavonic Cyrillic
+Deva=Devanagari
+Dsrt=Deseret
+Dupl=Duployan shorthand
+Egyd=Egyptian demotic
+Egyh=Egyptian hieratic
+Egyp=Egyptian hieroglyphs
+Elba=Elbasan
+Ethi=Ethiopic
+Geok=Khutsuri
+Geor=Georgian
+Glag=Glagolitic
+Goth=Gothic
+Gran=Grantha
+Grek=Greek
+Gujr=Gujarati
+Guru=Gurmukhi
+Hang=Hangul
+Hani=Han
+Hano=Hanunoo
+Hans=Simplified Han
+Hant=Traditional Han
+Hebr=Hebrew
+Hira=Hiragana
+Hmng=Pahawh Hmong
+Hrkt=Katakana or Hiragana
+Hung=Old Hungarian
+Inds=Indus
+Ital=Old Italic
+Java=Javanese
+Jpan=Japanese
+Kali=Kayah Li
+Kana=Katakana
+Khar=Kharoshthi
+Khmr=Khmer
+Knda=Kannada
+Kore=Korean
+Kpel=Kpelle
+Kthi=Kaithi
+Lana=Tai Tham
+Laoo=Lao
+Latf=Fraktur Latin
+Latg=Gaelic Latin
+Latn=Latin
+Lepc=Lepcha
+Limb=Limbu
+Lina=Linear A
+Linb=Linear B
+Lisu=Lisu
+Loma=Loma
+Lyci=Lycian
+Lydi=Lydian
+Mand=Mandaic
+Mani=Manichaean
+Maya=Mayan hieroglyphs
+Mend=Mende
+Merc=Meroitic Cursive
+Mero=Meroitic
+Mlym=Malayalam
+Mong=Mongolian
+Moon=Moon
+Mtei=Meitei Mayek
+Mymr=Myanmar
+Narb=Old North Arabian
+Nbat=Nabataean
+Nkgb=Nakhi Geba
+Nkoo=N\u2019Ko
+Ogam=Ogham
+Olck=Ol Chiki
+Orkh=Orkhon
+Orya=Oriya
+Osma=Osmanya
+Palm=Palmyrene
+Perm=Old Permic
+Phag=Phags-pa
+Phli=Inscriptional Pahlavi
+Phlp=Psalter Pahlavi
+Phlv=Book Pahlavi
+Phnx=Phoenician
+Plrd=Miao
+Prti=Inscriptional Parthian
+Rjng=Rejang
+Roro=Rongorongo
+Runr=Runic
+Samr=Samaritan
+Sara=Sarati
+Sarb=Old South Arabian
+Saur=Saurashtra
+Sgnw=SignWriting
+Shaw=Shavian
+Sind=Sindhi
+Sinh=Sinhala
+Sund=Sundanese
+Sylo=Syloti Nagri
+Syrc=Syriac
+Syre=Estrangelo Syriac
+Syrj=Western Syriac
+Syrn=Eastern Syriac
+Tagb=Tagbanwa
+Tale=Tai Le
+Talu=New Tai Lue
+Taml=Tamil
+Tavt=Tai Viet
+Telu=Telugu
+Teng=Tengwar
+Tfng=Tifinagh
+Tglg=Tagalog
+Thaa=Thaana
+Thai=Thai
+Tibt=Tibetan
+Ugar=Ugaritic
+Vaii=Vai
+Visp=Visible Speech
+Wara=Warang Citi
+Xpeo=Old Persian
+Xsux=Sumero-Akkadian Cuneiform
+Yiii=Yi
+Zinh=Inherited script
+Zmth=Mathematical Notation
+Zsym=Symbols
+Zxxx=Unwritten
+Zyyy=Undetermined script
+Zzzz=Uncoded script
+
 # country names
 # key is ISO 3166 country code
 
@@ -479,6 +630,39 @@
 ZM=Zambia
 ZW=Zimbabwe
 
+# territory names
+# key is UN M.49 country and area code
+
+001=World
+002=Africa
+003=North America
+005=South America
+009=Oceania
+011=Western Africa
+013=Central America
+014=Eastern Africa
+015=Northern Africa
+017=Middle Africa
+018=Southern Africa
+019=Americas
+021=Northern America
+029=Caribbean
+030=Eastern Asia
+034=Southern Asia
+035=South-Eastern Asia
+039=Southern Europe
+053=Australia and New Zealand
+054=Melanesia
+057=Micronesian Region
+061=Polynesia
+142=Asia
+143=Central Asia
+145=Western Asia
+150=Europe
+151=Eastern Europe
+154=Northern Europe
+155=Western Europe
+419=Latin America and the Caribbean
 
 # variant names
 # key is %%variant
--- a/src/share/classes/sun/util/resources/LocaleNames_zh.properties	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/util/resources/LocaleNames_zh.properties	Fri Sep 24 16:41:32 2010 -0700
@@ -227,6 +227,12 @@
 zh=\u4e2d\u6587
 zu=\u7956\u9c81\u6587
 
+# script names
+# key is ISO 15924 script code
+
+Hans=\u7b80\u4f53\u4e2d\u6587
+Hant=\u7e41\u4f53\u4e2d\u6587
+
 # country names
 # key is ISO 3166 country code
 
--- a/src/share/classes/sun/util/resources/LocaleNames_zh_TW.properties	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/classes/sun/util/resources/LocaleNames_zh_TW.properties	Fri Sep 24 16:41:32 2010 -0700
@@ -227,6 +227,12 @@
 zh=\u4e2d\u6587
 zu=\u7956\u9b6f\u6587
 
+# script names
+# key is ISO 15924 script code
+
+Hans=\u7c21\u9ad4\u4e2d\u6587
+Hant=\u7e41\u9ad4\u4e2d\u6587
+
 # country names
 # key is ISO 3166 country code
 
--- a/src/share/native/java/lang/System.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/java/lang/System.c	Fri Sep 24 16:41:32 2010 -0700
@@ -80,6 +80,21 @@
         (*env)->DeleteLocalRef(env, jval); \
         (*env)->DeleteLocalRef(env, r); \
     } else ((void) 0)
+#define REMOVEPROP(props, key) \
+    if (1) { \
+        jstring jkey = JNU_NewStringPlatform(env, key); \
+        jobject r = (*env)->CallObjectMethod(env, props, removeID, jkey); \
+        if ((*env)->ExceptionOccurred(env)) return NULL; \
+        (*env)->DeleteLocalRef(env, jkey); \
+        (*env)->DeleteLocalRef(env, r); \
+    } else ((void) 0)
+#define GETPROP(props, key, jret) \
+    if (1) { \
+        jstring jkey = JNU_NewStringPlatform(env, key); \
+        jret = (*env)->CallObjectMethod(env, props, getPropID, jkey); \
+        if ((*env)->ExceptionOccurred(env)) return NULL; \
+        (*env)->DeleteLocalRef(env, jkey); \
+    } else ((void) 0)
 
 #ifndef VENDOR /* Third party may overwrite this. */
 #define VENDOR "Sun Microsystems Inc."
@@ -90,6 +105,60 @@
 #define JAVA_MAX_SUPPORTED_VERSION 51
 #define JAVA_MAX_SUPPORTED_MINOR_VERSION 0
 
+static int fmtdefault; // boolean value
+jobject fillI18nProps(JNIEnv *env, jobject props, char *baseKey,
+                      char *platformDispVal, char *platformFmtVal,
+                      jmethodID putID, jmethodID getPropID) {
+    jstring jVMBaseVal = NULL;
+
+    GETPROP(props, baseKey, jVMBaseVal);
+    if (jVMBaseVal) {
+        // user specified the base property.  there's nothing to do here.
+        (*env)->DeleteLocalRef(env, jVMBaseVal);
+    } else {
+        char buf[64];
+        jstring jVMVal = NULL;
+        const char *baseVal = "";
+
+        /* user.xxx base property */
+        if (fmtdefault) {
+            if (platformFmtVal) {
+                PUTPROP(props, baseKey, platformFmtVal);
+                baseVal = platformFmtVal;
+            }
+        } else {
+            if (platformDispVal) {
+                PUTPROP(props, baseKey, platformDispVal);
+                baseVal = platformDispVal;
+            }
+        }
+
+        /* user.xxx.display property */
+        jio_snprintf(buf, sizeof(buf), "%s.display", baseKey);
+        GETPROP(props, buf, jVMVal);
+        if (jVMVal == NULL) {
+            if (platformDispVal && (strcmp(baseVal, platformDispVal) != 0)) {
+                PUTPROP(props, buf, platformDispVal);
+            }
+        } else {
+            (*env)->DeleteLocalRef(env, jVMVal);
+        }
+
+        /* user.xxx.format property */
+        jio_snprintf(buf, sizeof(buf), "%s.format", baseKey);
+        GETPROP(props, buf, jVMVal);
+        if (jVMVal == NULL) {
+            if (platformFmtVal && (strcmp(baseVal, platformFmtVal) != 0)) {
+                PUTPROP(props, buf, platformFmtVal);
+            }
+        } else {
+            (*env)->DeleteLocalRef(env, jVMVal);
+        }
+    }
+
+    return NULL;
+}
+
 JNIEXPORT jobject JNICALL
 Java_java_lang_System_initProperties(JNIEnv *env, jclass cla, jobject props)
 {
@@ -99,6 +168,16 @@
                                           (*env)->GetObjectClass(env, props),
                                           "put",
             "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+    jmethodID removeID = (*env)->GetMethodID(env,
+                                          (*env)->GetObjectClass(env, props),
+                                          "remove",
+            "(Ljava/lang/Object;)Ljava/lang/Object;");
+    jmethodID getPropID = (*env)->GetMethodID(env,
+                                          (*env)->GetObjectClass(env, props),
+                                          "getProperty",
+            "(Ljava/lang/String;)Ljava/lang/String;");
+    jobject ret = NULL;
+    jstring jVMVal = NULL;
 
     if (sprops == NULL || putID == NULL ) return NULL;
 
@@ -218,7 +297,46 @@
         PUTPROP(props, "sun.desktop", sprops->desktop);
     }
 
-    return JVM_InitProperties(env, props);
+    /*
+     * unset "user.language", "user.country", and "user.variant"
+     * in order to tell whether the command line option "-DXXXX=YYYY" is
+     * specified or not.  They will be reset in fillI18nProps() below.
+     */
+    REMOVEPROP(props, "user.language");
+    REMOVEPROP(props, "user.country");
+    REMOVEPROP(props, "user.variant");
+    REMOVEPROP(props, "file.encoding");
+
+    ret = JVM_InitProperties(env, props);
+
+    /* Check the compatibility flag */
+    GETPROP(props, "sun.locale.formatasdefault", jVMVal);
+    if (jVMVal) {
+        const char * val = (*env)->GetStringUTFChars(env, jVMVal, 0);
+        fmtdefault = !strcmp(val, "true");
+        (*env)->ReleaseStringUTFChars(env, jVMVal, val);
+        (*env)->DeleteLocalRef(env, jVMVal);
+    }
+
+    /* reconstruct i18n related properties */
+    fillI18nProps(env, props, "user.language", sprops->display_language,
+        sprops->format_language, putID, getPropID);
+    fillI18nProps(env, props, "user.country",
+        sprops->display_country, sprops->format_country, putID, getPropID);
+    fillI18nProps(env, props, "user.variant",
+        sprops->display_variant, sprops->format_variant, putID, getPropID);
+    GETPROP(props, "file.encoding", jVMVal);
+    if (jVMVal == NULL) {
+        if (fmtdefault) {
+            PUTPROP(props, "file.encoding", sprops->encoding);
+        } else {
+            PUTPROP(props, "file.encoding", sprops->sun_jnu_encoding);
+        }
+    } else {
+        (*env)->DeleteLocalRef(env, jVMVal);
+    }
+
+    return ret;
 }
 
 /*
--- a/src/share/native/java/lang/java_props.h	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/java/lang/java_props.h	Fri Sep 24 16:41:32 2010 -0700
@@ -53,8 +53,14 @@
     nchar *user_home;
 
     char *language;
+    char *format_language;
+    char *display_language;
     char *country;
+    char *format_country;
+    char *display_country;
     char *variant;
+    char *format_variant;
+    char *display_variant;
     char *encoding;
     char *sun_jnu_encoding;
     char *timezone;
--- a/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Fri Sep 24 16:41:32 2010 -0700
@@ -24,11 +24,13 @@
  */
 
 #include <stdio.h>
+#include <stdlib.h>
+#include <memory.h>
 #include "sun_java2d_cmm_lcms_LCMS.h"
 #include "jni_util.h"
 #include "Trace.h"
 #include "Disposer.h"
-#include "lcms.h"
+#include "lcms2.h"
 
 
 #define ALIGNLONG(x) (((x)+3) & ~(3))         // Aligns to DWORD boundary
@@ -38,10 +40,10 @@
 #else
 
 static
-void AdjustEndianess32(LPBYTE pByte)
+void AdjustEndianess32(cmsUInt8Number *pByte)
 {
-    BYTE temp1;
-    BYTE temp2;
+    cmsUInt8Number temp1;
+    cmsUInt8Number temp2;
 
     temp1 = *pByte++;
     temp2 = *pByte++;
@@ -57,11 +59,11 @@
 // big endian notation.
 
 static
-icInt32Number TransportValue32(icInt32Number Value)
+cmsInt32Number TransportValue32(cmsInt32Number Value)
 {
-    icInt32Number Temp = Value;
+    cmsInt32Number Temp = Value;
 
-    AdjustEndianess32((LPBYTE) &Temp);
+    AdjustEndianess32((cmsUInt8Number*) &Temp);
     return Temp;
 }
 
@@ -84,7 +86,13 @@
 /* Default temp profile list size */
 #define DF_ICC_BUF_SIZE 32
 
-#define ERR_MSG_SIZE 20
+#define ERR_MSG_SIZE 256
+
+#ifdef _MSC_VER
+# ifndef snprintf
+#       define snprintf  _snprintf
+# endif
+#endif
 
 typedef union storeID_s {    /* store SProfile stuff in a Java Long */
     cmsHPROFILE pf;
@@ -93,6 +101,11 @@
     jlong j;
 } storeID_t, *storeID_p;
 
+typedef union {
+    cmsTagSignature cms;
+    jint j;
+} TagSignature_t, *TagSignature_p;
+
 static jfieldID Trans_profileIDs_fID;
 static jfieldID Trans_renderType_fID;
 static jfieldID Trans_ID_fID;
@@ -108,21 +121,26 @@
 
 JavaVM *javaVM;
 
-int errorHandler(int errorCode, const char *errorText) {
+void errorHandler(cmsContext ContextID, cmsUInt32Number errorCode,
+                  const char *errorText) {
     JNIEnv *env;
     char errMsg[ERR_MSG_SIZE];
-    /* We can safely use sprintf here because error message has limited size */
-    sprintf(errMsg, "LCMS error %d", errorCode);
+
+    int count = snprintf(errMsg, ERR_MSG_SIZE,
+                          "LCMS error %d: %s", errorCode, errorText);
+    if (count < 0 || count >= ERR_MSG_SIZE) {
+        count = ERR_MSG_SIZE - 1;
+    }
+    errMsg[count] = 0;
 
     (*javaVM)->AttachCurrentThread(javaVM, (void**)&env, NULL);
     JNU_ThrowByName(env, "java/awt/color/CMMException", errMsg);
-    return 1;
 }
 
 JNIEXPORT int JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
     javaVM = jvm;
 
-    cmsSetErrorHandler(errorHandler);
+    cmsSetLogErrorHandler(errorHandler);
     return JNI_VERSION_1_6;
 }
 
@@ -141,11 +159,10 @@
  */
 JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_createNativeTransform
   (JNIEnv *env, jclass cls, jlongArray profileIDs, jint renderType,
-   jobject disposerRef)
+   jint inFormatter, jint outFormatter, jobject disposerRef)
 {
-    LPLCMSICCPROFILE _iccArray[DF_ICC_BUF_SIZE];
-    LPLCMSICCPROFILE *iccArray = &_iccArray[0];
-    cmsHTRANSFORM transform;
+    cmsHPROFILE _iccArray[DF_ICC_BUF_SIZE];
+    cmsHPROFILE *iccArray = &_iccArray[0];
     storeID_t sTrans;
     int i, j, size;
     jlong* ids;
@@ -154,17 +171,19 @@
     ids = (*env)->GetPrimitiveArrayCritical(env, profileIDs, 0);
 
     if (DF_ICC_BUF_SIZE < size*2) {
-        iccArray = (LPLCMSICCPROFILE*) malloc(
-            size*2*sizeof(LPLCMSICCPROFILE));
+        iccArray = (cmsHPROFILE*) malloc(
+            size*2*sizeof(cmsHPROFILE));
         if (iccArray == NULL) {
             J2dRlsTraceLn(J2D_TRACE_ERROR, "getXForm: iccArray == NULL");
-            return NULL;
+            return 0L;
         }
     }
 
     j = 0;
     for (i = 0; i < size; i++) {
-        LPLCMSICCPROFILE icc;
+        cmsHPROFILE icc;
+        cmsColorSpaceSignature cs;
+
         sTrans.j = ids[i];
         icc = sTrans.pf;
         iccArray[j++] = icc;
@@ -172,16 +191,17 @@
         /* Middle non-abstract profiles should be doubled before passing to
          * the cmsCreateMultiprofileTransform function
          */
+
+        cs = cmsGetColorSpace(icc);
         if (size > 2 && i != 0 && i != size - 1 &&
-            icc->ColorSpace != icSigXYZData &&
-            icc->ColorSpace != icSigLabData)
+            cs != cmsSigXYZData && cs != cmsSigLabData)
         {
             iccArray[j++] = icc;
         }
     }
 
     sTrans.xf = cmsCreateMultiprofileTransform(iccArray, j,
-        0, 0, renderType, 0);
+        inFormatter, outFormatter, renderType, 0);
 
     (*env)->ReleasePrimitiveArrayCritical(env, profileIDs, ids, 0);
 
@@ -190,12 +210,13 @@
                                        "sTrans.xf == NULL");
         JNU_ThrowByName(env, "java/awt/color/CMMException",
                         "Cannot get color transform");
+    } else {
+        Disposer_AddRecord(env, disposerRef, LCMS_freeTransform, sTrans.j);
     }
 
     if (iccArray != &_iccArray[0]) {
         free(iccArray);
     }
-    Disposer_AddRecord(env, disposerRef, LCMS_freeTransform, sTrans.j);
     return sTrans.j;
 }
 
@@ -215,7 +236,8 @@
     dataArray = (*env)->GetByteArrayElements (env, data, 0);
     dataSize = (*env)->GetArrayLength (env, data);
 
-    sProf.pf = cmsOpenProfileFromMem((LPVOID)dataArray, (DWORD) dataSize);
+    sProf.pf = cmsOpenProfileFromMem((const void *)dataArray,
+                                     (cmsUInt32Number) dataSize);
 
     (*env)->ReleaseByteArrayElements (env, data, dataArray, 0);
 
@@ -254,20 +276,17 @@
 JNIEXPORT jint JNICALL Java_sun_java2d_cmm_lcms_LCMS_getProfileSize
   (JNIEnv *env, jobject obj, jlong id)
 {
-    LPLCMSICCPROFILE Icc;
     storeID_t sProf;
-    unsigned char pfSize[4];
-
+    cmsUInt32Number pfSize = 0;
     sProf.j = id;
-    Icc = (LPLCMSICCPROFILE) sProf.pf;
-    Icc -> Seek(Icc, 0);
-    Icc -> Read(pfSize, 4, 1, Icc);
 
-    /* TODO: It's a correct but non-optimal for BE machines code, so should
-     * be special cased for them
-     */
-    return (pfSize[0]<<24) | (pfSize[1]<<16) | (pfSize[2]<<8) |
-        pfSize[3];
+    if (cmsSaveProfileToMem(sProf.pf, NULL, &pfSize) && ((jint)pfSize > 0)) {
+        return (jint)pfSize;
+    } else {
+      JNU_ThrowByName(env, "java/awt/color/CMMException",
+                      "Can not access specified profile.");
+        return -1;
+    }
 }
 
 /*
@@ -278,29 +297,46 @@
 JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_getProfileData
   (JNIEnv *env, jobject obj, jlong id, jbyteArray data)
 {
-    LPLCMSICCPROFILE Icc;
     storeID_t sProf;
-    unsigned char pfSize[4];
     jint size;
     jbyte* dataArray;
+    cmsUInt32Number pfSize = 0;
+    cmsBool status;
 
     sProf.j = id;
-    Icc = (LPLCMSICCPROFILE) sProf.pf;
-    Icc -> Seek(Icc, 0);
-    Icc -> Read(pfSize, 4, 1, Icc);
+
+    // determine actual profile size
+    if (!cmsSaveProfileToMem(sProf.pf, NULL, &pfSize)) {
+        JNU_ThrowByName(env, "java/awt/color/CMMException",
+                        "Can not access specified profile.");
+        return;
+    }
+
+    // verify java buffer capacity
+    size = (*env)->GetArrayLength(env, data);
+    if (0 >= size || pfSize > (cmsUInt32Number)size) {
+        JNU_ThrowByName(env, "java/awt/color/CMMException",
+                        "Insufficient buffer capacity.");
+        return;
+    }
 
     dataArray = (*env)->GetByteArrayElements (env, data, 0);
-    Icc->Seek(Icc, 0);
+
+    status = cmsSaveProfileToMem(sProf.pf, dataArray, &pfSize);
+
+    (*env)->ReleaseByteArrayElements (env, data, dataArray, 0);
 
-    /* TODO: It's a correct but non-optimal for BE machines code, so should
-     * be special cased for them
-     */
-    Icc->Read(dataArray, 1,
-              (pfSize[0]<<24) | (pfSize[1]<<16) | (pfSize[2]<<8) | pfSize[3],
-              Icc);
-    (*env)->ReleaseByteArrayElements (env, data, dataArray, 0);
+    if (!status) {
+        JNU_ThrowByName(env, "java/awt/color/CMMException",
+                        "Can not access specified profile.");
+        return;
+    }
 }
 
+/* Get profile header info */
+cmsBool _getHeaderInfo(cmsHPROFILE pf, jbyte* pBuffer, jint bufferSize);
+cmsBool _setHeaderInfo(cmsHPROFILE pf, jbyte* pBuffer, jint bufferSize);
+
 /*
  * Class:     sun_java2d_cmm_lcms_LCMS
  * Method:    getTagSize
@@ -309,24 +345,21 @@
 JNIEXPORT jint JNICALL Java_sun_java2d_cmm_lcms_LCMS_getTagSize
   (JNIEnv *env, jobject obj, jlong id, jint tagSig)
 {
-    LPLCMSICCPROFILE Icc;
     storeID_t sProf;
-    int i;
-    jint result;
+    TagSignature_t sig;
+    jint result = -1;
 
     sProf.j = id;
-    Icc = (LPLCMSICCPROFILE) sProf.pf;
+    sig.j = tagSig;
 
     if (tagSig == SigHead) {
-        result = sizeof(icHeader);
+        result = sizeof(cmsICCHeader);
     } else {
-        i =  _cmsSearchTag(Icc, tagSig, FALSE);
-        if (i >= 0) {
-            result = Icc->TagSizes[i];
+      if (cmsIsTag(sProf.pf, sig.cms)) {
+            result = cmsReadRawTag(sProf.pf, sig.cms, NULL, 0);
         } else {
             JNU_ThrowByName(env, "java/awt/color/CMMException",
                             "ICC profile tag not found");
-            result = -1;
         }
     }
 
@@ -341,43 +374,83 @@
 JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_getTagData
   (JNIEnv *env, jobject obj, jlong id, jint tagSig, jbyteArray data)
 {
-    LPLCMSICCPROFILE Icc;
     storeID_t sProf;
+    TagSignature_t sig;
+    cmsInt32Number tagSize;
+
     jbyte* dataArray;
-    int i, tagSize;
+    jint bufSize;
 
     sProf.j = id;
-    Icc = (LPLCMSICCPROFILE) sProf.pf;
+    sig.j = tagSig;
 
     if (tagSig == SigHead) {
+        cmsBool status;
+
+        bufSize =(*env)->GetArrayLength(env, data);
+
+        if (bufSize < sizeof(cmsICCHeader)) {
+           JNU_ThrowByName(env, "java/awt/color/CMMException",
+                            "Insufficient buffer capacity");
+           return;
+        }
+
         dataArray = (*env)->GetByteArrayElements (env, data, 0);
-        tagSize =(*env)->GetArrayLength(env, data);
-        Icc -> Seek(Icc, 0);
-        Icc -> Read(dataArray, sizeof(icHeader), 1, Icc);
+
+        if (dataArray == NULL) {
+           JNU_ThrowByName(env, "java/awt/color/CMMException",
+                            "Unable to get buffer");
+           return;
+        }
+
+        status = _getHeaderInfo(sProf.pf, dataArray, bufSize);
+
         (*env)->ReleaseByteArrayElements (env, data, dataArray, 0);
+
+        if (!status) {
+            JNU_ThrowByName(env, "java/awt/color/CMMException",
+                            "ICC Profile header not found");
+        }
+
         return;
     }
 
+    if (cmsIsTag(sProf.pf, sig.cms)) {
+        tagSize = cmsReadRawTag(sProf.pf, sig.cms, NULL, 0);
+    } else {
+        JNU_ThrowByName(env, "java/awt/color/CMMException",
+                        "ICC profile tag not found");
+        return;
+    }
 
-    i =  _cmsSearchTag(Icc, tagSig, FALSE);
-    if (i >=0) {
-        tagSize = Icc->TagSizes[i];
-        dataArray = (*env)->GetByteArrayElements (env, data, 0);
-        Icc->Seek(Icc, Icc->TagOffsets[i]);
-        Icc->Read(dataArray, 1, tagSize, Icc);
-        (*env)->ReleaseByteArrayElements (env, data, dataArray, 0);
+    // verify data buffer capacity
+    bufSize = (*env)->GetArrayLength(env, data);
+
+    if (tagSize < 0 || 0 > bufSize || tagSize > bufSize) {
+        JNU_ThrowByName(env, "java/awt/color/CMMException",
+                        "Insufficient buffer capacity.");
         return;
     }
 
-    JNU_ThrowByName(env, "java/awt/color/CMMException",
-                    "ICC profile tag not found");
+    dataArray = (*env)->GetByteArrayElements (env, data, 0);
+
+    if (dataArray == NULL) {
+        JNU_ThrowByName(env, "java/awt/color/CMMException",
+                        "Unable to get buffer");
+        return;
+    }
+
+    bufSize = cmsReadRawTag(sProf.pf, sig.cms, dataArray, tagSize);
+
+    (*env)->ReleaseByteArrayElements (env, data, dataArray, 0);
+
+    if (bufSize != tagSize) {
+        JNU_ThrowByName(env, "java/awt/color/CMMException",
+                        "Can not get tag data.");
+    }
     return;
 }
 
-// Modify data for a tag in a profile
-LCMSBOOL LCMSEXPORT _cmsModifyTagData(cmsHPROFILE hProfile,
-                                 icTagSignature sig, void *data, size_t size);
-
 /*
  * Class:     sun_java2d_cmm_lcms_LCMS
  * Method:    setTagData
@@ -386,23 +459,32 @@
 JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_setTagData
   (JNIEnv *env, jobject obj, jlong id, jint tagSig, jbyteArray data)
 {
-    cmsHPROFILE profile;
     storeID_t sProf;
+    TagSignature_t sig;
+    cmsBool status;
     jbyte* dataArray;
     int tagSize;
 
+    sProf.j = id;
+    sig.j = tagSig;
+
+
+    tagSize =(*env)->GetArrayLength(env, data);
+
+    dataArray = (*env)->GetByteArrayElements(env, data, 0);
+
     if (tagSig == SigHead) {
-        J2dRlsTraceLn(J2D_TRACE_ERROR, "LCMS_setTagData on icSigHead not "
-                      "permitted");
-        return;
+        status = _setHeaderInfo(sProf.pf, dataArray, tagSize);
+    } else {
+        status = cmsWriteRawTag(sProf.pf, sig.cms, dataArray, tagSize);
     }
 
-    sProf.j = id;
-    profile = (cmsHPROFILE) sProf.pf;
-    dataArray = (*env)->GetByteArrayElements(env, data, 0);
-    tagSize =(*env)->GetArrayLength(env, data);
-    _cmsModifyTagData(profile, (icTagSignature) tagSig, dataArray, tagSize);
     (*env)->ReleaseByteArrayElements(env, data, dataArray, 0);
+
+    if (!status) {
+        JNU_ThrowByName(env, "java/awt/color/CMMException",
+                        "Can not write tag data.");
+    }
 }
 
 void* getILData (JNIEnv *env, jobject img, jint* pDataType,
@@ -456,7 +538,7 @@
   (JNIEnv *env, jclass obj, jobject trans, jobject src, jobject dst)
 {
     storeID_t sTrans;
-    int size, inFmt, outFmt, srcDType, dstDType, outSize, renderType;
+    int inFmt, outFmt, srcDType, dstDType;
     int srcOffset, srcNextRowOffset, dstOffset, dstNextRowOffset;
     int width, height, i;
     void* inputBuffer;
@@ -483,8 +565,6 @@
     }
 #endif
     sTrans.j = (*env)->GetLongField (env, trans, Trans_ID_fID);
-    cmsChangeBuffersFormat(sTrans.xf, inFmt, outFmt);
-
 
     if (sTrans.xf == NULL) {
         J2dRlsTraceLn(J2D_TRACE_ERROR, "LCMS_colorConvert: transform == NULL");
@@ -565,190 +645,54 @@
     PF_ID_fID = (*env)->GetFieldID (env, Pf, "ID", "J");
 }
 
-LCMSBOOL _cmsModifyTagData(cmsHPROFILE hProfile, icTagSignature sig,
-                       void *data, size_t size)
+cmsBool _getHeaderInfo(cmsHPROFILE pf, jbyte* pBuffer, jint bufferSize)
 {
-    LCMSBOOL isNew;
-    int i, idx, delta, count;
-    LPBYTE padChars[3] = {0, 0, 0};
-    LPBYTE beforeBuf, afterBuf, ptr;
-    size_t beforeSize, afterSize;
-    icUInt32Number profileSize, temp;
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-    isNew = FALSE;
-    idx = _cmsSearchTag(Icc, sig, FALSE);
-    if (idx < 0) {
-        isNew = TRUE;
-        idx = Icc->TagCount++;
-        if (Icc->TagCount >= MAX_TABLE_TAG) {
-            J2dRlsTraceLn1(J2D_TRACE_ERROR, "_cmsModifyTagData: Too many tags "
-                           "(%d)\n", Icc->TagCount);
-            Icc->TagCount = MAX_TABLE_TAG-1;
-            return FALSE;
-        }
-    }
-
-    /* Read in size from header */
-    Icc->Seek(Icc, 0);
-    Icc->Read(&profileSize, sizeof(icUInt32Number), 1, Icc);
-    AdjustEndianess32((LPBYTE) &profileSize);
+  cmsUInt32Number pfSize = 0;
+  cmsUInt8Number* pfBuffer = NULL;
+  cmsBool status = FALSE;
 
-    /* Compute the change in profile size */
-    if (isNew) {
-        delta = sizeof(icTag) + ALIGNLONG(size);
-    } else {
-        delta = ALIGNLONG(size) - ALIGNLONG(Icc->TagSizes[idx]);
-    }
-    /* Add tag to internal structures */
-    ptr = malloc(size);
-    if (ptr == NULL) {
-        if(isNew) {
-            Icc->TagCount--;
-        }
-        J2dRlsTraceLn(J2D_TRACE_ERROR, "_cmsModifyTagData: ptr == NULL");
-        return FALSE;
-    }
+  if (!cmsSaveProfileToMem(pf, NULL, &pfSize) ||
+      pfSize < sizeof(cmsICCHeader) ||
+      bufferSize < sizeof(cmsICCHeader))
+  {
+    return FALSE;
+  }
 
-    /* We change the size of Icc here only if we know it'll actually
-     * grow: if Icc is about to shrink we must wait until we've read
-     * the previous data.  */
-    if (delta > 0) {
-        if (!Icc->Grow(Icc, delta)) {
-            free(ptr);
-            if(isNew) {
-                Icc->TagCount--;
-            }
-            J2dRlsTraceLn(J2D_TRACE_ERROR,
-                          "_cmsModifyTagData: Icc->Grow() == FALSE");
-            return FALSE;
-        }
-    }
-
-    /* Compute size of tag data before/after the modified tag */
-    beforeSize = ((isNew)?profileSize:Icc->TagOffsets[idx]) -
-                 Icc->TagOffsets[0];
-    if (Icc->TagCount == (idx + 1)) {
-        afterSize = 0;
-    } else {
-        afterSize = profileSize - Icc->TagOffsets[idx+1];
-    }
-    /* Make copies of the data before/after the modified tag */
-    if (beforeSize > 0) {
-        beforeBuf = malloc(beforeSize);
-        if (!beforeBuf) {
-            if(isNew) {
-                Icc->TagCount--;
-            }
-            free(ptr);
-            J2dRlsTraceLn(J2D_TRACE_ERROR,
-                          "_cmsModifyTagData: beforeBuf == NULL");
-            return FALSE;
-        }
-        Icc->Seek(Icc, Icc->TagOffsets[0]);
-        Icc->Read(beforeBuf, beforeSize, 1, Icc);
-    }
+  pfBuffer = malloc(pfSize);
+  if (pfBuffer == NULL) {
+    return FALSE;
+  }
 
-    if (afterSize > 0) {
-        afterBuf = malloc(afterSize);
-        if (!afterBuf) {
-            free(ptr);
-            if(isNew) {
-                Icc->TagCount--;
-            }
-            if (beforeSize > 0) {
-                free(beforeBuf);
-            }
-            J2dRlsTraceLn(J2D_TRACE_ERROR,
-                          "_cmsModifyTagData: afterBuf == NULL");
-            return FALSE;
-        }
-        Icc->Seek(Icc, Icc->TagOffsets[idx+1]);
-        Icc->Read(afterBuf, afterSize, 1, Icc);
-    }
+  // load raw profile data into the buffer
+  if (cmsSaveProfileToMem(pf, pfBuffer, &pfSize)) {
+    memcpy(pBuffer, pfBuffer, sizeof(cmsICCHeader));
+    status = TRUE;
+  }
+  free(pfBuffer);
+  return status;
+}
 
-    CopyMemory(ptr, data, size);
-    Icc->TagSizes[idx] = size;
-    Icc->TagNames[idx] = sig;
-    if (Icc->TagPtrs[idx]) {
-        free(Icc->TagPtrs[idx]);
-    }
-    Icc->TagPtrs[idx] = ptr;
-    if (isNew) {
-        Icc->TagOffsets[idx] = profileSize;
-    }
-
+cmsBool _setHeaderInfo(cmsHPROFILE pf, jbyte* pBuffer, jint bufferSize)
+{
+  cmsICCHeader pfHeader = { 0 };
 
-    /* Update the profile size in the header */
-    profileSize += delta;
-    Icc->Seek(Icc, 0);
-    temp = TransportValue32(profileSize);
-    Icc->Write(Icc, sizeof(icUInt32Number), &temp);
-
-    /* Shrink Icc, if needed.  */
-    if (delta < 0) {
-        if (!Icc->Grow(Icc, delta)) {
-            free(ptr);
-            if(isNew) {
-                Icc->TagCount--;
-            }
-            J2dRlsTraceLn(J2D_TRACE_ERROR,
-                          "_cmsModifyTagData: Icc->Grow() == FALSE");
-            return FALSE;
-        }
-    }
+  if (pBuffer == NULL || bufferSize < sizeof(cmsICCHeader)) {
+    return FALSE;
+  }
 
-    /* Adjust tag offsets: if the tag is new, we must account
-       for the new tag table entry; otherwise, only those tags after
-       the modified tag are changed (by delta) */
-    if (isNew) {
-        for (i = 0; i < Icc->TagCount; ++i) {
-            Icc->TagOffsets[i] += sizeof(icTag);
-        }
-    } else {
-        for (i = idx+1; i < Icc->TagCount; ++i) {
-            Icc->TagOffsets[i] += delta;
-        }
-    }
-
-    /* Write out a new tag table */
-    count = 0;
-    for (i = 0; i < Icc->TagCount; ++i) {
-        if (Icc->TagNames[i] != 0) {
-            ++count;
-        }
-    }
-    Icc->Seek(Icc, sizeof(icHeader));
-    temp = TransportValue32(count);
-    Icc->Write(Icc, sizeof(icUInt32Number), &temp);
+  memcpy(&pfHeader, pBuffer, sizeof(cmsICCHeader));
 
-    for (i = 0; i < Icc->TagCount; ++i) {
-        if (Icc->TagNames[i] != 0) {
-            icTag tag;
-            tag.sig = TransportValue32(Icc->TagNames[i]);
-            tag.offset = TransportValue32((icInt32Number) Icc->TagOffsets[i]);
-            tag.size = TransportValue32((icInt32Number) Icc->TagSizes[i]);
-            Icc->Write(Icc, sizeof(icTag), &tag);
-        }
-    }
+  // now set header fields, which we can access using the lcms2 public API
+  cmsSetHeaderFlags(pf, pfHeader.flags);
+  cmsSetHeaderManufacturer(pf, pfHeader.manufacturer);
+  cmsSetHeaderModel(pf, pfHeader.model);
+  cmsSetHeaderAttributes(pf, pfHeader.attributes);
+  cmsSetHeaderProfileID(pf, (cmsUInt8Number*)&(pfHeader.profileID));
+  cmsSetHeaderRenderingIntent(pf, pfHeader.renderingIntent);
+  cmsSetPCS(pf, pfHeader.pcs);
+  cmsSetColorSpace(pf, pfHeader.colorSpace);
+  cmsSetDeviceClass(pf, pfHeader.deviceClass);
+  cmsSetEncodedICCversion(pf, pfHeader.version);
 
-    /* Write unchanged data before the modified tag */
-    if (beforeSize > 0) {
-        Icc->Write(Icc, beforeSize, beforeBuf);
-        free(beforeBuf);
-    }
-
-    /* Write modified tag data */
-    Icc->Write(Icc, size, data);
-    if (size % 4) {
-        Icc->Write(Icc, 4 - (size % 4), padChars);
-    }
-
-    /* Write unchanged data after the modified tag */
-    if (afterSize > 0) {
-        Icc->Write(Icc, afterSize, afterBuf);
-        free(afterBuf);
-    }
-
-    return TRUE;
+  return TRUE;
 }
--- a/src/share/native/sun/java2d/cmm/lcms/cmscam02.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmscam02.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,69 +49,65 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
 
-
+#include "lcms2_internal.h"
 
 // CIECAM 02 appearance model. Many thanks to Jordi Vilar for the debugging.
 
-#include "lcms.h"
-
-
-LCMSAPI LCMSHANDLE LCMSEXPORT cmsCIECAM02Init(LPcmsViewingConditions pVC);
-LCMSAPI void       LCMSEXPORT cmsCIECAM02Done(LCMSHANDLE hModel);
-LCMSAPI void       LCMSEXPORT cmsCIECAM02Forward(LCMSHANDLE hModel, LPcmsCIEXYZ pIn, LPcmsJCh pOut);
-LCMSAPI void       LCMSEXPORT cmsCIECAM02Reverse(LCMSHANDLE hModel, LPcmsJCh pIn,    LPcmsCIEXYZ pOut);
-
-
 // ---------- Implementation --------------------------------------------
 
 typedef struct  {
 
-    double XYZ[3];
-    double RGB[3];
-    double RGBc[3];
-    double RGBp[3];
-    double RGBpa[3];
-    double a, b, h, e, H, A, J, Q, s, t, C, M;
-    double abC[2];
-    double abs[2];
-    double abM[2];
+    cmsFloat64Number XYZ[3];
+    cmsFloat64Number RGB[3];
+    cmsFloat64Number RGBc[3];
+    cmsFloat64Number RGBp[3];
+    cmsFloat64Number RGBpa[3];
+    cmsFloat64Number a, b, h, e, H, A, J, Q, s, t, C, M;
+    cmsFloat64Number abC[2];
+    cmsFloat64Number abs[2];
+    cmsFloat64Number abM[2];
 
-} CAM02COLOR, *LPCAM02COLOR;
+} CAM02COLOR;
 
 typedef struct  {
 
     CAM02COLOR adoptedWhite;
-    double LA, Yb;
-    double F, c, Nc;
-    int surround;
-    double n, Nbb, Ncb, z, FL, D;
+    cmsFloat64Number LA, Yb;
+    cmsFloat64Number F, c, Nc;
+    cmsUInt32Number surround;
+    cmsFloat64Number n, Nbb, Ncb, z, FL, D;
 
-} cmsCIECAM02, *LPcmsCIECAM02;
+       cmsContext ContextID;
+
+} cmsCIECAM02;
 
 
 static
-double compute_n(LPcmsCIECAM02 pMod)
+cmsFloat64Number compute_n(cmsCIECAM02* pMod)
 {
-    return(pMod -> Yb / pMod -> adoptedWhite.XYZ[1]);
+    return (pMod -> Yb / pMod -> adoptedWhite.XYZ[1]);
 }
 
 static
-double compute_z(LPcmsCIECAM02 pMod)
+cmsFloat64Number compute_z(cmsCIECAM02* pMod)
 {
-    return(1.48 + pow(pMod -> n, 0.5));
+    return (1.48 + pow(pMod -> n, 0.5));
 }
 
 static
-double computeNbb(LPcmsCIECAM02 pMod)
+cmsFloat64Number computeNbb(cmsCIECAM02* pMod)
 {
-    return(0.725 * pow((1.0 / pMod -> n), 0.2));
+    return (0.725 * pow((1.0 / pMod -> n), 0.2));
 }
 
 static
-double computeFL(LPcmsCIECAM02 pMod)
+cmsFloat64Number computeFL(cmsCIECAM02* pMod)
 {
-    double k, FL;
+    cmsFloat64Number k, FL;
 
     k = 1.0 / ((5.0 * pMod->LA) + 1.0);
     FL = 0.2 * pow(k, 4.0) * (5.0 * pMod->LA) + 0.1 *
@@ -121,9 +118,9 @@
 }
 
 static
-double computeD(LPcmsCIECAM02 pMod)
+cmsFloat64Number computeD(cmsCIECAM02* pMod)
 {
-    double D;
+    cmsFloat64Number D;
 
     D = pMod->F - (1.0/3.6)*(exp(((-pMod ->LA-42) / 92.0)));
 
@@ -142,9 +139,10 @@
 }
 
 static
-CAM02COLOR ChromaticAdaptation(CAM02COLOR clr, LPcmsCIECAM02 pMod)
+CAM02COLOR ChromaticAdaptation(CAM02COLOR clr, cmsCIECAM02* pMod)
 {
-    int i;
+    cmsUInt32Number i;
+
     for (i = 0; i < 3; i++) {
         clr.RGBc[i] = ((pMod -> adoptedWhite.XYZ[1] *
             (pMod->D / pMod -> adoptedWhite.RGB[i])) +
@@ -156,11 +154,9 @@
 
 
 static
-CAM02COLOR CAT02toHPE (CAM02COLOR clr)
+CAM02COLOR CAT02toHPE(CAM02COLOR clr)
 {
-
-    double M[9];
-
+    cmsFloat64Number M[9];
 
     M[0] =(( 0.38971 *  1.096124) + (0.68898 * 0.454369) + (-0.07868 * -0.009628));
     M[1] =(( 0.38971 * -0.278869) + (0.68898 * 0.473533) + (-0.07868 * -0.005698));
@@ -180,10 +176,10 @@
 }
 
 static
-CAM02COLOR NonlinearCompression(CAM02COLOR clr, LPcmsCIECAM02 pMod)
+CAM02COLOR NonlinearCompression(CAM02COLOR clr, cmsCIECAM02* pMod)
 {
-    int i;
-    double temp;
+    cmsUInt32Number i;
+    cmsFloat64Number temp;
 
     for (i = 0; i < 3; i++) {
         if (clr.RGBp[i] < 0) {
@@ -204,9 +200,9 @@
 }
 
 static
-CAM02COLOR ComputeCorrelates(CAM02COLOR clr, LPcmsCIECAM02 pMod)
+CAM02COLOR ComputeCorrelates(CAM02COLOR clr, cmsCIECAM02* pMod)
 {
-    double a, b, temp, e, t, r2d, d2r;
+    cmsFloat64Number a, b, temp, e, t, r2d, d2r;
 
     a = clr.RGBpa[0] - (12.0 * clr.RGBpa[1] / 11.0) + (clr.RGBpa[2] / 11.0);
     b = (clr.RGBpa[0] + clr.RGBpa[1] - (2.0 * clr.RGBpa[2])) / 9.0;
@@ -274,10 +270,10 @@
 
 
 static
-CAM02COLOR InverseCorrelates(CAM02COLOR clr, LPcmsCIECAM02 pMod)
+CAM02COLOR InverseCorrelates(CAM02COLOR clr, cmsCIECAM02* pMod)
 {
 
-    double t, e, p1, p2, p3, p4, p5, hr, d2r;
+    cmsFloat64Number t, e, p1, p2, p3, p4, p5, hr, d2r;
     d2r = 3.141592654 / 180.0;
 
     t = pow( (clr.C / (pow((clr.J / 100.0), 0.5) *
@@ -327,10 +323,10 @@
 }
 
 static
-CAM02COLOR InverseNonlinearity(CAM02COLOR clr, LPcmsCIECAM02 pMod)
+CAM02COLOR InverseNonlinearity(CAM02COLOR clr, cmsCIECAM02* pMod)
 {
-    int i;
-    double c1;
+    cmsUInt32Number i;
+    cmsFloat64Number c1;
 
     for (i = 0; i < 3; i++) {
         if ((clr.RGBpa[i] - 0.1) < 0) c1 = -1;
@@ -347,7 +343,7 @@
 static
 CAM02COLOR HPEtoCAT02(CAM02COLOR clr)
 {
-    double M[9];
+    cmsFloat64Number M[9];
 
     M[0] = (( 0.7328 *  1.910197) + (0.4296 * 0.370950));
     M[1] = (( 0.7328 * -1.112124) + (0.4296 * 0.629054));
@@ -362,19 +358,19 @@
     clr.RGBc[0] = (clr.RGBp[0] * M[0]) + (clr.RGBp[1] * M[1]) + (clr.RGBp[2] * M[2]);
     clr.RGBc[1] = (clr.RGBp[0] * M[3]) + (clr.RGBp[1] * M[4]) + (clr.RGBp[2] * M[5]);
     clr.RGBc[2] = (clr.RGBp[0] * M[6]) + (clr.RGBp[1] * M[7]) + (clr.RGBp[2] * M[8]);
-    return (clr);
+    return clr;
 }
 
 
 static
-CAM02COLOR InverseChromaticAdaptation(CAM02COLOR clr,  LPcmsCIECAM02 pMod)
+CAM02COLOR InverseChromaticAdaptation(CAM02COLOR clr,  cmsCIECAM02* pMod)
 {
-    int i;
+    cmsUInt32Number i;
     for (i = 0; i < 3; i++) {
         clr.RGB[i] = clr.RGBc[i] /
             ((pMod->adoptedWhite.XYZ[1] * pMod->D / pMod->adoptedWhite.RGB[i]) + 1.0 - pMod->D);
     }
-    return(clr);
+    return clr;
 }
 
 
@@ -385,23 +381,21 @@
     clr.XYZ[1] = (clr.RGB[0] *  0.454369) + (clr.RGB[1] *  0.473533) + (clr.RGB[2] *  0.072098);
     clr.XYZ[2] = (clr.RGB[0] * -0.009628) + (clr.RGB[1] * -0.005698) + (clr.RGB[2] *  1.015326);
 
-    return(clr);
+    return clr;
 }
 
 
-
-
-LCMSHANDLE LCMSEXPORT cmsCIECAM02Init(LPcmsViewingConditions pVC)
+cmsHANDLE  CMSEXPORT cmsCIECAM02Init(cmsContext ContextID, const cmsViewingConditions* pVC)
 {
-    LPcmsCIECAM02 lpMod;
-
+    cmsCIECAM02* lpMod;
 
-   if((lpMod = (LPcmsCIECAM02) _cmsMalloc(sizeof(cmsCIECAM02))) == NULL) {
-        return (LCMSHANDLE) NULL;
+    _cmsAssert(pVC != NULL);
+
+    if((lpMod = (cmsCIECAM02*) _cmsMallocZero(ContextID, sizeof(cmsCIECAM02))) == NULL) {
+        return NULL;
     }
 
-
-    ZeroMemory(lpMod, sizeof(cmsCIECAM02));
+    lpMod ->ContextID = ContextID;
 
     lpMod ->adoptedWhite.XYZ[0] = pVC ->whitePoint.X;
     lpMod ->adoptedWhite.XYZ[1] = pVC ->whitePoint.Y;
@@ -414,36 +408,30 @@
 
     switch (lpMod -> surround) {
 
-    case AVG_SURROUND_4:
-        lpMod->F = 1.0;     // Not included in CAM02
-        lpMod->c = 0.69;
-        lpMod->Nc = 1.0;
-        break;
 
-    case CUTSHEET_SURROUND:
-        lpMod->F = 0.8;
-        lpMod->c = 0.41;
-        lpMod->Nc = 0.8;
-        break;
+      case CUTSHEET_SURROUND:
+          lpMod->F = 0.8;
+          lpMod->c = 0.41;
+          lpMod->Nc = 0.8;
+          break;
 
-    case DARK_SURROUND:
-        lpMod -> F  = 0.8;
-        lpMod -> c  = 0.525;
-        lpMod -> Nc = 0.8;
-        break;
-
+      case DARK_SURROUND:
+          lpMod -> F  = 0.8;
+          lpMod -> c  = 0.525;
+          lpMod -> Nc = 0.8;
+          break;
 
-    case DIM_SURROUND:
-        lpMod -> F  = 0.9;
-        lpMod -> c  = 0.59;
-        lpMod -> Nc = 0.95;
-        break;
+      case DIM_SURROUND:
+          lpMod -> F  = 0.9;
+          lpMod -> c  = 0.59;
+          lpMod -> Nc = 0.95;
+          break;
 
-    default:
-        // Average surround
-        lpMod -> F  = 1.0;
-        lpMod -> c  = 0.69;
-        lpMod -> Nc = 1.0;
+      default:
+          // Average surround
+          lpMod -> F  = 1.0;
+          lpMod -> c  = 0.69;
+          lpMod -> Nc = 1.0;
     }
 
     lpMod -> n   = compute_n(lpMod);
@@ -451,10 +439,8 @@
     lpMod -> Nbb = computeNbb(lpMod);
     lpMod -> FL  = computeFL(lpMod);
 
-    if (lpMod -> D == D_CALCULATE ||
-        lpMod -> D == D_CALCULATE_DISCOUNT) {
-
-    lpMod -> D   = computeD(lpMod);
+    if (lpMod -> D == D_CALCULATE) {
+        lpMod -> D   = computeD(lpMod);
     }
 
     lpMod -> Ncb = lpMod -> Nbb;
@@ -464,21 +450,26 @@
     lpMod -> adoptedWhite = CAT02toHPE(lpMod -> adoptedWhite);
     lpMod -> adoptedWhite = NonlinearCompression(lpMod -> adoptedWhite, lpMod);
 
-    return (LCMSHANDLE) lpMod;
+    return (cmsHANDLE) lpMod;
 
 }
 
-void LCMSEXPORT cmsCIECAM02Done(LCMSHANDLE hModel)
+void CMSEXPORT cmsCIECAM02Done(cmsHANDLE hModel)
 {
-    LPcmsCIECAM02 lpMod = (LPcmsCIECAM02) (LPSTR) hModel;
-    if (lpMod) _cmsFree(lpMod);
+    cmsCIECAM02* lpMod = (cmsCIECAM02*) hModel;
+
+    if (lpMod) _cmsFree(lpMod ->ContextID, lpMod);
 }
 
 
-void LCMSEXPORT cmsCIECAM02Forward(LCMSHANDLE hModel, LPcmsCIEXYZ pIn, LPcmsJCh pOut)
+void CMSEXPORT cmsCIECAM02Forward(cmsHANDLE hModel, const cmsCIEXYZ* pIn, cmsJCh* pOut)
 {
     CAM02COLOR clr;
-    LPcmsCIECAM02 lpMod = (LPcmsCIECAM02) (LPSTR) hModel;
+    cmsCIECAM02* lpMod = (cmsCIECAM02*) hModel;
+
+    _cmsAssert(lpMod != NULL);
+    _cmsAssert(pIn != NULL);
+    _cmsAssert(pOut != NULL);
 
     clr.XYZ[0] = pIn ->X;
     clr.XYZ[1] = pIn ->Y;
@@ -495,11 +486,14 @@
     pOut ->h = clr.h;
 }
 
-void LCMSEXPORT cmsCIECAM02Reverse(LCMSHANDLE hModel, LPcmsJCh pIn, LPcmsCIEXYZ pOut)
+void CMSEXPORT cmsCIECAM02Reverse(cmsHANDLE hModel, const cmsJCh* pIn, cmsCIEXYZ* pOut)
 {
     CAM02COLOR clr;
-    LPcmsCIECAM02 lpMod = (LPcmsCIECAM02) (LPSTR) hModel;
+    cmsCIECAM02* lpMod = (cmsCIECAM02*) hModel;
 
+    _cmsAssert(lpMod != NULL);
+    _cmsAssert(pIn != NULL);
+    _cmsAssert(pOut != NULL);
 
     clr.J = pIn -> J;
     clr.C = pIn -> C;
@@ -514,6 +508,5 @@
     pOut ->X = clr.XYZ[0];
     pOut ->Y = clr.XYZ[1];
     pOut ->Z = clr.XYZ[2];
-
 }
 
--- a/src/share/native/sun/java2d/cmm/lcms/cmscam97.c	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,750 +0,0 @@
-/*
- * 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// This file is available under and governed by the GNU General Public
-// License version 2 only, as published by the Free Software Foundation.
-// However, the following notice accompanied the original version of this
-// file:
-//
-//
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the Software
-// is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
-// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-#include "lcms.h"
-
-
-/*
-typedef struct {
-               double J;
-               double C;
-               double h;
-
-               } cmsJCh, FAR* LPcmsJCh;
-
-
-#define AVG_SURROUND_4     0
-#define AVG_SURROUND       1
-#define DIM_SURROUND       2
-#define DARK_SURROUND      3
-#define CUTSHEET_SURROUND  4
-
-
-typedef struct {
-
-              cmsCIEXYZ whitePoint;
-              double    Yb;
-              double    La;
-              int       surround;
-              double    D_value;
-
-              } cmsViewingConditions, FAR* LPcmsViewingConditions;
-
-
-
-LCMSAPI LCMSHANDLE LCMSEXPORT cmsCIECAM97sInit(LPcmsViewingConditions pVC);
-LCMSAPI void   LCMSEXPORT cmsCIECAM97sDone(LCMSHANDLE hModel);
-LCMSAPI void   LCMSEXPORT cmsCIECAM97sForward(LCMSHANDLE hModel, LPcmsCIEXYZ pIn, LPcmsJCh pOut);
-LCMSAPI void   LCMSEXPORT cmsCIECAM97sReverse(LCMSHANDLE hModel, LPcmsJCh pIn,    LPcmsCIEXYZ pOut);
-
-*/
-
-// ---------- Implementation --------------------------------------------
-
-// #define USE_CIECAM97s2  1
-
-#ifdef USE_CIECAM97s2
-
-#       define NOISE_CONSTANT   3.05
-#else
-#       define NOISE_CONSTANT   2.05
-#endif
-
-
-/*
-  The model input data are the adapting field luminance in cd/m2
-  (normally taken to be 20% of the luminance of white in the adapting field),
-  LA , the relative tristimulus values of the stimulus, XYZ, the relative
-  tristimulus values of white in the same viewing conditions, Xw Yw Zw ,
-  and the relative luminance of the background, Yb . Relative tristimulus
-  values should be expressed on a scale from Y = 0 for a perfect black
-  to Y = 100 for a perfect reflecting diffuser. Additionally, the
-  parameters c, for the impact of surround, Nc , a chromatic induction factor,
-  and F, a factor for degree of adaptation, must be selected according to the
-  guidelines in table
-
-  All CIE tristimulus values are obtained using the CIE 1931
-  Standard Colorimetric Observer (2°).
-
-*/
-
-typedef struct {
-
-    cmsCIEXYZ WP;
-    int surround;
-    int calculate_D;
-
-    double  Yb;         // rel. luminance of background
-
-    cmsCIEXYZ RefWhite;
-
-    double La;    // The adapting field luminance in cd/m2
-
-    double c;     // Impact of surround
-    double Nc;    // Chromatic induction factor
-    double Fll;   // Lightness contrast factor (Removed on rev 2)
-    double F;     // Degree of adaptation
-
-
-    double k;
-    double Fl;
-
-    double Nbb;  // The background and chromatic brightness induction factors.
-    double Ncb;
-    double z;    // base exponential nonlinearity
-    double n;    // background induction factor
-    double D;
-
-    MAT3 MlamRigg;
-    MAT3 MlamRigg_1;
-
-    MAT3 Mhunt;
-    MAT3 Mhunt_1;
-
-    MAT3 Mhunt_x_MlamRigg_1;
-    MAT3 MlamRigg_x_Mhunt_1;
-
-
-    VEC3 RGB_subw;
-    VEC3 RGB_subw_prime;
-
-    double p;
-
-    VEC3 RGB_subwc;
-
-    VEC3 RGB_subaw_prime;
-    double A_subw;
-    double Q_subw;
-
-    } cmsCIECAM97s,FAR *LPcmsCIECAM97s;
-
-
-
-// Free model structure
-
-LCMSAPI void LCMSEXPORT cmsCIECAM97sDone(LCMSHANDLE hModel)
-{
-    LPcmsCIECAM97s lpMod = (LPcmsCIECAM97s) (LPSTR) hModel;
-    if (lpMod) _cmsFree(lpMod);
-}
-
-// Partial discounting for adaptation degree computation
-
-static
-double discount(double d, double chan)
-{
-    return (d * chan + 1 - d);
-}
-
-
-// This routine does model exponential nonlinearity on the short wavelenght
-// sensitive channel. On CIECAM97s rev 2 this has been reverted to linear.
-
-static
-void FwAdaptationDegree(LPcmsCIECAM97s lpMod, LPVEC3 RGBc, LPVEC3 RGB)
-{
-
-
-#ifdef USE_CIECAM97s2
-    RGBc->n[0] = RGB->n[0]* discount(lpMod->D, 100.0/lpMod->RGB_subw.n[0]);
-    RGBc->n[1] = RGB->n[1]* discount(lpMod->D, 100.0/lpMod->RGB_subw.n[1]);
-    RGBc->n[2] = RGB->n[2]* discount(lpMod->D, 100.0/lpMod->RGB_subw.n[2]);
-#else
-
-    RGBc->n[0] = RGB->n[0]* discount(lpMod->D, 1.0/lpMod->RGB_subw.n[0]);
-    RGBc->n[1] = RGB->n[1]* discount(lpMod->D, 1.0/lpMod->RGB_subw.n[1]);
-
-    RGBc->n[2] = pow(fabs(RGB->n[2]), lpMod ->p) * discount(lpMod->D, (1.0/pow(lpMod->RGB_subw.n[2], lpMod->p)));
-
-    // If B happens to be negative, Then Bc is also set to be negative
-
-    if (RGB->n[2] < 0)
-           RGBc->n[2] = -RGBc->n[2];
-#endif
-}
-
-
-static
-void RvAdaptationDegree(LPcmsCIECAM97s lpMod, LPVEC3 RGBc, LPVEC3 RGB)
-{
-
-
-#ifdef USE_CIECAM97s2
-    RGBc->n[0] = RGB->n[0]/discount(lpMod->D, 100.0/lpMod->RGB_subw.n[0]);
-    RGBc->n[1] = RGB->n[1]/discount(lpMod->D, 100.0/lpMod->RGB_subw.n[1]);
-    RGBc->n[2] = RGB->n[2]/discount(lpMod->D, 100.0/lpMod->RGB_subw.n[2]);
-#else
-
-    RGBc->n[0] = RGB->n[0]/discount(lpMod->D, 1.0/lpMod->RGB_subw.n[0]);
-    RGBc->n[1] = RGB->n[1]/discount(lpMod->D, 1.0/lpMod->RGB_subw.n[1]);
-    RGBc->n[2] = pow(fabs(RGB->n[2]), 1.0/lpMod->p)/pow(discount(lpMod->D, 1.0/pow(lpMod->RGB_subw.n[2], lpMod->p)), 1.0/lpMod->p);
-    if (RGB->n[2] < 0)
-           RGBc->n[2] = -RGBc->n[2];
-#endif
-}
-
-
-
-static
-void PostAdaptationConeResponses(LPcmsCIECAM97s lpMod, LPVEC3 RGBa_prime, LPVEC3 RGBprime)
-{
-     if (RGBprime->n[0]>=0.0) {
-
-            RGBa_prime->n[0]=((40.0*pow(lpMod -> Fl * RGBprime->n[0]/100.0, 0.73))/(pow(lpMod -> Fl * RGBprime->n[0]/100.0, 0.73)+2))+1;
-     }
-     else
-     {
-            RGBa_prime->n[0]=((-40.0*pow((-lpMod -> Fl * RGBprime->n[0])/100.0, 0.73))/(pow((-lpMod -> Fl * RGBprime->n[0])/100.0, 0.73)+2))+1;
-     }
-
-     if (RGBprime->n[1]>=0.0)
-     {
-            RGBa_prime->n[1]=((40.0*pow(lpMod -> Fl * RGBprime->n[1]/100.0, 0.73))/(pow(lpMod -> Fl * RGBprime->n[1]/100.0, 0.73)+2))+1;
-     }
-     else
-     {
-            RGBa_prime->n[1]=((-40.0*pow((-lpMod -> Fl * RGBprime->n[1])/100.0, 0.73))/(pow((-lpMod -> Fl * RGBprime->n[1])/100.0, 0.73)+2))+1;
-     }
-
-     if (RGBprime->n[2]>=0.0)
-     {
-            RGBa_prime->n[2]=((40.0*pow(lpMod -> Fl * RGBprime->n[2]/100.0, 0.73))/(pow(lpMod -> Fl * RGBprime->n[2]/100.0, 0.73)+2))+1;
-     }
-     else
-     {
-            RGBa_prime->n[2]=((-40.0*pow((-lpMod -> Fl * RGBprime->n[2])/100.0, 0.73))/(pow((-lpMod -> Fl * RGBprime->n[2])/100.0, 0.73)+2))+1;
-     }
-}
-
-
-// Compute hue quadrature, eccentricity factor, e
-
-static
-void ComputeHueQuadrature(double h, double* H, double* e)
-{
-
-
-#define IRED    0
-#define IYELLOW 1
-#define IGREEN  2
-#define IBLUE   3
-
-      double e_tab[] = {0.8, 0.7, 1.0, 1.2};
-      double H_tab[] = {  0, 100, 200, 300};
-      int p1, p2;
-      double e1, e2, h1, h2;
-
-
-       if (h >= 20.14 && h < 90.0) { // Red
-
-                        p1 = IRED;
-                        p2 = IYELLOW;
-       }
-       else
-       if (h >= 90.0 && h < 164.25) { // Yellow
-
-                        p1 = IYELLOW;
-                        p2 = IGREEN;
-       }
-       else
-       if (h >= 164.25 && h < 237.53) { // Green
-
-                        p1 = IGREEN;
-                        p2 = IBLUE;       }
-       else {                         // Blue
-
-                        p1 = IBLUE;
-                        p2 = IRED;
-       }
-
-       e1 = e_tab[p1]; e2 = e_tab[p2];
-       h1 = H_tab[p1]; h2 = H_tab[p2];
-
-
-
-       *e = e1 + ((e2-e1)*(h-h1)/(h2 - h1));
-       *H = h1 + (100. * (h - h1) / e1) / ((h - h1)/e1 + (h2 - h) / e2);
-
-#undef IRED
-#undef IYELLOW
-#undef IGREEN
-#undef IBLUE
-
-}
-
-
-
-
-
-
-LCMSAPI LCMSHANDLE LCMSEXPORT cmsCIECAM97sInit(LPcmsViewingConditions pVC)
-{
-    LPcmsCIECAM97s lpMod;
-    VEC3 tmp;
-
-    if((lpMod = (LPcmsCIECAM97s) _cmsMalloc(sizeof(cmsCIECAM97s))) == NULL) {
-        return (LCMSHANDLE) NULL;
-    }
-
-
-    lpMod->WP.X = pVC->whitePoint.X;
-    lpMod->WP.Y = pVC->whitePoint.Y;
-    lpMod->WP.Z = pVC->whitePoint.Z;
-
-    lpMod->Yb   = pVC->Yb;
-    lpMod->La   = pVC->La;
-
-    lpMod->surround = pVC->surround;
-
-    lpMod->RefWhite.X = 100.0;
-    lpMod->RefWhite.Y = 100.0;
-    lpMod->RefWhite.Z = 100.0;
-
-#ifdef USE_CIECAM97s2
-
-    VEC3init(&lpMod->MlamRigg.v[0],  0.8562, 0.3372, -0.1934);
-    VEC3init(&lpMod->MlamRigg.v[1], -0.8360, 1.8327,  0.0033);
-    VEC3init(&lpMod->MlamRigg.v[2],  0.0357,-0.0469,  1.0112);
-
-    VEC3init(&lpMod->MlamRigg_1.v[0], 0.9874, -0.1768, 0.1894);
-    VEC3init(&lpMod->MlamRigg_1.v[1], 0.4504,  0.4649, 0.0846);
-    VEC3init(&lpMod->MlamRigg_1.v[2],-0.0139,  0.0278, 0.9861);
-
-#else
-    // Bradford transform: Lam-Rigg cone responses
-    VEC3init(&lpMod->MlamRigg.v[0],  0.8951,  0.2664, -0.1614);
-    VEC3init(&lpMod->MlamRigg.v[1], -0.7502,  1.7135,  0.0367);
-    VEC3init(&lpMod->MlamRigg.v[2],  0.0389, -0.0685,  1.0296);
-
-
-    // Inverse of Lam-Rigg
-    VEC3init(&lpMod->MlamRigg_1.v[0],  0.98699, -0.14705,  0.15996);
-    VEC3init(&lpMod->MlamRigg_1.v[1],  0.43231,  0.51836,  0.04929);
-    VEC3init(&lpMod->MlamRigg_1.v[2], -0.00853,  0.04004,  0.96849);
-
-#endif
-
-    // Hunt-Pointer-Estevez cone responses
-    VEC3init(&lpMod->Mhunt.v[0],   0.38971,  0.68898, -0.07868);
-    VEC3init(&lpMod->Mhunt.v[1],  -0.22981,  1.18340,  0.04641);
-    VEC3init(&lpMod->Mhunt.v[2],   0.0,      0.0,      1.0);
-
-    // Inverse of Hunt-Pointer-Estevez
-    VEC3init(&lpMod->Mhunt_1.v[0],     1.91019, -1.11214, 0.20195);
-    VEC3init(&lpMod->Mhunt_1.v[1],     0.37095,  0.62905, 0.0);
-    VEC3init(&lpMod->Mhunt_1.v[2],     0.0,      0.0,     1.0);
-
-
-    if (pVC->D_value == -1.0)
-          lpMod->calculate_D = 1;
-    else
-    if (pVC->D_value == -2.0)
-           lpMod->calculate_D = 2;
-    else {
-        lpMod->calculate_D = 0;
-        lpMod->D = pVC->D_value;
-    }
-
-   // Table I (revised)
-
-   switch (lpMod->surround) {
-
-    case AVG_SURROUND_4:
-       lpMod->F = 1.0;
-       lpMod->c = 0.69;
-       lpMod->Fll = 0.0;    // Not included on Rev 2
-       lpMod->Nc = 1.0;
-       break;
-    case AVG_SURROUND:
-       lpMod->F = 1.0;
-       lpMod->c = 0.69;
-       lpMod->Fll = 1.0;
-       lpMod->Nc = 1.0;
-       break;
-    case DIM_SURROUND:
-       lpMod->F = 0.99;
-       lpMod->c = 0.59;
-       lpMod->Fll = 1.0;
-       lpMod->Nc = 0.95;
-       break;
-    case DARK_SURROUND:
-       lpMod->F = 0.9;
-       lpMod->c = 0.525;
-       lpMod->Fll = 1.0;
-       lpMod->Nc = 0.8;
-       break;
-    case CUTSHEET_SURROUND:
-       lpMod->F = 0.9;
-       lpMod->c = 0.41;
-       lpMod->Fll = 1.0;
-       lpMod->Nc = 0.8;
-       break;
-    default:
-       lpMod->F = 1.0;
-       lpMod->c = 0.69;
-       lpMod->Fll = 1.0;
-       lpMod->Nc = 1.0;
-       break;
-    }
-
-    lpMod->k = 1 / (5 * lpMod->La  + 1);
-    lpMod->Fl = lpMod->La * pow(lpMod->k, 4) + 0.1*pow(1 - pow(lpMod->k, 4), 2.0) * pow(5*lpMod->La, 1.0/3.0);
-
-    if (lpMod->calculate_D > 0) {
-
-       lpMod->D = lpMod->F * (1 - 1 / (1 + 2*pow(lpMod->La, 0.25) + pow(lpMod->La, 2)/300.0));
-       if (lpMod->calculate_D > 1)
-           lpMod->D = (lpMod->D + 1.0) / 2;
-    }
-
-
-    // RGB_subw = [MlamRigg][WP/YWp]
-#ifdef USE_CIECAM97s2
-    MAT3eval(&lpMod -> RGB_subw, &lpMod -> MlamRigg, &lpMod -> WP);
-#else
-    VEC3divK(&tmp, (LPVEC3) &lpMod -> WP, lpMod->WP.Y);
-    MAT3eval(&lpMod -> RGB_subw, &lpMod -> MlamRigg, &tmp);
-#endif
-
-
-
-    MAT3per(&lpMod -> Mhunt_x_MlamRigg_1,   &lpMod -> Mhunt,   &lpMod->MlamRigg_1  );
-    MAT3per(&lpMod -> MlamRigg_x_Mhunt_1,   &lpMod -> MlamRigg, &lpMod -> Mhunt_1  );
-
-    // p is used on forward model
-    lpMod->p = pow(lpMod->RGB_subw.n[2], 0.0834);
-
-    FwAdaptationDegree(lpMod, &lpMod->RGB_subwc, &lpMod->RGB_subw);
-
-#if USE_CIECAM97s2
-    MAT3eval(&lpMod->RGB_subw_prime, &lpMod->Mhunt_x_MlamRigg_1, &lpMod -> RGB_subwc);
-#else
-    VEC3perK(&tmp, &lpMod -> RGB_subwc, lpMod->WP.Y);
-    MAT3eval(&lpMod->RGB_subw_prime, &lpMod->Mhunt_x_MlamRigg_1, &tmp);
-#endif
-
-    lpMod->n = lpMod-> Yb / lpMod-> WP.Y;
-
-    lpMod->z = 1 + lpMod->Fll * sqrt(lpMod->n);
-    lpMod->Nbb = lpMod->Ncb = 0.725 / pow(lpMod->n, 0.2);
-
-    PostAdaptationConeResponses(lpMod, &lpMod->RGB_subaw_prime, &lpMod->RGB_subw_prime);
-
-    lpMod->A_subw=lpMod->Nbb*(2.0*lpMod->RGB_subaw_prime.n[0]+lpMod->RGB_subaw_prime.n[1]+lpMod->RGB_subaw_prime.n[2]/20.0-NOISE_CONSTANT);
-
-    return (LCMSHANDLE) lpMod;
-}
-
-
-
-
-//
-// The forward model: XYZ -> JCh
-//
-
-LCMSAPI void LCMSEXPORT cmsCIECAM97sForward(LCMSHANDLE hModel, LPcmsCIEXYZ inPtr, LPcmsJCh outPtr)
-{
-
-        LPcmsCIECAM97s lpMod = (LPcmsCIECAM97s) (LPSTR) hModel;
-        double a, b, h, s, H1val, es, A;
-        VEC3 In, RGB, RGBc, RGBprime, RGBa_prime;
-
-        if (inPtr -> Y <= 0.0) {
-
-      outPtr -> J = outPtr -> C = outPtr -> h = 0.0;
-          return;
-        }
-
-       // An initial chromatic adaptation transform is used to go from the source
-       // viewing conditions to corresponding colours under the equal-energy-illuminant
-       // reference viewing conditions. This is handled differently on rev 2
-
-       VEC3init(&In, inPtr -> X, inPtr -> Y, inPtr -> Z);    // 2.1
-
-#ifdef USE_CIECAM97s2
-       // Since the chromatic adaptation transform has been linearized, it
-       // is no longer required to divide the stimulus tristimulus values
-       // by their own Y tristimulus value prior to the chromatic adaptation.
-#else
-       VEC3divK(&In, &In, inPtr -> Y);
-#endif
-
-       MAT3eval(&RGB, &lpMod -> MlamRigg, &In);              // 2.2
-
-       FwAdaptationDegree(lpMod, &RGBc, &RGB);
-
-       // The post-adaptation signals for both the sample and the white are then
-       // transformed from the sharpened cone responses to the Hunt-Pointer-Estevez
-       // cone responses.
-#ifdef USE_CIECAM97s2
-#else
-       VEC3perK(&RGBc, &RGBc, inPtr->Y);
-#endif
-
-       MAT3eval(&RGBprime, &lpMod->Mhunt_x_MlamRigg_1, &RGBc);
-
-       // The post-adaptation cone responses (for both the stimulus and the white)
-       // are then calculated.
-
-       PostAdaptationConeResponses(lpMod, &RGBa_prime, &RGBprime);
-
-       // Preliminary red-green and yellow-blue opponent dimensions are calculated
-
-       a = RGBa_prime.n[0] - (12.0 * RGBa_prime.n[1] / 11.0) + RGBa_prime.n[2]/11.0;
-       b = (RGBa_prime.n[0] + RGBa_prime.n[1] - 2.0 * RGBa_prime.n[2]) / 9.0;
-
-
-       // The CIECAM97s hue angle, h, is then calculated
-       h = (180.0/M_PI)*(atan2(b, a));
-
-
-       while (h < 0)
-              h += 360.0;
-
-       outPtr->h = h;
-
-       // hue quadrature and eccentricity factors, e, are calculated
-
-       ComputeHueQuadrature(h, &H1val, &es);
-
-       // ComputeHueQuadrature(h, &H1val, &h1, &e1, &h2, &e2, &es);
-
-
-      // The achromatic response A
-      A = lpMod->Nbb * (2.0 * RGBa_prime.n[0] + RGBa_prime.n[1] + RGBa_prime.n[2]/20.0 - NOISE_CONSTANT);
-
-      // CIECAM97s Lightness J
-      outPtr -> J = 100.0 * pow(A / lpMod->A_subw, lpMod->c * lpMod->z);
-
-      // CIECAM97s saturation s
-      s =  (50 * hypot (a, b) * 100 * es * (10.0/13.0) * lpMod-> Nc * lpMod->Ncb) / (RGBa_prime.n[0] + RGBa_prime.n[1] + 1.05 * RGBa_prime.n[2]);
-
-      // CIECAM97s Chroma C
-
-#ifdef USE_CIECAM97s2
-      // Eq. 26 has been modified to allow accurate prediction of the Munsell chroma scales.
-      outPtr->C = 0.7487 * pow(s, 0.973) * pow(outPtr->J/100.0, 0.945 * lpMod->n) * (1.64 - pow(0.29, lpMod->n));
-
-#else
-      outPtr->C = 2.44 * pow(s, 0.69) * pow(outPtr->J/100.0, 0.67 * lpMod->n) * (1.64 - pow(0.29, lpMod->n));
-#endif
-}
-
-
-//
-// The reverse model JCh -> XYZ
-//
-
-
-LCMSAPI void LCMSEXPORT cmsCIECAM97sReverse(LCMSHANDLE hModel, LPcmsJCh inPtr, LPcmsCIEXYZ outPtr)
-{
-    LPcmsCIECAM97s lpMod = (LPcmsCIECAM97s) (LPSTR) hModel;
-    double J, C, h, A, H1val, es, s, a, b;
-    double tan_h, sec_h;
-    double R_suba_prime, G_suba_prime, B_suba_prime;
-    double R_prime, G_prime, B_prime;
-    double Y_subc, Y_prime, B_term;
-    VEC3 tmp;
-    VEC3 RGB_prime, RGB_subc_Y;
-    VEC3 Y_over_Y_subc_RGB;
-    VEC3 XYZ_primeprime_over_Y_subc;
-#ifdef USE_CIECAM92s2
-    VEC3 RGBY;
-    VEC3 Out;
-#endif
-
-    J = inPtr->J;
-    h = inPtr->h;
-    C = inPtr->C;
-
-    if (J <= 0) {
-
-        outPtr->X =  0.0;
-        outPtr->Y =  0.0;
-        outPtr->Z =  0.0;
-        return;
-    }
-
-
-
-    // (2) From J Obtain A
-
-    A =  pow(J/100.0, 1/(lpMod->c * lpMod->z)) * lpMod->A_subw;
-
-
-    // (3), (4), (5) Using H Determine h1, h2, e1, e2
-    // e1 and h1 are the values  of e and h for the unique hue having the
-    // nearest lower valur of h and e2 and h2 are the values of e and h for
-    // the unique hue having the nearest higher value of h.
-
-
-    ComputeHueQuadrature(h, &H1val, &es);
-
-    // (7) Calculate s
-
-    s = pow(C / (2.44 * pow(J/100.0, 0.67*lpMod->n) * (1.64 - pow(0.29, lpMod->n))) , (1./0.69));
-
-
-    // (8) Calculate a and b.
-    // NOTE: sqrt(1 + tan^2) == sec(h)
-
-    tan_h = tan ((M_PI/180.)*(h));
-    sec_h = sqrt(1 + tan_h * tan_h);
-
-    if ((h > 90) && (h < 270))
-            sec_h = -sec_h;
-
-    a = s * ( A/lpMod->Nbb + NOISE_CONSTANT) / ( sec_h * 50000.0 * es * lpMod->Nc * lpMod->Ncb/ 13.0 +
-           s * (11.0 / 23.0 + (108.0/23.0) * tan_h));
-
-    b = a * tan_h;
-
-    //(9) Calculate R'a G'a and B'a
-
-    R_suba_prime = (20.0/61.0) * (A/lpMod->Nbb + NOISE_CONSTANT) + (41.0/61.0) * (11.0/23.0) * a + (288.0/61.0) / 23.0 * b;
-    G_suba_prime = (20.0/61.0) * (A/lpMod->Nbb + NOISE_CONSTANT) - (81.0/61.0) * (11.0/23.0) * a - (261.0/61.0) / 23.0 * b;
-    B_suba_prime = (20.0/61.0) * (A/lpMod->Nbb + NOISE_CONSTANT) - (20.0/61.0) * (11.0/23.0) * a - (20.0/61.0) * (315.0/23.0) * b;
-
-    // (10) Calculate R', G' and B'
-
-    if ((R_suba_prime - 1) < 0) {
-
-         R_prime = -100.0 * pow((2.0 - 2.0 * R_suba_prime) /
-                            (39.0 + R_suba_prime), 1.0/0.73);
-    }
-    else
-    {
-         R_prime = 100.0 * pow((2.0 * R_suba_prime - 2.0) /
-                            (41.0 - R_suba_prime), 1.0/0.73);
-    }
-
-    if ((G_suba_prime - 1) < 0)
-    {
-         G_prime = -100.0 * pow((2.0 - 2.0 * G_suba_prime) /
-                            (39.0 + G_suba_prime), 1.0/0.73);
-    }
-    else
-    {
-         G_prime = 100.0 * pow((2.0 * G_suba_prime - 2.0) /
-                            (41.0 - G_suba_prime), 1.0/0.73);
-    }
-
-    if ((B_suba_prime - 1) < 0)
-    {
-         B_prime = -100.0 * pow((2.0 - 2.0 * B_suba_prime) /
-                            (39.0 + B_suba_prime), 1.0/0.73);
-    }
-    else
-    {
-         B_prime = 100.0 * pow((2.0 * B_suba_prime - 2.0) /
-                            (41.0 - B_suba_prime), 1.0/0.73);
-    }
-
-
-    // (11) Calculate RcY, GcY and BcY
-
-    VEC3init(&RGB_prime, R_prime, G_prime, B_prime);
-    VEC3divK(&tmp, &RGB_prime, lpMod -> Fl);
-
-    MAT3eval(&RGB_subc_Y, &lpMod->MlamRigg_x_Mhunt_1, &tmp);
-
-
-
-
-#ifdef USE_CIECAM97s2
-
-       // (12)
-
-
-           RvAdaptationDegree(lpMod, &RGBY, &RGB_subc_Y);
-           MAT3eval(&Out, &lpMod->MlamRigg_1, &RGBY);
-
-           outPtr -> X = Out.n[0];
-           outPtr -> Y = Out.n[1];
-           outPtr -> Z = Out.n[2];
-
-#else
-
-           // (12) Calculate Yc
-
-       Y_subc = 0.43231*RGB_subc_Y.n[0]+0.51836*RGB_subc_Y.n[1]+0.04929*RGB_subc_Y.n[2];
-
-           // (13) Calculate (Y/Yc)R, (Y/Yc)G and (Y/Yc)B
-
-           VEC3divK(&RGB_subc_Y, &RGB_subc_Y, Y_subc);
-           RvAdaptationDegree(lpMod, &Y_over_Y_subc_RGB, &RGB_subc_Y);
-
-           // (14) Calculate Y'
-       Y_prime = 0.43231*(Y_over_Y_subc_RGB.n[0]*Y_subc) + 0.51836*(Y_over_Y_subc_RGB.n[1]*Y_subc) + 0.04929 * (Y_over_Y_subc_RGB.n[2]*Y_subc);
-
-           if (Y_prime < 0 || Y_subc < 0)
-           {
-                // Discard to near black point
-
-                outPtr -> X = 0;
-                outPtr -> Y = 0;
-                outPtr -> Z = 0;
-                return;
-           }
-
-       B_term = pow(Y_prime / Y_subc, (1.0 / lpMod->p) - 1);
-
-          // (15) Calculate X'', Y'' and Z''
-           Y_over_Y_subc_RGB.n[2] /= B_term;
-           MAT3eval(&XYZ_primeprime_over_Y_subc, &lpMod->MlamRigg_1, &Y_over_Y_subc_RGB);
-
-           outPtr->X =  XYZ_primeprime_over_Y_subc.n[0] * Y_subc;
-           outPtr->Y =  XYZ_primeprime_over_Y_subc.n[1] * Y_subc;
-           outPtr->Z =  XYZ_primeprime_over_Y_subc.n[2] * Y_subc;
-#endif
-
-}
--- a/src/share/native/sun/java2d/cmm/lcms/cmscgats.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmscgats.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -49,104 +50,30 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-// IT8.7 / CGATS.17-200x handling
-
-#include "lcms.h"
-
-
-LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8Alloc(void);
-LCMSAPI void            LCMSEXPORT cmsIT8Free(LCMSHANDLE IT8);
-
-// Tables
-
-LCMSAPI int             LCMSEXPORT cmsIT8TableCount(LCMSHANDLE IT8);
-LCMSAPI int             LCMSEXPORT cmsIT8SetTable(LCMSHANDLE IT8, int nTable);
-
-// Persistence
-LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8LoadFromFile(const char* cFileName);
-LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8LoadFromMem(void *Ptr, size_t len);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE IT8, const char* cFileName);
-
-// Properties
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetSheetType(LCMSHANDLE hIT8);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* cComment);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* cProp, const char *Str);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char* cSubProp, const char *Val);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer);
-
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* cProp);
-LCMSAPI double          LCMSEXPORT cmsIT8GetPropertyDbl(LCMSHANDLE hIT8, const char* cProp);
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char *cSubProp);
-LCMSAPI int             LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE IT8, const char ***PropertyNames);
-LCMSAPI int             LCMSEXPORT cmsIT8EnumPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char*** SubpropertyNames);
-
-// Datasets
-
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetPatchName(LCMSHANDLE hIT8, int nPatch, char* buffer);
-
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetDataRowCol(LCMSHANDLE IT8, int row, int col);
-LCMSAPI double          LCMSEXPORT cmsIT8GetDataRowColDbl(LCMSHANDLE IT8, int col, int row);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col,
-                                                const char* Val);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col,
-                                                double Val);
-
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetData(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
-
-
-LCMSAPI double          LCMSEXPORT cmsIT8GetDataDbl(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetData(LCMSHANDLE IT8, const char* cPatch,
-                                                const char* cSample,
-                                                const char *Val);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
-                                                const char* cSample,
-                                                double Val);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE IT8, int n, const char *Sample);
-LCMSAPI int             LCMSEXPORT cmsIT8EnumDataFormat(LCMSHANDLE IT8, char ***SampleNames);
-
-LCMSAPI void            LCMSEXPORT cmsIT8DefineDblFormat(LCMSHANDLE IT8, const char* Formatter);
-
-LCMSAPI int             LCMSEXPORT cmsIT8SetTableByLabel(LCMSHANDLE hIT8, const char* cSet,
-                                                                          const char* cField,
-                                                                          const char* ExpectedType);
-
-// ------------------------------------------------------------- Implementation
-
-
-#define SIZEOFLONGMINUS1    (sizeof(long)-1)
-#define ALIGNLONG(x) (((x)+SIZEOFLONGMINUS1) & ~(SIZEOFLONGMINUS1))
-
-// #define STRICT_CGATS  1
-
-#define MAXID       128     // Max lenght of identifier
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
+
+
+// IT8.7 / CGATS.17-200x handling -----------------------------------------------------------------------------
+
+
+#define MAXID        128     // Max lenght of identifier
 #define MAXSTR      1024     // Max lenght of string
-#define MAXTABLES   255     // Max Number of tables in a single stream
-#define MAXINCLUDE   20     // Max number of nested includes
+#define MAXTABLES    255     // Max Number of tables in a single stream
+#define MAXINCLUDE    20     // Max number of nested includes
 
 #define DEFAULT_DBL_FORMAT  "%.10g" // Double formatting
 
-#include <ctype.h>
-#include <limits.h>
-
-#ifndef NON_WINDOWS
-#include <io.h>
-#define DIR_CHAR    '\\'
+#ifdef CMS_IS_WINDOWS_
+#    include <io.h>
+#    define DIR_CHAR    '\\'
 #else
-#define DIR_CHAR    '/'
+#    define DIR_CHAR    '/'
 #endif
 
 // Symbols
-
 typedef enum {
 
         SNONE,
@@ -173,8 +100,8 @@
 
 
 // How to write the value
-
 typedef enum {
+
         WRITE_UNCOOKED,
         WRITE_STRINGIFY,
         WRITE_HEXADECIMAL,
@@ -184,7 +111,6 @@
     } WRITEMODE;
 
 // Linked list of variable names
-
 typedef struct _KeyVal {
 
         struct _KeyVal*  Next;
@@ -194,108 +120,101 @@
         char*            Value;         // Points to value
         WRITEMODE        WriteAs;       // How to write the value
 
-   } KEYVALUE, *LPKEYVALUE;
+   } KEYVALUE;
 
 
 // Linked list of memory chunks (Memory sink)
-
 typedef struct _OwnedMem {
 
         struct _OwnedMem* Next;
         void *            Ptr;          // Point to value
 
-   } OWNEDMEM, *LPOWNEDMEM;
+   } OWNEDMEM;
 
 // Suballocator
-
 typedef struct _SubAllocator {
 
-         LPBYTE Block;
-         size_t BlockSize;
-         size_t Used;
-
-    } SUBALLOCATOR, *LPSUBALLOCATOR;
+         cmsUInt8Number* Block;
+         cmsUInt32Number BlockSize;
+         cmsUInt32Number Used;
+
+    } SUBALLOCATOR;
 
 // Table. Each individual table can hold properties and rows & cols
-
 typedef struct _Table {
 
         int            nSamples, nPatches;    // Cols, Rows
         int            SampleID;              // Pos of ID
 
-        LPKEYVALUE     HeaderList;            // The properties
+        KEYVALUE*      HeaderList;            // The properties
 
         char**         DataFormat;            // The binary stream descriptor
         char**         Data;                  // The binary stream
 
-    } TABLE, *LPTABLE;
+    } TABLE;
 
 // File stream being parsed
-
 typedef struct _FileContext {
-        char           FileName[MAX_PATH];    // File name if being readed from file
-        FILE*          Stream;                // File stream or NULL if holded in memory
-    } FILECTX, *LPFILECTX;
-
-// This struct hold all information about an openened
-// IT8 handler. Only one dataset is allowed.
-
+        char           FileName[cmsMAX_PATH];    // File name if being readed from file
+        FILE*          Stream;                   // File stream or NULL if holded in memory
+    } FILECTX;
+
+// This struct hold all information about an open IT8 handler.
 typedef struct {
 
-        char SheetType[MAXSTR];
-
-        int  TablesCount;                     // How many tables in this stream
-        int  nTable;                          // The actual table
+        char SheetType[MAXSTR];               // The first row of the IT8 (the type)
+
+        cmsUInt32Number  TablesCount;                     // How many tables in this stream
+        cmsUInt32Number  nTable;                          // The actual table
 
         TABLE Tab[MAXTABLES];
 
         // Memory management
-
-        LPOWNEDMEM     MemorySink;            // The storage backend
+        OWNEDMEM*      MemorySink;            // The storage backend
         SUBALLOCATOR   Allocator;             // String suballocator -- just to keep it fast
 
         // Parser state machine
-
         SYMBOL         sy;                    // Current symbol
         int            ch;                    // Current character
 
         int            inum;                  // integer value
-        double         dnum;                  // real value
+        cmsFloat64Number         dnum;                  // real value
         char           id[MAXID];             // identifier
         char           str[MAXSTR];           // string
 
         // Allowed keywords & datasets. They have visibility on whole stream
-
-        LPKEYVALUE     ValidKeywords;
-        LPKEYVALUE     ValidSampleID;
+        KEYVALUE*     ValidKeywords;
+        KEYVALUE*     ValidSampleID;
 
         char*          Source;                // Points to loc. being parsed
         int            lineno;                // line counter for error reporting
 
-        LPFILECTX      FileStack[MAXINCLUDE]; // Stack of files being parsed
+        FILECTX*       FileStack[MAXINCLUDE]; // Stack of files being parsed
         int            IncludeSP;             // Include Stack Pointer
 
         char*          MemoryBlock;           // The stream if holded in memory
 
-        char           DoubleFormatter[MAXID];   // Printf-like 'double' formatter
-
-   } IT8, *LPIT8;
-
-
-
+        char           DoubleFormatter[MAXID];// Printf-like 'cmsFloat64Number' formatter
+
+        cmsContext    ContextID;              // The threading context
+
+   } cmsIT8;
+
+
+// The stream for save operations
 typedef struct {
 
         FILE* stream;   // For save-to-file behaviour
 
-        LPBYTE Base;
-        LPBYTE Ptr;     // For save-to-mem behaviour
-        size_t Used;
-        size_t Max;
-
-    } SAVESTREAM, FAR* LPSAVESTREAM;
-
-
-// ------------------------------------------------------ IT8 parsing routines
+        cmsUInt8Number* Base;
+        cmsUInt8Number* Ptr;        // For save-to-mem behaviour
+        cmsUInt32Number Used;
+        cmsUInt32Number Max;
+
+    } SAVESTREAM;
+
+
+// ------------------------------------------------------ cmsIT8 parsing routines
 
 
 // A keyword
@@ -309,14 +228,15 @@
 // The keyword->symbol translation table. Sorting is required.
 static const KEYWORD TabKeys[] = {
 
-        {"$INCLUDE",            SINCLUDE},
-        {".INCLUDE",            SINCLUDE},
-        {"BEGIN_DATA",          SBEGIN_DATA },
-        {"BEGIN_DATA_FORMAT",   SBEGIN_DATA_FORMAT },
+        {"$INCLUDE",               SINCLUDE},   // This is an extension!
+        {".INCLUDE",               SINCLUDE},   // This is an extension!
+
+        {"BEGIN_DATA",             SBEGIN_DATA },
+        {"BEGIN_DATA_FORMAT",      SBEGIN_DATA_FORMAT },
         {"DATA_FORMAT_IDENTIFIER", SDATA_FORMAT_ID},
-        {"END_DATA",            SEND_DATA},
-        {"END_DATA_FORMAT",     SEND_DATA_FORMAT},
-        {"KEYWORD",             SKEYWORD}
+        {"END_DATA",               SEND_DATA},
+        {"END_DATA_FORMAT",        SEND_DATA_FORMAT},
+        {"KEYWORD",                SKEYWORD}
         };
 
 #define NUMKEYS (sizeof(TabKeys)/sizeof(KEYWORD))
@@ -325,8 +245,8 @@
 
 // A property
 typedef struct {
-        const char *id;
-        WRITEMODE as;
+        const char *id;    // The identifier
+        WRITEMODE as;      // How is supposed to be written
     } PROPERTY;
 
 static PROPERTY PredefinedProperties[] = {
@@ -366,7 +286,8 @@
 
         {"CHISQ_DOF",        WRITE_STRINGIFY},   // Degrees of freedom associated with the Chi squared statistic
 
-//    new in recent specs:
+       // below properties are new in recent specs:
+
         {"MEASUREMENT_GEOMETRY", WRITE_STRINGIFY}, // The type of measurement, either reflection or transmission, should be indicated
                                // along with details of the geometry and the aperture size and shape. For example,
                                // for transmission measurements it is important to identify 0/diffuse, diffuse/0,
@@ -438,9 +359,9 @@
         "LAB_B",          // b* component of Lab data
         "LAB_C",          // C*ab component of Lab data
         "LAB_H",          // hab component of Lab data
-        "LAB_DE",         //  CIE dE
-        "LAB_DE_94",      //  CIE dE using CIE 94
-        "LAB_DE_CMC",     //  dE using CMC
+        "LAB_DE",         // CIE dE
+        "LAB_DE_94",      // CIE dE using CIE 94
+        "LAB_DE_CMC",     // dE using CMC
         "LAB_DE_2000",    // CIE dE using CIE DE 2000
         "MEAN_DE",        // Mean Delta E (LAB_DE) of samples compared to batch average
                           // (Used for data files for ANSI IT8.7/1 and IT8.7/2 targets)
@@ -458,84 +379,94 @@
 #define NUMPREDEFINEDSAMPLEID (sizeof(PredefinedSampleID)/sizeof(char *))
 
 //Forward declaration of some internal functions
-static
-void* AllocChunk(LPIT8 it8, size_t size);
+static void* AllocChunk(cmsIT8* it8, cmsUInt32Number size);
 
 // Checks if c is a separator
 static
-LCMSBOOL isseparator(int c)
+cmsBool isseparator(int c)
 {
         return (c == ' ') || (c == '\t') || (c == '\r');
 }
 
 // Checks whatever if c is a valid identifier char
 static
-LCMSBOOL ismiddle(int c)
+cmsBool ismiddle(int c)
 {
    return (!isseparator(c) && (c != '#') && (c !='\"') && (c != '\'') && (c > 32) && (c < 127));
 }
 
 // Checks whatsever if c is a valid identifier middle char.
 static
-LCMSBOOL isidchar(int c)
+cmsBool isidchar(int c)
 {
    return isalnum(c) || ismiddle(c);
 }
 
 // Checks whatsever if c is a valid identifier first char.
 static
-LCMSBOOL isfirstidchar(int c)
+cmsBool isfirstidchar(int c)
 {
      return !isdigit(c) && ismiddle(c);
 }
 
-// checks whether the supplied path looks like an absolute path
-// NOTE: this function doesn't checks if the path exists or even if it's legal
+// Guess whether the supplied path looks like an absolute path
 static
-LCMSBOOL isabsolutepath(const char *path)
+cmsBool isabsolutepath(const char *path)
 {
+    char ThreeChars[4];
+
     if(path == NULL)
         return FALSE;
-
-    if(path[0] == DIR_CHAR)
+    if (path[0] == 0)
+        return FALSE;
+
+    strncpy(ThreeChars, path, 3);
+    ThreeChars[3] = 0;
+
+    if(ThreeChars[0] == DIR_CHAR)
         return TRUE;
 
-#ifndef NON_WINDOWS
-    if(isalpha(path[0]) && path[1] == ':')
+#ifdef  CMS_IS_WINDOWS_
+    if (isalpha((int) ThreeChars[0]) && ThreeChars[1] == ':')
         return TRUE;
 #endif
     return FALSE;
 }
 
 // Makes a file path based on a given reference path
-// NOTE: buffer is assumed to point to at least MAX_PATH bytes
-// NOTE: both relPath and basePath are assumed to be no more than MAX_PATH characters long (including the null terminator!)
 // NOTE: this function doesn't check if the path exists or even if it's legal
 static
-LCMSBOOL _cmsMakePath(const char *relPath, const char *basePath, char *buffer)
+cmsBool BuildAbsolutePath(const char *relPath, const char *basePath, char *buffer, cmsUInt32Number MaxLen)
 {
-    if (!isabsolutepath(relPath)) {
-
-        char *tail;
-
-        strncpy(buffer, basePath, MAX_PATH-1);
-        tail = strrchr(buffer, DIR_CHAR);
-        if (tail != NULL) {
-
-            size_t len = tail - buffer;
-            strncpy(tail + 1, relPath, MAX_PATH - len -1);
-            //  TODO: if combined path is longer than MAX_PATH, this should return FALSE!
-            return TRUE;
-        }
+    char *tail;
+    cmsUInt32Number len;
+
+    // Already absolute?
+    if (isabsolutepath(relPath)) {
+
+        strncpy(buffer, relPath, MaxLen);
+        buffer[MaxLen-1] = 0;
+        return TRUE;
     }
-    strncpy(buffer, relPath, MAX_PATH - 1);
-        buffer[MAX_PATH-1] = 0;
+
+    // No, search for last
+    strncpy(buffer, basePath, MaxLen);
+    buffer[MaxLen-1] = 0;
+
+    tail = strrchr(buffer, DIR_CHAR);
+    if (tail == NULL) return FALSE;    // Is not absolute and has no separators??
+
+    len = (cmsUInt32Number) (tail - buffer);
+    if (len >= MaxLen) return FALSE;
+
+    // No need to assure zero terminator over here
+    strncpy(tail + 1, relPath, MaxLen - len);
+
     return TRUE;
 }
 
 
 // Make sure no exploit is being even tried
-
 static
 const char* NoMeta(const char* str)
 {
@@ -545,40 +476,37 @@
     return str;
 }
 
-
 // Syntax error
 static
-LCMSBOOL SynError(LPIT8 it8, const char *Txt, ...)
+cmsBool SynError(cmsIT8* it8, const char *Txt, ...)
 {
-        char Buffer[256], ErrMsg[1024];
-        va_list args;
-
-        va_start(args, Txt);
-        vsnprintf(Buffer, 255, Txt, args);
-        Buffer[255] = 0;
-        va_end(args);
-
-        snprintf(ErrMsg, 1023, "%s: Line %d, %s", it8->FileStack[it8 ->IncludeSP]->FileName, it8->lineno, Buffer);
-        ErrMsg[1023] = 0;
-        it8->sy = SSYNERROR;
-        cmsSignalError(LCMS_ERRC_ABORTED, "%s", ErrMsg);
-        return FALSE;
+    char Buffer[256], ErrMsg[1024];
+    va_list args;
+
+    va_start(args, Txt);
+    vsnprintf(Buffer, 255, Txt, args);
+    Buffer[255] = 0;
+    va_end(args);
+
+    snprintf(ErrMsg, 1023, "%s: Line %d, %s", it8->FileStack[it8 ->IncludeSP]->FileName, it8->lineno, Buffer);
+    ErrMsg[1023] = 0;
+    it8->sy = SSYNERROR;
+    cmsSignalError(it8 ->ContextID, cmsERROR_CORRUPTION_DETECTED, "%s", ErrMsg);
+    return FALSE;
 }
 
 // Check if current symbol is same as specified. issue an error else.
 static
-LCMSBOOL Check(LPIT8 it8, SYMBOL sy, const char* Err)
+cmsBool Check(cmsIT8* it8, SYMBOL sy, const char* Err)
 {
         if (it8 -> sy != sy)
                 return SynError(it8, NoMeta(Err));
         return TRUE;
 }
 
-
-
 // Read Next character from stream
 static
-void NextCh(LPIT8 it8)
+void NextCh(cmsIT8* it8)
 {
     if (it8 -> FileStack[it8 ->IncludeSP]->Stream) {
 
@@ -594,9 +522,6 @@
             } else
                 it8 ->ch = 0;   // EOF
         }
-
-
-
     }
     else {
         it8->ch = *it8->Source;
@@ -609,100 +534,98 @@
 static
 SYMBOL BinSrchKey(const char *id)
 {
-        int l = 1;
-        int r = NUMKEYS;
-        int x, res;
-
-        while (r >= l)
-        {
-                x = (l+r)/2;
-                res = stricmp(id, TabKeys[x-1].id);
-                if (res == 0) return TabKeys[x-1].sy;
-                if (res < 0) r = x - 1;
-                else l = x + 1;
-        }
-
-        return SNONE;
+    int l = 1;
+    int r = NUMKEYS;
+    int x, res;
+
+    while (r >= l)
+    {
+        x = (l+r)/2;
+        res = cmsstrcasecmp(id, TabKeys[x-1].id);
+        if (res == 0) return TabKeys[x-1].sy;
+        if (res < 0) r = x - 1;
+        else l = x + 1;
+    }
+
+    return SNONE;
 }
 
 
 // 10 ^n
 static
-double xpow10(int n)
+cmsFloat64Number xpow10(int n)
 {
-    return pow(10, (double) n);
+    return pow(10, (cmsFloat64Number) n);
 }
 
 
 //  Reads a Real number, tries to follow from integer number
 static
-void ReadReal(LPIT8 it8, int inum)
+void ReadReal(cmsIT8* it8, int inum)
 {
-        it8->dnum = (double) inum;
-
-        while (isdigit(it8->ch)) {
+    it8->dnum = (cmsFloat64Number) inum;
+
+    while (isdigit(it8->ch)) {
 
         it8->dnum = it8->dnum * 10.0 + (it8->ch - '0');
         NextCh(it8);
-        }
-
-        if (it8->ch == '.') {        // Decimal point
-
-                double frac = 0.0;      // fraction
-                int prec = 0;           // precission
-
-                NextCh(it8);               // Eats dec. point
-
-                while (isdigit(it8->ch)) {
-
-                        frac = frac * 10.0 + (it8->ch - '0');
-                        prec++;
-                        NextCh(it8);
-                }
-
-                it8->dnum = it8->dnum + (frac / xpow10(prec));
+    }
+
+    if (it8->ch == '.') {        // Decimal point
+
+        cmsFloat64Number frac = 0.0;      // fraction
+        int prec = 0;           // precision
+
+        NextCh(it8);               // Eats dec. point
+
+        while (isdigit(it8->ch)) {
+
+            frac = frac * 10.0 + (it8->ch - '0');
+            prec++;
+            NextCh(it8);
         }
 
-        // Exponent, example 34.00E+20
-        if (toupper(it8->ch) == 'E') {
-
-                int e;
-                int sgn;
-
-                NextCh(it8); sgn = 1;
-
-                if (it8->ch == '-') {
-
-                        sgn = -1; NextCh(it8);
-                }
-                else
-                if (it8->ch == '+') {
-
-                        sgn = +1;
-                        NextCh(it8);
-                }
-
-
-                e = 0;
-                while (isdigit(it8->ch)) {
-
-                        if ((double) e * 10L < INT_MAX)
-                            e = e * 10 + (it8->ch - '0');
-
-                        NextCh(it8);
-                }
-
-                e = sgn*e;
-
-                it8 -> dnum = it8 -> dnum * xpow10(e);
+        it8->dnum = it8->dnum + (frac / xpow10(prec));
+    }
+
+    // Exponent, example 34.00E+20
+    if (toupper(it8->ch) == 'E') {
+
+        int e;
+        int sgn;
+
+        NextCh(it8); sgn = 1;
+
+        if (it8->ch == '-') {
+
+            sgn = -1; NextCh(it8);
         }
+        else
+            if (it8->ch == '+') {
+
+                sgn = +1;
+                NextCh(it8);
+            }
+
+            e = 0;
+            while (isdigit(it8->ch)) {
+
+                if ((cmsFloat64Number) e * 10L < INT_MAX)
+                    e = e * 10 + (it8->ch - '0');
+
+                NextCh(it8);
+            }
+
+            e = sgn*e;
+            it8 -> dnum = it8 -> dnum * xpow10(e);
+    }
 }
 
 
 
 // Reads next symbol
 static
-void InSymbol(LPIT8 it8)
+void InSymbol(cmsIT8* it8)
 {
     register char *idptr;
     register int k;
@@ -716,7 +639,6 @@
 
         if (isfirstidchar(it8->ch)) {          // Identifier
 
-
             k = 0;
             idptr = it8->id;
 
@@ -845,7 +767,6 @@
                     } while (isidchar(it8->ch));
 
                     *idptr = '\0';
-
                     it8->sy = SIDENT;
                 }
                 return;
@@ -860,7 +781,6 @@
             break;
 
         // Eof stream markers
-
         case 0:
         case -1:
             it8->sy = SEOF;
@@ -868,7 +788,6 @@
 
 
         // Next line
-
         case '\n':
             NextCh(it8);
             it8->sy = SEOLN;
@@ -876,7 +795,6 @@
             break;
 
         // Comment
-
         case '#':
             NextCh(it8);
             while (it8->ch && it8->ch != '\n')
@@ -885,8 +803,7 @@
             it8->sy = SCOMMENT;
             break;
 
-            // String.
-
+        // String.
         case '\'':
         case '\"':
             idptr = it8->str;
@@ -921,10 +838,10 @@
 
     if (it8 -> sy == SINCLUDE) {
 
-                LPFILECTX FileNest;
-
-                if(it8 -> IncludeSP >= (MAXINCLUDE-1))
-                {
+                FILECTX* FileNest;
+
+                if(it8 -> IncludeSP >= (MAXINCLUDE-1)) {
+
                     SynError(it8, "Too many recursion levels");
                     return;
                 }
@@ -933,15 +850,16 @@
                 if (!Check(it8, SSTRING, "Filename expected")) return;
 
                 FileNest = it8 -> FileStack[it8 -> IncludeSP + 1];
-                if(FileNest == NULL)
-                {
-                    FileNest = it8 ->FileStack[it8 -> IncludeSP + 1] = (LPFILECTX)AllocChunk(it8, sizeof(FILECTX));
+                if(FileNest == NULL) {
+
+                    FileNest = it8 ->FileStack[it8 -> IncludeSP + 1] = (FILECTX*)AllocChunk(it8, sizeof(FILECTX));
                     //if(FileNest == NULL)
-                        //  TODO: how to manage out-of-memory conditions?
+                    //  TODO: how to manage out-of-memory conditions?
                 }
 
-                if(_cmsMakePath(it8->str, it8->FileStack[it8->IncludeSP]->FileName, FileNest->FileName) == FALSE)
-                {
+                if (BuildAbsolutePath(it8->str,
+                                      it8->FileStack[it8->IncludeSP]->FileName,
+                                      FileNest->FileName, cmsMAX_PATH-1) == FALSE) {
                     SynError(it8, "File path too long");
                     return;
                 }
@@ -962,7 +880,7 @@
 
 // Checks end of line separator
 static
-LCMSBOOL CheckEOLN(LPIT8 it8)
+cmsBool CheckEOLN(cmsIT8* it8)
 {
         if (!Check(it8, SEOLN, "Expected separator")) return FALSE;
         while (it8 -> sy == SEOLN)
@@ -974,7 +892,7 @@
 // Skip a symbol
 
 static
-void Skip(LPIT8 it8, SYMBOL sy)
+void Skip(cmsIT8* it8, SYMBOL sy)
 {
         if (it8->sy == sy && it8->sy != SEOF)
                         InSymbol(it8);
@@ -983,7 +901,7 @@
 
 // Skip multiple EOLN
 static
-void SkipEOLN(LPIT8 it8)
+void SkipEOLN(cmsIT8* it8)
 {
     while (it8->sy == SEOLN) {
              InSymbol(it8);
@@ -993,7 +911,7 @@
 
 // Returns a string holding current value
 static
-LCMSBOOL GetVal(LPIT8 it8, char* Buffer, size_t max, const char* ErrorTitle)
+cmsBool GetVal(cmsIT8* it8, char* Buffer, cmsUInt32Number max, const char* ErrorTitle)
 {
     switch (it8->sy) {
 
@@ -1018,9 +936,9 @@
 // ---------------------------------------------------------- Table
 
 static
-LPTABLE GetTable(LPIT8 it8)
+TABLE* GetTable(cmsIT8* it8)
 {
-   if ((it8 -> nTable >= it8 ->TablesCount) || (it8 -> nTable < 0)) {
+   if ((it8 -> nTable >= it8 ->TablesCount)) {
 
            SynError(it8, "Table %d out of sequence", it8 -> nTable);
            return it8 -> Tab;
@@ -1032,75 +950,70 @@
 // ---------------------------------------------------------- Memory management
 
 
-
 // Frees an allocator and owned memory
-void LCMSEXPORT cmsIT8Free(LCMSHANDLE hIT8)
+void CMSEXPORT cmsIT8Free(cmsHANDLE hIT8)
 {
-   LPIT8 it8 = (LPIT8) hIT8;
+   cmsIT8* it8 = (cmsIT8*) hIT8;
 
     if (it8 == NULL)
         return;
 
-
     if (it8->MemorySink) {
 
-        LPOWNEDMEM p;
-        LPOWNEDMEM n;
+        OWNEDMEM* p;
+        OWNEDMEM* n;
 
         for (p = it8->MemorySink; p != NULL; p = n) {
 
             n = p->Next;
-            if (p->Ptr) _cmsFree(p->Ptr);
-            _cmsFree(p);
+            if (p->Ptr) _cmsFree(it8 ->ContextID, p->Ptr);
+            _cmsFree(it8 ->ContextID, p);
         }
     }
 
     if (it8->MemoryBlock)
-        _cmsFree(it8->MemoryBlock);
-
-     _cmsFree(it8);
+        _cmsFree(it8 ->ContextID, it8->MemoryBlock);
+
+    _cmsFree(it8 ->ContextID, it8);
 }
 
 
 // Allocates a chunk of data, keep linked list
 static
-void* AllocBigBlock(LPIT8 it8, size_t size)
+void* AllocBigBlock(cmsIT8* it8, cmsUInt32Number size)
 {
-   LPOWNEDMEM ptr1;
-   void* ptr = _cmsMalloc(size);
-
-        if (ptr) {
-
-                ZeroMemory(ptr, size);
-                ptr1 = (LPOWNEDMEM) _cmsMalloc(sizeof(OWNEDMEM));
-
-                if (ptr1 == NULL) {
-
-                     _cmsFree(ptr);
-                    return NULL;
-                }
-
-                ZeroMemory(ptr1, sizeof(OWNEDMEM));
-
-                ptr1-> Ptr        = ptr;
-                ptr1-> Next       = it8 -> MemorySink;
-                it8 -> MemorySink = ptr1;
+    OWNEDMEM* ptr1;
+    void* ptr = _cmsMallocZero(it8->ContextID, size);
+
+    if (ptr != NULL) {
+
+        ptr1 = (OWNEDMEM*) _cmsMallocZero(it8 ->ContextID, sizeof(OWNEDMEM));
+
+        if (ptr1 == NULL) {
+
+            _cmsFree(it8 ->ContextID, ptr);
+            return NULL;
         }
 
-        return ptr;
+        ptr1-> Ptr        = ptr;
+        ptr1-> Next       = it8 -> MemorySink;
+        it8 -> MemorySink = ptr1;
+    }
+
+    return ptr;
 }
 
 
 // Suballocator.
 static
-void* AllocChunk(LPIT8 it8, size_t size)
+void* AllocChunk(cmsIT8* it8, cmsUInt32Number size)
 {
-    size_t free = it8 ->Allocator.BlockSize - it8 ->Allocator.Used;
-    LPBYTE ptr;
-
-    size = ALIGNLONG(size);
-
-    if (size > free) {
+    cmsUInt32Number Free = it8 ->Allocator.BlockSize - it8 ->Allocator.Used;
+    cmsUInt8Number* ptr;
+
+    size = _cmsALIGNLONG(size);
+
+    if (size > Free) {
 
         if (it8 -> Allocator.BlockSize == 0)
 
@@ -1112,7 +1025,7 @@
                 it8 ->Allocator.BlockSize = size;
 
         it8 ->Allocator.Used = 0;
-        it8 ->Allocator.Block = (LPBYTE) AllocBigBlock(it8, it8 ->Allocator.BlockSize);
+        it8 ->Allocator.Block = (cmsUInt8Number*)  AllocBigBlock(it8, it8 ->Allocator.BlockSize);
     }
 
     ptr = it8 ->Allocator.Block + it8 ->Allocator.Used;
@@ -1125,9 +1038,9 @@
 
 // Allocates a string
 static
-char *AllocString(LPIT8 it8, const char* str)
+char *AllocString(cmsIT8* it8, const char* str)
 {
-    size_t Size = strlen(str)+1;
+    cmsUInt32Number Size = (cmsUInt32Number) strlen(str)+1;
     char *ptr;
 
 
@@ -1140,7 +1053,7 @@
 // Searches through linked list
 
 static
-LCMSBOOL IsAvailableOnList(LPKEYVALUE p, const char* Key, const char* Subkey, LPKEYVALUE* LastPtr)
+cmsBool IsAvailableOnList(KEYVALUE* p, const char* Key, const char* Subkey, KEYVALUE** LastPtr)
 {
     if (LastPtr) *LastPtr = p;
 
@@ -1150,7 +1063,7 @@
 
         if (*Key != '#') { // Comments are ignored
 
-            if (stricmp(Key, p->Keyword) == 0)
+            if (cmsstrcasecmp(Key, p->Keyword) == 0)
                     break;
         }
         }
@@ -1165,9 +1078,9 @@
 
         if (LastPtr) *LastPtr = p;
 
-        if (stricmp(Subkey, p->Subkey) == 0)
-            return TRUE;
-    }
+        if (cmsstrcasecmp(Subkey, p->Subkey) == 0)
+                    return TRUE;
+        }
 
     return FALSE;
 }
@@ -1176,55 +1089,62 @@
 
 // Add a property into a linked list
 static
-LPKEYVALUE AddToList(LPIT8 it8, LPKEYVALUE* Head, const char *Key, const char *Subkey, const char* xValue, WRITEMODE WriteAs)
+KEYVALUE* AddToList(cmsIT8* it8, KEYVALUE** Head, const char *Key, const char *Subkey, const char* xValue, WRITEMODE WriteAs)
 {
-    LPKEYVALUE p;
-
-    // Check if property is already in list (this is an error)
+    KEYVALUE* p;
+    KEYVALUE* last;
+
+
+    // Check if property is already in list
 
     if (IsAvailableOnList(*Head, Key, Subkey, &p)) {
 
-            // This may work for editing properties
+        // This may work for editing properties
 
         //     return SynError(it8, "duplicate key <%s>", Key);
     }
     else {
-        LPKEYVALUE last = p;
-
-    // Allocate the container
-    p = (LPKEYVALUE) AllocChunk(it8, sizeof(KEYVALUE));
-    if (p == NULL)
-    {
+
+        last = p;
+
+        // Allocate the container
+        p = (KEYVALUE*) AllocChunk(it8, sizeof(KEYVALUE));
+        if (p == NULL)
+        {
             SynError(it8, "AddToList: out of memory");
             return NULL;
-    }
-
-    // Store name and value
-    p->Keyword = AllocString(it8, Key);
+        }
+
+        // Store name and value
+        p->Keyword = AllocString(it8, Key);
         p->Subkey = (Subkey == NULL) ? NULL : AllocString(it8, Subkey);
 
         // Keep the container in our list
-        if (*Head == NULL)
+        if (*Head == NULL) {
             *Head = p;
+        }
         else
         {
-            if(Subkey != 0 && last != 0) {
+            if (Subkey != NULL && last != NULL) {
+
                 last->NextSubkey = p;
 
                 // If Subkey is not null, then last is the last property with the same key,
                 // but not necessarily is the last property in the list, so we need to move
                 // to the actual list end
-                while(last->Next != 0)
-                    last = last->Next;
-    }
-            last->Next = p;
-    }
-
-    p->Next    = NULL;
+                while (last->Next != NULL)
+                         last = last->Next;
+            }
+
+            if (last != NULL) last->Next = p;
+        }
+
+        p->Next    = NULL;
         p->NextSubkey = NULL;
     }
 
     p->WriteAs = WriteAs;
+
     if (xValue != NULL) {
 
         p->Value   = AllocString(it8, xValue);
@@ -1237,23 +1157,23 @@
 }
 
 static
-LPKEYVALUE AddAvailableProperty(LPIT8 it8, const char* Key, WRITEMODE as)
+KEYVALUE* AddAvailableProperty(cmsIT8* it8, const char* Key, WRITEMODE as)
 {
-        return AddToList(it8, &it8->ValidKeywords, Key, NULL, NULL, as);
+    return AddToList(it8, &it8->ValidKeywords, Key, NULL, NULL, as);
 }
 
 
 static
-LPKEYVALUE AddAvailableSampleID(LPIT8 it8, const char* Key)
+KEYVALUE* AddAvailableSampleID(cmsIT8* it8, const char* Key)
 {
-        return AddToList(it8, &it8->ValidSampleID, Key, NULL, NULL, WRITE_UNCOOKED);
+    return AddToList(it8, &it8->ValidSampleID, Key, NULL, NULL, WRITE_UNCOOKED);
 }
 
 
 static
-void AllocTable(LPIT8 it8)
+void AllocTable(cmsIT8* it8)
 {
-    LPTABLE t;
+    TABLE* t;
 
     t = it8 ->Tab + it8 ->TablesCount;
 
@@ -1265,9 +1185,9 @@
 }
 
 
-int LCMSEXPORT cmsIT8SetTable(LCMSHANDLE IT8, int nTable)
+cmsInt32Number CMSEXPORT cmsIT8SetTable(cmsHANDLE  IT8, cmsUInt32Number nTable)
 {
-     LPIT8 it8 = (LPIT8) IT8;
+     cmsIT8* it8 = (cmsIT8*) IT8;
 
      if (nTable >= it8 ->TablesCount) {
 
@@ -1289,16 +1209,14 @@
 
 
 // Init an empty container
-LCMSHANDLE LCMSEXPORT cmsIT8Alloc(void)
+cmsHANDLE  CMSEXPORT cmsIT8Alloc(cmsContext ContextID)
 {
-    LPIT8 it8;
+    cmsIT8* it8;
     int i;
 
-    it8 = (LPIT8) malloc(sizeof(IT8));
+    it8 = (cmsIT8*) _cmsMallocZero(ContextID, sizeof(cmsIT8));
     if (it8 == NULL) return NULL;
 
-    ZeroMemory(it8, sizeof(IT8));
-
     AllocTable(it8);
 
     it8->MemoryBlock = NULL;
@@ -1306,6 +1224,7 @@
 
     it8 ->nTable = 0;
 
+    it8->ContextID = ContextID;
     it8->Allocator.Used = 0;
     it8->Allocator.Block = NULL;
     it8->Allocator.BlockSize = 0;
@@ -1319,7 +1238,7 @@
     it8 -> inum = 0;
     it8 -> dnum = 0.0;
 
-    it8->FileStack[0] = (LPFILECTX)AllocChunk(it8, sizeof(FILECTX));
+    it8->FileStack[0] = (FILECTX*)AllocChunk(it8, sizeof(FILECTX));
     it8->IncludeSP   = 0;
     it8 -> lineno = 1;
 
@@ -1335,30 +1254,30 @@
             AddAvailableSampleID(it8, PredefinedSampleID[i]);
 
 
-   return (LCMSHANDLE) it8;
+   return (cmsHANDLE) it8;
 }
 
 
-const char* LCMSEXPORT cmsIT8GetSheetType(LCMSHANDLE hIT8)
+const char* CMSEXPORT cmsIT8GetSheetType(cmsHANDLE hIT8)
 {
-        LPIT8 it8 = (LPIT8) hIT8;
+        cmsIT8* it8 = (cmsIT8*) hIT8;
 
         return it8 ->SheetType;
 
 }
 
-LCMSBOOL  LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type)
+cmsBool CMSEXPORT cmsIT8SetSheetType(cmsHANDLE hIT8, const char* Type)
 {
-        LPIT8 it8 = (LPIT8) hIT8;
+        cmsIT8* it8 = (cmsIT8*) hIT8;
 
         strncpy(it8 ->SheetType, Type, MAXSTR-1);
         it8 ->SheetType[MAXSTR-1] = 0;
         return TRUE;
 }
 
-LCMSBOOL LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* Val)
+cmsBool CMSEXPORT cmsIT8SetComment(cmsHANDLE hIT8, const char* Val)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
 
     if (!Val) return FALSE;
     if (!*Val) return FALSE;
@@ -1369,9 +1288,9 @@
 
 
 // Sets a property
-LCMSBOOL LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* Key, const char *Val)
+cmsBool CMSEXPORT cmsIT8SetPropertyStr(cmsHANDLE hIT8, const char* Key, const char *Val)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
 
     if (!Val) return FALSE;
     if (!*Val) return FALSE;
@@ -1380,9 +1299,9 @@
 }
 
 
-LCMSBOOL LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val)
+cmsBool CMSEXPORT cmsIT8SetPropertyDbl(cmsHANDLE hIT8, const char* cProp, cmsFloat64Number Val)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
     char Buffer[1024];
 
     sprintf(Buffer, it8->DoubleFormatter, Val);
@@ -1390,9 +1309,9 @@
     return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_UNCOOKED) != NULL;
 }
 
-LCMSBOOL LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val)
+cmsBool CMSEXPORT cmsIT8SetPropertyHex(cmsHANDLE hIT8, const char* cProp, cmsUInt32Number Val)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
     char Buffer[1024];
 
     sprintf(Buffer, "%d", Val);
@@ -1400,25 +1319,25 @@
     return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_HEXADECIMAL) != NULL;
 }
 
-LCMSBOOL LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer)
+cmsBool CMSEXPORT cmsIT8SetPropertyUncooked(cmsHANDLE hIT8, const char* Key, const char* Buffer)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
 
     return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Buffer, WRITE_UNCOOKED) != NULL;
 }
 
-LCMSBOOL LCMSEXPORT cmsIT8SetPropertyMulti(LCMSHANDLE hIT8, const char* Key, const char* SubKey, const char *Buffer)
+cmsBool CMSEXPORT cmsIT8SetPropertyMulti(cmsHANDLE hIT8, const char* Key, const char* SubKey, const char *Buffer)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
 
     return AddToList(it8, &GetTable(it8)->HeaderList, Key, SubKey, Buffer, WRITE_PAIR) != NULL;
 }
 
 // Gets a property
-const char* LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* Key)
+const char* CMSEXPORT cmsIT8GetProperty(cmsHANDLE hIT8, const char* Key)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
-    LPKEYVALUE p;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+    KEYVALUE* p;
 
     if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, NULL, &p))
     {
@@ -1428,7 +1347,7 @@
 }
 
 
-double LCMSEXPORT cmsIT8GetPropertyDbl(LCMSHANDLE hIT8, const char* cProp)
+cmsFloat64Number CMSEXPORT cmsIT8GetPropertyDbl(cmsHANDLE hIT8, const char* cProp)
 {
     const char *v = cmsIT8GetProperty(hIT8, cProp);
 
@@ -1436,13 +1355,12 @@
     else return 0.0;
 }
 
-const char* LCMSEXPORT cmsIT8GetPropertyMulti(LCMSHANDLE hIT8, const char* Key, const char *SubKey)
+const char* CMSEXPORT cmsIT8GetPropertyMulti(cmsHANDLE hIT8, const char* Key, const char *SubKey)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
-    LPKEYVALUE p;
-
-    if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, SubKey, &p))
-    {
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+    KEYVALUE* p;
+
+    if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, SubKey, &p)) {
         return p -> Value;
     }
     return NULL;
@@ -1452,9 +1370,9 @@
 
 
 static
-void AllocateDataFormat(LPIT8 it8)
+void AllocateDataFormat(cmsIT8* it8)
 {
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     if (t -> DataFormat) return;    // Already allocated
 
@@ -1467,17 +1385,17 @@
         }
 
     t -> DataFormat = (char**) AllocChunk (it8, (t->nSamples + 1) * sizeof(char *));
-    if (t->DataFormat == NULL)
-    {
+    if (t->DataFormat == NULL) {
+
         SynError(it8, "AllocateDataFormat: Unable to allocate dataFormat array");
     }
 
 }
 
 static
-const char *GetDataFormat(LPIT8 it8, int n)
+const char *GetDataFormat(cmsIT8* it8, int n)
 {
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     if (t->DataFormat)
         return t->DataFormat[n];
@@ -1486,16 +1404,9 @@
 }
 
 static
-LCMSBOOL SetDataFormat(LPIT8 it8, int n, const char *label)
+cmsBool SetDataFormat(cmsIT8* it8, int n, const char *label)
 {
-    LPTABLE t = GetTable(it8);
-
-#ifdef  STRICT_CGATS
-    if (!IsAvailableOnList(it8-> ValidSampleID, label, NULL, NULL)) {
-        SynError(it8, "Invalid data format '%s'.", label);
-        return FALSE;
-    }
-#endif
+    TABLE* t = GetTable(it8);
 
     if (!t->DataFormat)
         AllocateDataFormat(it8);
@@ -1505,7 +1416,6 @@
         return FALSE;
     }
 
-
     if (t->DataFormat) {
         t->DataFormat[n] = AllocString(it8, label);
     }
@@ -1514,16 +1424,16 @@
 }
 
 
-LCMSBOOL LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE h, int n, const char *Sample)
+cmsBool CMSEXPORT cmsIT8SetDataFormat(cmsHANDLE  h, int n, const char *Sample)
 {
-        LPIT8 it8 = (LPIT8) h;
+        cmsIT8* it8 = (cmsIT8*) h;
         return SetDataFormat(it8, n, Sample);
 }
 
 static
-void AllocateDataSet(LPIT8 it8)
+void AllocateDataSet(cmsIT8* it8)
 {
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     if (t -> Data) return;    // Already allocated
 
@@ -1531,21 +1441,20 @@
     t-> nPatches   = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
 
     t-> Data = (char**)AllocChunk (it8, (t->nSamples + 1) * (t->nPatches + 1) *sizeof (char*));
-    if (t->Data == NULL)
-    {
+    if (t->Data == NULL) {
+
         SynError(it8, "AllocateDataSet: Unable to allocate data array");
     }
 
 }
 
 static
-char* GetData(LPIT8 it8, int nSet, int nField)
+char* GetData(cmsIT8* it8, int nSet, int nField)
 {
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
     int  nSamples   = t -> nSamples;
     int  nPatches   = t -> nPatches;
 
-
     if (nSet >= nPatches || nField >= nSamples)
         return NULL;
 
@@ -1554,17 +1463,15 @@
 }
 
 static
-LCMSBOOL SetData(LPIT8 it8, int nSet, int nField, const char *Val)
+cmsBool SetData(cmsIT8* it8, int nSet, int nField, const char *Val)
 {
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     if (!t->Data)
         AllocateDataSet(it8);
 
     if (!t->Data) return FALSE;
 
-
-
     if (nSet > t -> nPatches || nSet < 0) {
 
             return SynError(it8, "Patch %d out of range, there are %d patches", nSet, t -> nPatches);
@@ -1575,7 +1482,6 @@
 
     }
 
-
     t->Data [nSet * t -> nSamples + nField] = AllocString(it8, Val);
     return TRUE;
 }
@@ -1586,38 +1492,38 @@
 
 // Writes a string to file
 static
-void WriteStr(LPSAVESTREAM f, const char *str)
+void WriteStr(SAVESTREAM* f, const char *str)
 {
-
-    size_t len;
+    cmsUInt32Number len;
 
     if (str == NULL)
         str = " ";
 
     // Lenghth to write
-    len = strlen(str);
+    len = (cmsUInt32Number) strlen(str);
     f ->Used += len;
 
 
     if (f ->stream) {   // Should I write it to a file?
 
-        fwrite(str, 1, len, f->stream);
+        if (fwrite(str, 1, len, f->stream) != len) {
+            cmsSignalError(0, cmsERROR_WRITE, "Write to file error in CGATS parser");
+            return;
+        }
 
     }
     else {  // Or to a memory block?
 
-
         if (f ->Base) {   // Am I just counting the bytes?
 
             if (f ->Used > f ->Max) {
 
-                cmsSignalError(LCMS_ERRC_ABORTED, "Write to memory overflows in CGATS parser");
-                return;
+                 cmsSignalError(0, cmsERROR_WRITE, "Write to memory overflows in CGATS parser");
+                 return;
             }
 
-            CopyMemory(f ->Ptr, str, len);
+            memmove(f ->Ptr, str, len);
             f->Ptr += len;
-
         }
 
     }
@@ -1627,7 +1533,7 @@
 // Write formatted
 
 static
-void Writef(LPSAVESTREAM f, const char* frm, ...)
+void Writef(SAVESTREAM* f, const char* frm, ...)
 {
     char Buffer[4096];
     va_list args;
@@ -1642,10 +1548,10 @@
 
 // Writes full header
 static
-void WriteHeader(LPIT8 it8, LPSAVESTREAM fp)
+void WriteHeader(cmsIT8* it8, SAVESTREAM* fp)
 {
-    LPKEYVALUE p;
-    LPTABLE t = GetTable(it8);
+    KEYVALUE* p;
+    TABLE* t = GetTable(it8);
 
 
     for (p = t->HeaderList; (p != NULL); p = p->Next)
@@ -1672,14 +1578,13 @@
 
         if (!IsAvailableOnList(it8-> ValidKeywords, p->Keyword, NULL, NULL)) {
 
-#ifdef STRICT_CGATS
+#ifdef CMS_STRICT_CGATS
             WriteStr(fp, "KEYWORD\t\"");
             WriteStr(fp, p->Keyword);
             WriteStr(fp, "\"\n");
 #endif
 
             AddAvailableProperty(it8, p->Keyword, WRITE_UNCOOKED);
-
         }
 
         WriteStr(fp, p->Keyword);
@@ -1720,10 +1625,10 @@
 
 // Writes the data format
 static
-void WriteDataFormat(LPSAVESTREAM fp, LPIT8 it8)
+void WriteDataFormat(SAVESTREAM* fp, cmsIT8* it8)
 {
     int i, nSamples;
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     if (!t -> DataFormat) return;
 
@@ -1743,10 +1648,10 @@
 
 // Writes data array
 static
-void WriteData(LPSAVESTREAM fp, LPIT8 it8)
+void WriteData(SAVESTREAM* fp, cmsIT8* it8)
 {
        int  i, j;
-       LPTABLE t = GetTable(it8);
+       TABLE* t = GetTable(it8);
 
        if (!t->Data) return;
 
@@ -1785,13 +1690,13 @@
 
 
 // Saves whole file
-LCMSBOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE hIT8, const char* cFileName)
+cmsBool CMSEXPORT cmsIT8SaveToFile(cmsHANDLE hIT8, const char* cFileName)
 {
     SAVESTREAM sd;
-    int i;
-    LPIT8 it8 = (LPIT8) hIT8;
-
-    ZeroMemory(&sd, sizeof(SAVESTREAM));
+    cmsUInt32Number i;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+
+    memset(&sd, 0, sizeof(sd));
 
     sd.stream = fopen(cFileName, "wt");
     if (!sd.stream) return FALSE;
@@ -1806,23 +1711,23 @@
             WriteData(&sd, it8);
     }
 
-    fclose(sd.stream);
+    if (fclose(sd.stream) != 0) return FALSE;
 
     return TRUE;
 }
 
 
 // Saves to memory
-LCMSBOOL LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded)
+cmsBool CMSEXPORT cmsIT8SaveToMem(cmsHANDLE hIT8, void *MemPtr, cmsUInt32Number* BytesNeeded)
 {
     SAVESTREAM sd;
-    int i;
-    LPIT8 it8 = (LPIT8) hIT8;
-
-    ZeroMemory(&sd, sizeof(SAVESTREAM));
+    cmsUInt32Number i;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+
+    memset(&sd, 0, sizeof(sd));
 
     sd.stream = NULL;
-    sd.Base   = (LPBYTE) MemPtr;
+    sd.Base   = (cmsUInt8Number*)  MemPtr;
     sd.Ptr    = sd.Base;
 
     sd.Used = 0;
@@ -1856,10 +1761,10 @@
 // -------------------------------------------------------------- Higer level parsing
 
 static
-LCMSBOOL DataFormatSection(LPIT8 it8)
+cmsBool DataFormatSection(cmsIT8* it8)
 {
     int iField = 0;
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     InSymbol(it8);   // Eats "BEGIN_DATA_FORMAT"
     CheckEOLN(it8);
@@ -1897,12 +1802,12 @@
 
 
 static
-LCMSBOOL DataSection (LPIT8 it8)
+cmsBool DataSection (cmsIT8* it8)
 {
     int  iField = 0;
     int  iSet   = 0;
-    char Buffer[MAXSTR];
-    LPTABLE t = GetTable(it8);
+    char Buffer[256];
+    TABLE* t = GetTable(it8);
 
     InSymbol(it8);   // Eats "BEGIN_DATA"
     CheckEOLN(it8);
@@ -1949,11 +1854,11 @@
 
 
 static
-LCMSBOOL HeaderSection(LPIT8 it8)
+cmsBool HeaderSection(cmsIT8* it8)
 {
     char VarName[MAXID];
     char Buffer[MAXSTR];
-    LPKEYVALUE Key;
+    KEYVALUE* Key;
 
         while (it8->sy != SEOF &&
                it8->sy != SSYNERROR &&
@@ -1985,7 +1890,7 @@
 
                 if (!IsAvailableOnList(it8-> ValidKeywords, VarName, NULL, &Key)) {
 
-#ifdef STRICT_CGATS
+#ifdef CMS_STRICT_CGATS
                  return SynError(it8, "Undefined keyword '%s'", VarName);
 #else
                     Key = AddAvailableProperty(it8, VarName, WRITE_UNCOOKED);
@@ -2007,7 +1912,7 @@
                         return SynError(it8, "Invalid value '%s' for property '%s'.", Buffer, VarName);
 
                     // chop the string as a list of "subkey, value" pairs, using ';' as a separator
-                    for(Subkey = Buffer; Subkey != NULL; Subkey = Nextkey)
+                    for (Subkey = Buffer; Subkey != NULL; Subkey = Nextkey)
                     {
                         char *Value, *temp;
 
@@ -2058,7 +1963,7 @@
 
 
 static
-LCMSBOOL ParseIT8(LPIT8 it8, LCMSBOOL nosheet)
+cmsBool ParseIT8(cmsIT8* it8, cmsBool nosheet)
 {
     char* SheetTypePtr = it8 ->SheetType;
 
@@ -2119,33 +2024,32 @@
 // Init usefull pointers
 
 static
-void CookPointers(LPIT8 it8)
+void CookPointers(cmsIT8* it8)
 {
     int idField, i;
     char* Fld;
-    int j;
-    int nOldTable = it8 ->nTable;
+    cmsUInt32Number j;
+    cmsUInt32Number nOldTable = it8 ->nTable;
 
     for (j=0; j < it8 ->TablesCount; j++) {
 
-    LPTABLE t = it8 ->Tab + j;
+    TABLE* t = it8 ->Tab + j;
 
     t -> SampleID = 0;
     it8 ->nTable = j;
 
     for (idField = 0; idField < t -> nSamples; idField++)
     {
-        if (t ->DataFormat == NULL) {
-             SynError(it8, "Undefined DATA_FORMAT");
-             return;
-
+        if (t ->DataFormat == NULL){
+            SynError(it8, "Undefined DATA_FORMAT");
+            return;
         }
 
         Fld = t->DataFormat[idField];
         if (!Fld) continue;
 
 
-        if (stricmp(Fld, "SAMPLE_ID") == 0) {
+        if (cmsstrcasecmp(Fld, "SAMPLE_ID") == 0) {
 
                     t -> SampleID = idField;
 
@@ -2170,7 +2074,7 @@
 
         // "LABEL" is an extension. It keeps references to forward tables
 
-        if ((stricmp(Fld, "LABEL") == 0) || Fld[0] == '$' ) {
+        if ((cmsstrcasecmp(Fld, "LABEL") == 0) || Fld[0] == '$' ) {
 
                     // Search for table references...
                     for (i=0; i < t -> nPatches; i++) {
@@ -2179,15 +2083,15 @@
 
                             if (Label) {
 
-                                int k;
+                                cmsUInt32Number k;
 
                                 // This is the label, search for a table containing
                                 // this property
 
                                 for (k=0; k < it8 ->TablesCount; k++) {
 
-                                    LPTABLE Table = it8 ->Tab + k;
-                                    LPKEYVALUE p;
+                                    TABLE* Table = it8 ->Tab + k;
+                                    KEYVALUE* p;
 
                                     if (IsAvailableOnList(Table->HeaderList, Label, NULL, &p)) {
 
@@ -2221,10 +2125,10 @@
 // that should be something like some printable characters plus a \n
 
 static
-int IsMyBlock(LPBYTE Buffer, size_t n)
+int IsMyBlock(cmsUInt8Number* Buffer, int n)
 {
     int cols = 1, space = 0, quot = 0;
-    size_t i;
+    int i;
 
     if (n < 10) return FALSE;   // Too small
 
@@ -2261,20 +2165,22 @@
 
 
 static
-int IsMyFile(const char* FileName)
+cmsBool IsMyFile(const char* FileName)
 {
    FILE *fp;
-   size_t Size;
-   BYTE Ptr[133];
+   cmsUInt32Number Size;
+   cmsUInt8Number Ptr[133];
 
    fp = fopen(FileName, "rt");
    if (!fp) {
-       cmsSignalError(LCMS_ERRC_ABORTED, "File '%s' not found", FileName);
+       cmsSignalError(0, cmsERROR_FILE, "File '%s' not found", FileName);
        return FALSE;
    }
 
-   Size = fread(Ptr, 1, 132, fp);
-   fclose(fp);
+   Size = (cmsUInt32Number) fread(Ptr, 1, 132, fp);
+
+   if (fclose(fp) != 0)
+       return FALSE;
 
    Ptr[Size] = '\0';
 
@@ -2284,24 +2190,28 @@
 // ---------------------------------------------------------- Exported routines
 
 
-LCMSHANDLE LCMSEXPORT cmsIT8LoadFromMem(void *Ptr, size_t len)
+cmsHANDLE  CMSEXPORT cmsIT8LoadFromMem(cmsContext ContextID, void *Ptr, cmsUInt32Number len)
 {
-    LCMSHANDLE hIT8;
-    LPIT8  it8;
-
-    int type = IsMyBlock((LPBYTE) Ptr, len);
+    cmsHANDLE hIT8;
+    cmsIT8*  it8;
+    int type;
+
+    _cmsAssert(Ptr != NULL);
+    _cmsAssert(len != 0);
+
+    type = IsMyBlock((cmsUInt8Number*)Ptr, len);
     if (type == 0) return NULL;
 
-    hIT8 = cmsIT8Alloc();
+    hIT8 = cmsIT8Alloc(ContextID);
     if (!hIT8) return NULL;
 
-    it8 = (LPIT8) hIT8;
-    it8 ->MemoryBlock = (char*) _cmsMalloc(len + 1);
+    it8 = (cmsIT8*) hIT8;
+    it8 ->MemoryBlock = (char*) _cmsMalloc(ContextID, len + 1);
 
     strncpy(it8 ->MemoryBlock, (const char*) Ptr, len);
     it8 ->MemoryBlock[len] = 0;
 
-    strncpy(it8->FileStack[0]->FileName, "", MAX_PATH-1);
+    strncpy(it8->FileStack[0]->FileName, "", cmsMAX_PATH-1);
     it8-> Source = it8 -> MemoryBlock;
 
     if (!ParseIT8(it8, type-1)) {
@@ -2313,7 +2223,7 @@
     CookPointers(it8);
     it8 ->nTable = 0;
 
-     _cmsFree(it8->MemoryBlock);
+    _cmsFree(ContextID, it8->MemoryBlock);
     it8 -> MemoryBlock = NULL;
 
     return hIT8;
@@ -2322,17 +2232,20 @@
 }
 
 
-LCMSHANDLE LCMSEXPORT cmsIT8LoadFromFile(const char* cFileName)
+cmsHANDLE  CMSEXPORT cmsIT8LoadFromFile(cmsContext ContextID, const char* cFileName)
 {
 
-     LCMSHANDLE hIT8;
-     LPIT8  it8;
-
-     int type = IsMyFile(cFileName);
+     cmsHANDLE hIT8;
+     cmsIT8*  it8;
+     int type;
+
+     _cmsAssert(cFileName != NULL);
+
+     type = IsMyFile(cFileName);
      if (type == 0) return NULL;
 
-     hIT8 = cmsIT8Alloc();
-     it8 = (LPIT8) hIT8;
+     hIT8 = cmsIT8Alloc(ContextID);
+     it8 = (cmsIT8*) hIT8;
      if (!hIT8) return NULL;
 
 
@@ -2344,8 +2257,8 @@
      }
 
 
-    strncpy(it8->FileStack[0]->FileName, cFileName, MAX_PATH-1);
-    it8->FileStack[0]->FileName[MAX_PATH-1] = 0;
+    strncpy(it8->FileStack[0]->FileName, cFileName, cmsMAX_PATH-1);
+    it8->FileStack[0]->FileName[cmsMAX_PATH-1] = 0;
 
     if (!ParseIT8(it8, type-1)) {
 
@@ -2357,28 +2270,41 @@
     CookPointers(it8);
     it8 ->nTable = 0;
 
-    fclose(it8 ->FileStack[0]->Stream);
+    if (fclose(it8 ->FileStack[0]->Stream)!= 0) {
+        cmsIT8Free(hIT8);
+            return NULL;
+    }
+
     return hIT8;
 
 }
 
-int LCMSEXPORT cmsIT8EnumDataFormat(LCMSHANDLE hIT8, char ***SampleNames)
+int CMSEXPORT cmsIT8EnumDataFormat(cmsHANDLE hIT8, char ***SampleNames)
 {
-        LPIT8 it8 = (LPIT8) hIT8;
-        LPTABLE t = GetTable(it8);
-
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+    TABLE* t;
+
+    _cmsAssert(hIT8 != NULL);
+
+    t = GetTable(it8);
+
+    if (SampleNames)
         *SampleNames = t -> DataFormat;
-        return t -> nSamples;
+    return t -> nSamples;
 }
 
 
-int LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE hIT8, const char ***PropertyNames)
+cmsUInt32Number CMSEXPORT cmsIT8EnumProperties(cmsHANDLE hIT8, char ***PropertyNames)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
-    LPKEYVALUE p;
-    int n;
-    const char **Props;
-    LPTABLE t = GetTable(it8);
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+    KEYVALUE* p;
+    cmsUInt32Number n;
+    char **Props;
+    TABLE* t;
+
+    _cmsAssert(hIT8 != NULL);
+
+    t = GetTable(it8);
 
     // Pass#1 - count properties
 
@@ -2388,7 +2314,7 @@
     }
 
 
-    Props = (const char **) AllocChunk(it8, sizeof(char *) * n);
+    Props = (char **) AllocChunk(it8, sizeof(char *) * n);
 
     // Pass#2 - Fill pointers
     n = 0;
@@ -2400,13 +2326,18 @@
     return n;
 }
 
-int LCMSEXPORT cmsIT8EnumPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char ***SubpropertyNames)
+cmsUInt32Number CMSEXPORT cmsIT8EnumPropertyMulti(cmsHANDLE hIT8, const char* cProp, const char ***SubpropertyNames)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
-    LPKEYVALUE p, tmp;
-    int n;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+    KEYVALUE *p, *tmp;
+    cmsUInt32Number n;
     const char **Props;
-    LPTABLE t = GetTable(it8);
+    TABLE* t;
+
+    _cmsAssert(hIT8 != NULL);
+
+
+    t = GetTable(it8);
 
     if(!IsAvailableOnList(t->HeaderList, cProp, NULL, &p)) {
         *SubpropertyNames = 0;
@@ -2436,11 +2367,11 @@
 }
 
 static
-int LocatePatch(LPIT8 it8, const char* cPatch)
+int LocatePatch(cmsIT8* it8, const char* cPatch)
 {
     int i;
     const char *data;
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     for (i=0; i < t-> nPatches; i++) {
 
@@ -2448,7 +2379,7 @@
 
         if (data != NULL) {
 
-                if (stricmp(data, cPatch) == 0)
+                if (cmsstrcasecmp(data, cPatch) == 0)
                         return i;
                 }
         }
@@ -2459,62 +2390,65 @@
 
 
 static
-int LocateEmptyPatch(LPIT8 it8)
+int LocateEmptyPatch(cmsIT8* it8)
 {
     int i;
     const char *data;
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     for (i=0; i < t-> nPatches; i++) {
 
         data = GetData(it8, i, t->SampleID);
 
         if (data == NULL)
-                    return i;
-
-        }
-
-        return -1;
+            return i;
+
+    }
+
+    return -1;
 }
 
 static
-int LocateSample(LPIT8 it8, const char* cSample)
+int LocateSample(cmsIT8* it8, const char* cSample)
 {
     int i;
     const char *fld;
-    LPTABLE t = GetTable(it8);
+    TABLE* t = GetTable(it8);
 
     for (i=0; i < t->nSamples; i++) {
 
         fld = GetDataFormat(it8, i);
-        if (stricmp(fld, cSample) == 0)
+        if (cmsstrcasecmp(fld, cSample) == 0)
             return i;
     }
 
-
-    // SynError(it8, "Couldn't find data field %s\n", cSample);
     return -1;
 
 }
 
 
-int LCMSEXPORT cmsIT8GetDataFormat(LCMSHANDLE hIT8, const char* cSample)
+int CMSEXPORT cmsIT8FindDataFormat(cmsHANDLE hIT8, const char* cSample)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+
+    _cmsAssert(hIT8 != NULL);
+
     return LocateSample(it8, cSample);
 }
 
 
 
-const char* LCMSEXPORT cmsIT8GetDataRowCol(LCMSHANDLE hIT8, int row, int col)
+const char* CMSEXPORT cmsIT8GetDataRowCol(cmsHANDLE hIT8, int row, int col)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+
+    _cmsAssert(hIT8 != NULL);
 
     return GetData(it8, row, col);
 }
 
 
-double LCMSEXPORT cmsIT8GetDataRowColDbl(LCMSHANDLE hIT8, int row, int col)
+cmsFloat64Number CMSEXPORT cmsIT8GetDataRowColDbl(cmsHANDLE hIT8, int row, int col)
 {
     const char* Buffer;
 
@@ -2530,19 +2464,23 @@
 }
 
 
-LCMSBOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col, const char* Val)
+cmsBool CMSEXPORT cmsIT8SetDataRowCol(cmsHANDLE hIT8, int row, int col, const char* Val)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+
+    _cmsAssert(hIT8 != NULL);
 
     return SetData(it8, row, col, Val);
 }
 
 
-LCMSBOOL LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col, double Val)
+cmsBool CMSEXPORT cmsIT8SetDataRowColDbl(cmsHANDLE hIT8, int row, int col, cmsFloat64Number Val)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
     char Buff[256];
 
+    _cmsAssert(hIT8 != NULL);
+
     sprintf(Buff, it8->DoubleFormatter, Val);
 
     return SetData(it8, row, col, Buff);
@@ -2550,18 +2488,18 @@
 
 
 
-const char* LCMSEXPORT cmsIT8GetData(LCMSHANDLE hIT8, const char* cPatch, const char* cSample)
+const char* CMSEXPORT cmsIT8GetData(cmsHANDLE hIT8, const char* cPatch, const char* cSample)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
     int iField, iSet;
 
+    _cmsAssert(hIT8 != NULL);
 
     iField = LocateSample(it8, cSample);
     if (iField < 0) {
         return NULL;
     }
 
-
     iSet = LocatePatch(it8, cPatch);
     if (iSet < 0) {
             return NULL;
@@ -2571,7 +2509,7 @@
 }
 
 
-double LCMSEXPORT cmsIT8GetDataDbl(LCMSHANDLE it8, const char* cPatch, const char* cSample)
+cmsFloat64Number CMSEXPORT cmsIT8GetDataDbl(cmsHANDLE  it8, const char* cPatch, const char* cSample)
 {
     const char* Buffer;
 
@@ -2589,100 +2527,109 @@
 
 
 
-LCMSBOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE hIT8, const char* cPatch,
-                        const char* cSample,
-                        const char *Val)
+cmsBool CMSEXPORT cmsIT8SetData(cmsHANDLE hIT8, const char* cPatch, const char* cSample, const char *Val)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
     int iField, iSet;
-    LPTABLE t = GetTable(it8);
-
+    TABLE* t;
+
+    _cmsAssert(hIT8 != NULL);
+
+    t = GetTable(it8);
 
     iField = LocateSample(it8, cSample);
 
     if (iField < 0)
         return FALSE;
 
-
-
-        if (t-> nPatches == 0) {
-
-                AllocateDataFormat(it8);
-                AllocateDataSet(it8);
-                CookPointers(it8);
-        }
-
-
-        if (stricmp(cSample, "SAMPLE_ID") == 0)
-        {
-
-                iSet   = LocateEmptyPatch(it8);
-                if (iSet < 0) {
-                        return SynError(it8, "Couldn't add more patches '%s'\n", cPatch);
-                }
-
-                iField = t -> SampleID;
+    if (t-> nPatches == 0) {
+
+        AllocateDataFormat(it8);
+        AllocateDataSet(it8);
+        CookPointers(it8);
+    }
+
+    if (cmsstrcasecmp(cSample, "SAMPLE_ID") == 0) {
+
+        iSet   = LocateEmptyPatch(it8);
+        if (iSet < 0) {
+            return SynError(it8, "Couldn't add more patches '%s'\n", cPatch);
         }
-        else {
-                iSet = LocatePatch(it8, cPatch);
-                if (iSet < 0) {
-                    return FALSE;
-            }
+
+        iField = t -> SampleID;
+    }
+    else {
+        iSet = LocatePatch(it8, cPatch);
+        if (iSet < 0) {
+            return FALSE;
         }
-
-        return SetData(it8, iSet, iField, Val);
+    }
+
+    return SetData(it8, iSet, iField, Val);
 }
 
 
-LCMSBOOL LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
-                        const char* cSample,
-                        double Val)
+cmsBool CMSEXPORT cmsIT8SetDataDbl(cmsHANDLE hIT8, const char* cPatch,
+                                   const char* cSample,
+                                   cmsFloat64Number Val)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
     char Buff[256];
 
-        snprintf(Buff, 255, it8->DoubleFormatter, Val);
-        return cmsIT8SetData(hIT8, cPatch, cSample, Buff);
-
+    _cmsAssert(hIT8 != NULL);
+
+    snprintf(Buff, 255, it8->DoubleFormatter, Val);
+    return cmsIT8SetData(hIT8, cPatch, cSample, Buff);
 }
 
 // Buffer should get MAXSTR at least
 
-const char* LCMSEXPORT cmsIT8GetPatchName(LCMSHANDLE hIT8, int nPatch, char* buffer)
+const char* CMSEXPORT cmsIT8GetPatchName(cmsHANDLE hIT8, int nPatch, char* buffer)
 {
-        LPIT8 it8 = (LPIT8) hIT8;
-        LPTABLE t = GetTable(it8);
-        char* Data = GetData(it8, nPatch, t->SampleID);
-
-        if (!Data) return NULL;
-        if (!buffer) return Data;
-
-        strncpy(buffer, Data, MAXSTR-1);
-        buffer[MAXSTR-1] = 0;
-        return buffer;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+    TABLE* t;
+    char* Data;
+
+    _cmsAssert(hIT8 != NULL);
+
+    t = GetTable(it8);
+    Data = GetData(it8, nPatch, t->SampleID);
+
+    if (!Data) return NULL;
+    if (!buffer) return Data;
+
+    strncpy(buffer, Data, MAXSTR-1);
+    buffer[MAXSTR-1] = 0;
+    return buffer;
 }
 
-int LCMSEXPORT cmsIT8GetPatchByName(LCMSHANDLE hIT8, const char *cPatch)
+int CMSEXPORT cmsIT8GetPatchByName(cmsHANDLE hIT8, const char *cPatch)
 {
-    return LocatePatch((LPIT8)hIT8, cPatch);
+    _cmsAssert(hIT8 != NULL);
+
+    return LocatePatch((cmsIT8*)hIT8, cPatch);
 }
 
-int LCMSEXPORT cmsIT8TableCount(LCMSHANDLE hIT8)
+cmsUInt32Number CMSEXPORT cmsIT8TableCount(cmsHANDLE hIT8)
 {
-        LPIT8 it8 = (LPIT8) hIT8;
-
-        return it8 ->TablesCount;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+
+    _cmsAssert(hIT8 != NULL);
+
+    return it8 ->TablesCount;
 }
 
 // This handles the "LABEL" extension.
 // Label, nTable, Type
 
-int LCMSEXPORT cmsIT8SetTableByLabel(LCMSHANDLE hIT8, const char* cSet, const char* cField, const char* ExpectedType)
+int CMSEXPORT cmsIT8SetTableByLabel(cmsHANDLE hIT8, const char* cSet, const char* cField, const char* ExpectedType)
 {
     const char* cLabelFld;
     char Type[256], Label[256];
     int nTable;
 
+    _cmsAssert(hIT8 != NULL);
+
     if (cField != NULL && *cField == 0)
             cField = "LABEL";
 
@@ -2700,18 +2647,21 @@
 
     if (ExpectedType) {
 
-        if (stricmp(Type, ExpectedType) != 0) return -1;
+        if (cmsstrcasecmp(Type, ExpectedType) != 0) return -1;
     }
 
     return cmsIT8SetTable(hIT8, nTable);
 }
 
 
-LCMSBOOL LCMSEXPORT cmsIT8SetIndexColumn(LCMSHANDLE hIT8, const char* cSample)
+cmsBool CMSEXPORT cmsIT8SetIndexColumn(cmsHANDLE hIT8, const char* cSample)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
-
-    int pos = LocateSample(it8, cSample);
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+    int pos;
+
+    _cmsAssert(hIT8 != NULL);
+
+    pos = LocateSample(it8, cSample);
     if(pos == -1)
         return FALSE;
 
@@ -2720,9 +2670,11 @@
 }
 
 
-void LCMSEXPORT cmsIT8DefineDblFormat(LCMSHANDLE hIT8, const char* Formatter)
+void CMSEXPORT cmsIT8DefineDblFormat(cmsHANDLE hIT8, const char* Formatter)
 {
-    LPIT8 it8 = (LPIT8) hIT8;
+    cmsIT8* it8 = (cmsIT8*) hIT8;
+
+    _cmsAssert(hIT8 != NULL);
 
     if (Formatter == NULL)
         strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
--- a/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,178 +49,117 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-#include "lcms.h"
-
-
-
-
-/*
-       This module provides conversion stages for handling intents.
-
-The chain of evaluation in a transform is:
-
-                PCS1            PCS2                    PCS3          PCS4
-
-|From |  |From  |  |Conversion |  |Preview |  |Gamut   |  |Conversion |  |To    |  |To     |
-|Input|->|Device|->|Stage 1    |->|handling|->|Checking|->|Stage 2    |->|Device|->|output |
-
---------  -------  -------------   ---------  ----------  -------------   -------  ---------
-
-          AToB0                     prew0       gamut                     BToA0
-Formatting LUT      Adjusting        LUT         LUT       Adjusting       LUT      Formatting
-          Intent     Intent 1       intent      intent      Intent 2      Intent
-
-
-Some of these LUT may be missing
-
-There are two intents involved here, the intent of the transform itself, and the
-intent the proof is being done, if is the case. Since the first intent is to be
-applied to preview, is the proofing intent. The second intent  identifies the
-transform intent. Input data of any stage is taked as relative colorimetric
-always.
-
-
-NOTES: V4 states than perceptual & saturation intents between mixed v2 & v4 profiles should
-scale PCS from a black point equal to ZERO in v2 profiles to the reference media black of
-perceptual v4 PCS. Since I found many v2 profiles to be using a perceptual intent with black
-point not zero at all, I'm implementing that as a black point compensation from whatever
-black from perceptal intent to the reference media black for v4 profiles.
-
-*/
-
+//
+//---------------------------------------------------------------------------------
+//
 
-
-
-int cdecl cmsChooseCnvrt(int Absolute,
-                 int Phase1, LPcmsCIEXYZ BlackPointIn,
-                             LPcmsCIEXYZ WhitePointIn,
-                             LPcmsCIEXYZ IlluminantIn,
-                             LPMAT3 ChromaticAdaptationMatrixIn,
-
-                 int Phase2, LPcmsCIEXYZ BlackPointOut,
-                             LPcmsCIEXYZ WhitePointOut,
-                             LPcmsCIEXYZ IlluminantOut,
-                             LPMAT3 ChromaticAdaptationMatrixOut,
-
-                int DoBlackPointCompensation,
-                double AdaptationState,
-                 _cmsADJFN *fn1,
-                 LPWMAT3 wm, LPWVEC3 wof);
-
-
-// -------------------------------------------------------------------------
-
-// D50 - Widely used
-
-LCMSAPI LPcmsCIEXYZ LCMSEXPORT cmsD50_XYZ(void)
-{
-    static cmsCIEXYZ D50XYZ = {D50X, D50Y, D50Z};
-
-    return &D50XYZ;
-}
-
-LCMSAPI LPcmsCIExyY LCMSEXPORT cmsD50_xyY(void)
-{
-    static cmsCIExyY D50xyY;
-    cmsXYZ2xyY(&D50xyY, cmsD50_XYZ());
-
-    return &D50xyY;
-}
-
-
-// ---------------- From LUT to LUT --------------------------
+#include "lcms2_internal.h"
 
 
-// Calculate m, offset Relativ -> Absolute undoing any chromatic
-// adaptation done by the profile.
+// Link several profiles to obtain a single LUT modelling the whole color transform. Intents, Black point
+// compensation and Adaptation parameters may vary across profiles. BPC and Adaptation refers to the PCS
+// after the profile. I.e, BPC[0] refers to connexion between profile(0) and profile(1)
+cmsPipeline* _cmsLinkProfiles(cmsContext     ContextID,
+                              cmsUInt32Number nProfiles,
+                              cmsUInt32Number Intents[],
+                              cmsHPROFILE     hProfiles[],
+                              cmsBool         BPC[],
+                              cmsFloat64Number AdaptationStates[],
+                              cmsUInt32Number dwFlags);
 
-#ifdef _MSC_VER
-#pragma warning(disable : 4100 4505)
-#endif
-
-
+//---------------------------------------------------------------------------------
 
-// join scalings to obtain:
-//     relative input to absolute and then to relative output
-
+// This is the default routine for ICC-style intents. A user may decide to override it by using a plugin.
+// Supported intents are perceptual, relative colorimetric, saturation and ICC-absolute colorimetric
 static
-void Rel2RelStepAbsCoefs(double AdaptationState,
+cmsPipeline* DefaultICCintents(cmsContext     ContextID,
+                               cmsUInt32Number nProfiles,
+                               cmsUInt32Number Intents[],
+                               cmsHPROFILE     hProfiles[],
+                               cmsBool         BPC[],
+                               cmsFloat64Number AdaptationStates[],
+                               cmsUInt32Number dwFlags);
 
-                         LPcmsCIEXYZ BlackPointIn,
-                         LPcmsCIEXYZ WhitePointIn,
-                         LPcmsCIEXYZ IlluminantIn,
-                         LPMAT3 ChromaticAdaptationMatrixIn,
+//---------------------------------------------------------------------------------
 
-                         LPcmsCIEXYZ BlackPointOut,
-                         LPcmsCIEXYZ WhitePointOut,
-                         LPcmsCIEXYZ IlluminantOut,
-                         LPMAT3 ChromaticAdaptationMatrixOut,
+// This is the entry for black-preserving K-only intents, which are non-ICC. Last profile have to be a output profile
+// to do the trick (no devicelinks allowed at that position)
+static
+cmsPipeline*  BlackPreservingKOnlyIntents(cmsContext     ContextID,
+                                          cmsUInt32Number nProfiles,
+                                          cmsUInt32Number Intents[],
+                                          cmsHPROFILE     hProfiles[],
+                                          cmsBool         BPC[],
+                                          cmsFloat64Number AdaptationStates[],
+                                          cmsUInt32Number dwFlags);
 
-                         LPMAT3 m, LPVEC3 of)
-{
+//---------------------------------------------------------------------------------
 
-       VEC3 WtPtIn, WtPtInAdapted;
-       VEC3 WtPtOut, WtPtOutAdapted;
-       MAT3 Scale, m1, m2, m3;
-
-       VEC3init(&WtPtIn, WhitePointIn->X, WhitePointIn->Y, WhitePointIn->Z);
-       MAT3eval(&WtPtInAdapted, ChromaticAdaptationMatrixIn, &WtPtIn);
+// This is the entry for black-plane preserving, which are non-ICC. Again, Last profile have to be a output profile
+// to do the trick (no devicelinks allowed at that position)
+static
+cmsPipeline*  BlackPreservingKPlaneIntents(cmsContext     ContextID,
+                                           cmsUInt32Number nProfiles,
+                                           cmsUInt32Number Intents[],
+                                           cmsHPROFILE     hProfiles[],
+                                           cmsBool         BPC[],
+                                           cmsFloat64Number AdaptationStates[],
+                                           cmsUInt32Number dwFlags);
 
-       VEC3init(&WtPtOut, WhitePointOut->X, WhitePointOut->Y, WhitePointOut->Z);
-       MAT3eval(&WtPtOutAdapted, ChromaticAdaptationMatrixOut, &WtPtOut);
-
-       VEC3init(&Scale.v[0], WtPtInAdapted.n[0] / WtPtOutAdapted.n[0], 0, 0);
-       VEC3init(&Scale.v[1], 0, WtPtInAdapted.n[1] / WtPtOutAdapted.n[1], 0);
-       VEC3init(&Scale.v[2], 0, 0, WtPtInAdapted.n[2] / WtPtOutAdapted.n[2]);
+//---------------------------------------------------------------------------------
 
 
-       // Adaptation state
-
-       if (AdaptationState == 1.0) {
-
-           // Observer is fully adapted. Keep chromatic adaptation
-
-           CopyMemory(m, &Scale, sizeof(MAT3));
+// This is a structure holding implementations for all supported intents.
+typedef struct _cms_intents_list {
 
-       }
-       else {
+    cmsUInt32Number Intent;
+    char            Description[256];
+    cmsIntentFn     Link;
+    struct _cms_intents_list*  Next;
 
-            // Observer is not adapted, undo the chromatic adaptation
-            m1 = *ChromaticAdaptationMatrixIn;
-            MAT3inverse(&m1, &m2);
-
-            MAT3per(&m3, &m2, &Scale);
-            MAT3per(m, &m3, ChromaticAdaptationMatrixOut);
-       }
+} cmsIntentsList;
 
 
-       VEC3init(of, 0.0, 0.0, 0.0);
+// Built-in intents
+static cmsIntentsList DefaultIntents[] = {
 
-}
+    { INTENT_PERCEPTUAL,                            "Perceptual",                                   DefaultICCintents,            &DefaultIntents[1] },
+    { INTENT_RELATIVE_COLORIMETRIC,                 "Relative colorimetric",                        DefaultICCintents,            &DefaultIntents[2] },
+    { INTENT_SATURATION,                            "Saturation",                                   DefaultICCintents,            &DefaultIntents[3] },
+    { INTENT_ABSOLUTE_COLORIMETRIC,                 "Absolute colorimetric",                        DefaultICCintents,            &DefaultIntents[4] },
+    { INTENT_PRESERVE_K_ONLY_PERCEPTUAL,            "Perceptual preserving black ink",              BlackPreservingKOnlyIntents,  &DefaultIntents[5] },
+    { INTENT_PRESERVE_K_ONLY_RELATIVE_COLORIMETRIC, "Relative colorimetric preserving black ink",   BlackPreservingKOnlyIntents,  &DefaultIntents[6] },
+    { INTENT_PRESERVE_K_ONLY_SATURATION,            "Saturation preserving black ink",              BlackPreservingKOnlyIntents,  &DefaultIntents[7] },
+    { INTENT_PRESERVE_K_PLANE_PERCEPTUAL,           "Perceptual preserving black plane",            BlackPreservingKPlaneIntents, &DefaultIntents[8] },
+    { INTENT_PRESERVE_K_PLANE_RELATIVE_COLORIMETRIC,"Relative colorimetric preserving black plane", BlackPreservingKPlaneIntents, &DefaultIntents[9] },
+    { INTENT_PRESERVE_K_PLANE_SATURATION,           "Saturation preserving black plane",            BlackPreservingKPlaneIntents, NULL }
+};
 
 
-// The (in)famous black point compensation. Right now implemented as
-// a linear scaling in XYZ
+// A pointer to the begining of the list
+static cmsIntentsList *Intents = DefaultIntents;
 
+// Search the list for a suitable intent. Returns NULL if not found
 static
-void ComputeBlackPointCompensationFactors(LPcmsCIEXYZ BlackPointIn,
-                      LPcmsCIEXYZ WhitePointIn,
-                      LPcmsCIEXYZ IlluminantIn,
-                      LPcmsCIEXYZ BlackPointOut,
-                      LPcmsCIEXYZ WhitePointOut,
-                      LPcmsCIEXYZ IlluminantOut,
-                      LPMAT3 m, LPVEC3 of)
+cmsIntentsList* SearchIntent(cmsUInt32Number Intent)
 {
+    cmsIntentsList* pt;
+
+    for (pt = Intents; pt != NULL; pt = pt -> Next)
+        if (pt ->Intent == Intent) return pt;
+
+    return NULL;
+}
 
-
-   cmsCIEXYZ RelativeBlackPointIn, RelativeBlackPointOut;
-   double ax, ay, az, bx, by, bz, tx, ty, tz;
-
-   // At first, convert both black points to relative.
-
-   cmsAdaptToIlluminant(&RelativeBlackPointIn,  WhitePointIn, IlluminantIn, BlackPointIn);
-   cmsAdaptToIlluminant(&RelativeBlackPointOut, WhitePointOut, IlluminantOut, BlackPointOut);
+// Black point compensation. Implemented as a linear scaling in XYZ. Black points
+// should come relative to the white point. Fills an matrix/offset element m
+// which is organized as a 4x4 matrix.
+static
+void ComputeBlackPointCompensation(const cmsCIEXYZ* BlackPointIn,
+                                   const cmsCIEXYZ* BlackPointOut,
+                                   cmsMAT3* m, cmsVEC3* off)
+{
+  cmsFloat64Number ax, ay, az, bx, by, bz, tx, ty, tz;
 
    // Now we need to compute a matrix plus an offset m and of such of
    // [m]*bpin + off = bpout
@@ -229,438 +169,900 @@
    // a = (bpout - D50) / (bpin - D50)
    // b = - D50* (bpout - bpin) / (bpin - D50)
 
+   tx = BlackPointIn->X - cmsD50_XYZ()->X;
+   ty = BlackPointIn->Y - cmsD50_XYZ()->Y;
+   tz = BlackPointIn->Z - cmsD50_XYZ()->Z;
 
-   tx = RelativeBlackPointIn.X - IlluminantIn ->X;
-   ty = RelativeBlackPointIn.Y - IlluminantIn ->Y;
-   tz = RelativeBlackPointIn.Z - IlluminantIn ->Z;
+   ax = (BlackPointOut->X - cmsD50_XYZ()->X) / tx;
+   ay = (BlackPointOut->Y - cmsD50_XYZ()->Y) / ty;
+   az = (BlackPointOut->Z - cmsD50_XYZ()->Z) / tz;
 
-   ax = (RelativeBlackPointOut.X - IlluminantOut ->X) / tx;
-   ay = (RelativeBlackPointOut.Y - IlluminantOut ->Y) / ty;
-   az = (RelativeBlackPointOut.Z - IlluminantOut ->Z) / tz;
+   bx = - cmsD50_XYZ()-> X * (BlackPointOut->X - BlackPointIn->X) / tx;
+   by = - cmsD50_XYZ()-> Y * (BlackPointOut->Y - BlackPointIn->Y) / ty;
+   bz = - cmsD50_XYZ()-> Z * (BlackPointOut->Z - BlackPointIn->Z) / tz;
 
-   bx = - IlluminantOut -> X * (RelativeBlackPointOut.X - RelativeBlackPointIn.X) / tx;
-   by = - IlluminantOut -> Y * (RelativeBlackPointOut.Y - RelativeBlackPointIn.Y) / ty;
-   bz = - IlluminantOut -> Z * (RelativeBlackPointOut.Z - RelativeBlackPointIn.Z) / tz;
+   _cmsVEC3init(&m ->v[0], ax, 0,  0);
+   _cmsVEC3init(&m ->v[1], 0, ay,  0);
+   _cmsVEC3init(&m ->v[2], 0,  0,  az);
+   _cmsVEC3init(off, bx, by, bz);
+
+}
 
 
-   MAT3identity(m);
+// Approximate a blackbody illuminant based on CHAD information
+static
+cmsFloat64Number CHAD2Temp(const cmsMAT3* Chad)
+{
+    // Convert D50 across CHAD to get the absolute white point
+     cmsVEC3 d, s;
+     cmsCIEXYZ Dest;
+     cmsCIExyY DestChromaticity;
+     cmsFloat64Number TempK;
+
+    s.n[VX] = cmsD50_XYZ() -> X;
+    s.n[VY] = cmsD50_XYZ() -> Y;
+    s.n[VZ] = cmsD50_XYZ() -> Z;
+
+    _cmsMAT3eval(&d, Chad, &s);
+
+    Dest.X = d.n[VX];
+    Dest.Y = d.n[VY];
+    Dest.Z = d.n[VZ];
+
+    cmsXYZ2xyY(&DestChromaticity, &Dest);
+
+    if (!cmsTempFromWhitePoint(&TempK, &DestChromaticity))
+        return -1.0;
+
+    return TempK;
+}
+
+// Compute a CHAD based on a given temperature
+static
+void Temp2CHAD(cmsMAT3* Chad, cmsFloat64Number Temp)
+{
+    cmsCIEXYZ White;
+    cmsCIExyY ChromaticityOfWhite;
+
+    cmsWhitePointFromTemp(&ChromaticityOfWhite, Temp);
+    cmsxyY2XYZ(&White, &ChromaticityOfWhite);
+    _cmsAdaptationMatrix(Chad, NULL, cmsD50_XYZ(), &White);
+
+}
+
+// Join scalings to obtain relative input to absolute and then to relative output.
+// Result is stored in a 3x3 matrix
+static
+cmsBool  ComputeAbsoluteIntent(cmsFloat64Number AdaptationState,
+                               const cmsCIEXYZ* WhitePointIn,
+                               const cmsMAT3* ChromaticAdaptationMatrixIn,
+                               const cmsCIEXYZ* WhitePointOut,
+                               const cmsMAT3* ChromaticAdaptationMatrixOut,
+                               cmsMAT3* m)
+{
+    cmsMAT3 Scale, m1, m2, m3;
 
-   m->v[VX].n[0] = ax;
-   m->v[VY].n[1] = ay;
-   m->v[VZ].n[2] = az;
+    // Adaptation state
+    if (AdaptationState == 1.0) {
+
+        // Observer is fully adapted. Keep chromatic adaptation.
+        // That is the standard V4 behaviour
+        _cmsVEC3init(&m->v[0], WhitePointIn->X / WhitePointOut->X, 0, 0);
+        _cmsVEC3init(&m->v[1], 0, WhitePointIn->Y / WhitePointOut->Y, 0);
+        _cmsVEC3init(&m->v[2], 0, 0, WhitePointIn->Z / WhitePointOut->Z);
+
+    }
+    else  {
+
+        // Incomplete adaptation. This is an advanced feature.
+        _cmsVEC3init(&Scale.v[0], WhitePointIn->X / WhitePointOut->X, 0, 0);
+        _cmsVEC3init(&Scale.v[1], 0,  WhitePointIn->Y / WhitePointOut->Y, 0);
+        _cmsVEC3init(&Scale.v[2], 0, 0,  WhitePointIn->Z / WhitePointOut->Z);
+
+        m1 = *ChromaticAdaptationMatrixIn;
+        if (!_cmsMAT3inverse(&m1, &m2)) return FALSE;
+        _cmsMAT3per(&m3, &m2, &Scale);
+
+        // m3 holds CHAD from input white to D50 times abs. col. scaling
+        if (AdaptationState == 0.0) {
+
+            // Observer is not adapted, undo the chromatic adaptation
+            _cmsMAT3per(m, &m3, ChromaticAdaptationMatrixOut);
 
-   VEC3init(of, bx, by, bz);
+        } else {
+
+            cmsMAT3 MixedCHAD;
+            cmsFloat64Number TempSrc, TempDest, Temp;
+
+            TempSrc  = CHAD2Temp(ChromaticAdaptationMatrixIn);  // K for source white
+            TempDest = CHAD2Temp(ChromaticAdaptationMatrixOut); // K for dest white
+
+            if (TempSrc < 0.0 || TempDest < 0.0) return FALSE; // Something went wrong
+
+            if (_cmsMAT3isIdentity(&Scale) && fabs(TempSrc - TempDest) < 0.01) {
+
+                _cmsMAT3identity(m);
+                return TRUE;
+            }
+
+            Temp = AdaptationState * TempSrc + (1.0 - AdaptationState) * TempDest;
+
+            // Get a CHAD from D50 to whatever output temperature. This replaces output CHAD
+            Temp2CHAD(&MixedCHAD, Temp);
+
+            _cmsMAT3per(m, &m3, &MixedCHAD);
+        }
+
+    }
+    return TRUE;
 
 }
 
-// Return TRUE if both m and of are empy -- "m" being identity and "of" being 0
+// Just to see if m matrix should be applied
+static
+cmsBool IsEmptyLayer(cmsMAT3* m, cmsVEC3* off)
+{
+    cmsFloat64Number diff = 0;
+    cmsMAT3 Ident;
+    int i;
+
+    if (m == NULL && off == NULL) return TRUE;  // NULL is allowed as an empty layer
+    if (m == NULL && off != NULL) return FALSE; // This is an internal error
+
+    _cmsMAT3identity(&Ident);
+
+    for (i=0; i < 3*3; i++)
+        diff += fabs(((cmsFloat64Number*)m)[i] - ((cmsFloat64Number*)&Ident)[i]);
 
+    for (i=0; i < 3; i++)
+        diff += fabs(((cmsFloat64Number*)off)[i]);
+
+
+    return (diff < 0.002);
+}
+
+
+// Compute the conversion layer
 static
-LCMSBOOL IdentityParameters(LPWMAT3 m, LPWVEC3 of)
+cmsBool ComputeConversion(int i, cmsHPROFILE hProfiles[],
+                                 cmsUInt32Number Intent,
+                                 cmsBool BPC,
+                                 cmsFloat64Number AdaptationState,
+                                 cmsMAT3* m, cmsVEC3* off)
 {
-    WVEC3 wv0;
+
+    int k;
+
+    // m  and off are set to identity and this is detected latter on
+    _cmsMAT3identity(m);
+    _cmsVEC3init(off, 0, 0, 0);
+
+    // If intent is abs. colorimetric,
+    if (Intent == INTENT_ABSOLUTE_COLORIMETRIC) {
+
+        cmsCIEXYZ WhitePointIn, WhitePointOut;
+        cmsMAT3 ChromaticAdaptationMatrixIn, ChromaticAdaptationMatrixOut;
+
+        _cmsReadMediaWhitePoint(&WhitePointIn,  hProfiles[i-1]);
+        _cmsReadCHAD(&ChromaticAdaptationMatrixIn, hProfiles[i-1]);
+
+        _cmsReadMediaWhitePoint(&WhitePointOut,  hProfiles[i]);
+        _cmsReadCHAD(&ChromaticAdaptationMatrixOut, hProfiles[i]);
+
+        if (!ComputeAbsoluteIntent(AdaptationState,
+                                  &WhitePointIn,  &ChromaticAdaptationMatrixIn,
+                                  &WhitePointOut, &ChromaticAdaptationMatrixOut, m)) return FALSE;
+
+    }
+    else {
+        // Rest of intents may apply BPC.
+
+        if (BPC) {
+
+            cmsCIEXYZ BlackPointIn, BlackPointOut;
+
+            cmsDetectBlackPoint(&BlackPointIn,  hProfiles[i-1], Intent, 0);
+            cmsDetectBlackPoint(&BlackPointOut, hProfiles[i], Intent, 0);
+
+            // If black points are equal, then do nothing
+            if (BlackPointIn.X != BlackPointOut.X ||
+                BlackPointIn.Y != BlackPointOut.Y ||
+                BlackPointIn.Z != BlackPointOut.Z)
+                    ComputeBlackPointCompensation(&BlackPointIn, &BlackPointOut, m, off);
+        }
+    }
+
+    // Offset should be adjusted because the encoding. We encode XYZ normalized to 0..1.0,
+    // to do that, we divide by MAX_ENCODEABLE_XZY. The conversion stage goes XYZ -> XYZ so
+    // we have first to convert from encoded to XYZ and then convert back to encoded.
+    // y = Mx + Off
+    // x = x'c
+    // y = M x'c + Off
+    // y = y'c; y' = y / c
+    // y' = (Mx'c + Off) /c = Mx' + (Off / c)
+
+    for (k=0; k < 3; k++) {
+        off ->n[k] /= MAX_ENCODEABLE_XYZ;
+    }
+
+    return TRUE;
+}
+
 
-    VEC3initF(&wv0, 0, 0, 0);
+// Add a conversion stage if needed. If a matrix/offset m is given, it applies to XYZ space
+static
+cmsBool AddConversion(cmsPipeline* Result, cmsColorSpaceSignature InPCS, cmsColorSpaceSignature OutPCS, cmsMAT3* m, cmsVEC3* off)
+{
+    cmsFloat64Number* m_as_dbl = (cmsFloat64Number*) m;
+    cmsFloat64Number* off_as_dbl = (cmsFloat64Number*) off;
+
+    // Handle PCS mismatches. A specialized stage is added to the LUT in such case
+    switch (InPCS) {
+
+        case cmsSigXYZData: // Input profile operates in XYZ
+
+            switch (OutPCS) {
+
+            case cmsSigXYZData:  // XYZ -> XYZ
+                if (!IsEmptyLayer(m, off))
+                    cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
+                break;
+
+            case cmsSigLabData:  // XYZ -> Lab
+                if (!IsEmptyLayer(m, off))
+                    cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
+                cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID));
+                break;
+
+            default:
+                return FALSE;   // Colorspace mismatch
+                }
+                break;
+
 
-    if (!MAT3isIdentity(m, 0.00001)) return FALSE;
-    if (!VEC3equal(of, &wv0, 0.00001)) return FALSE;
+        case cmsSigLabData: // Input profile operates in Lab
+
+            switch (OutPCS) {
+
+            case cmsSigXYZData:  // Lab -> XYZ
+
+                cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID));
+                if (!IsEmptyLayer(m, off))
+                    cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
+                break;
+
+            case cmsSigLabData:  // Lab -> Lab
+
+                if (!IsEmptyLayer(m, off)) {
+                    cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID));
+                    cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
+                    cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID));
+                }
+                break;
+
+            default:
+                return FALSE;  // Mismatch
+            }
+            break;
+
+
+            // On colorspaces other than PCS, check for same space
+        default:
+            if (InPCS != OutPCS) return FALSE;
+            break;
+    }
 
     return TRUE;
 }
 
 
-
-
-// ----------------------------------------- Inter PCS conversions
-
-// XYZ to XYZ linear scaling. Aso used on Black point compensation
-
+// Is a given space compatible with another?
 static
-void XYZ2XYZ(WORD In[], WORD Out[], LPWMAT3 m, LPWVEC3 of)
+cmsBool ColorSpaceIsCompatible(cmsColorSpaceSignature a, cmsColorSpaceSignature b)
 {
+    // If they are same, they are compatible.
+    if (a == b) return TRUE;
 
-    WVEC3 a, r;
-
-    a.n[0] = In[0] << 1;
-    a.n[1] = In[1] << 1;
-    a.n[2] = In[2] << 1;
+    // Check for XYZ/Lab. Those spaces are interchangeable as they can be computed one from other.
+    if ((a == cmsSigXYZData) && (b == cmsSigLabData)) return TRUE;
+    if ((a == cmsSigLabData) && (b == cmsSigXYZData)) return TRUE;
 
-    MAT3evalW(&r, m, &a);
-
-    Out[0] = _cmsClampWord((r.n[VX] + of->n[VX]) >> 1);
-    Out[1] = _cmsClampWord((r.n[VY] + of->n[VY]) >> 1);
-    Out[2] = _cmsClampWord((r.n[VZ] + of->n[VZ]) >> 1);
+    return FALSE;
 }
 
 
-// XYZ to Lab, scaling first
-
+// Default handler for ICC-style intents
 static
-void XYZ2Lab(WORD In[], WORD Out[], LPWMAT3 m, LPWVEC3 of)
+cmsPipeline* DefaultICCintents(cmsContext       ContextID,
+                               cmsUInt32Number  nProfiles,
+                               cmsUInt32Number  TheIntents[],
+                               cmsHPROFILE      hProfiles[],
+                               cmsBool          BPC[],
+                               cmsFloat64Number AdaptationStates[],
+                               cmsUInt32Number  dwFlags)
 {
-  WORD XYZ[3];
-
-  XYZ2XYZ(In, XYZ, m, of);
-  cmsXYZ2LabEncoded(XYZ, Out);
-}
-
-// Lab to XYZ, then scalling
-
-static
-void Lab2XYZ(WORD In[], WORD Out[], LPWMAT3 m, LPWVEC3 of)
-{
-       WORD XYZ[3];
-
-       cmsLab2XYZEncoded(In, XYZ);
-       XYZ2XYZ(XYZ, Out, m, of);
-}
+    cmsPipeline* Lut, *Result;
+    cmsHPROFILE hProfile;
+    cmsMAT3 m;
+    cmsVEC3 off;
+    cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut, CurrentColorSpace;
+    cmsProfileClassSignature ClassSig;
+    cmsUInt32Number  i, Intent;
 
-// Lab to XYZ, scalling and then, back to Lab
+    // For safety
+    if (nProfiles == 0) return NULL;
 
-static
-void Lab2XYZ2Lab(WORD In[], WORD Out[], LPWMAT3 m, LPWVEC3 of)
-{
-       WORD XYZ[3], XYZ2[3];
+    // Allocate an empty LUT for holding the result. 0 as channel count means 'undefined'
+    Result = cmsPipelineAlloc(ContextID, 0, 0);
+    if (Result == NULL) return NULL;
 
-       cmsLab2XYZEncoded(In, XYZ);
-       XYZ2XYZ(XYZ, XYZ2, m, of);
-       cmsXYZ2LabEncoded(XYZ2, Out);
-}
+    CurrentColorSpace = cmsGetColorSpace(hProfiles[0]);
 
-// ------------------------------------------------------------------
+    for (i=0; i < nProfiles; i++) {
 
-// Dispatcher for XYZ Relative LUT
+        cmsBool  lIsDeviceLink, lIsInput;
 
-static
-int FromXYZRelLUT(int Absolute,
-                             LPcmsCIEXYZ BlackPointIn,
-                             LPcmsCIEXYZ WhitePointIn,
-                             LPcmsCIEXYZ IlluminantIn,
-                             LPMAT3 ChromaticAdaptationMatrixIn,
+        hProfile      = hProfiles[i];
+        ClassSig      = cmsGetDeviceClass(hProfile);
+        lIsDeviceLink = (ClassSig == cmsSigLinkClass || ClassSig == cmsSigAbstractClass );
 
-                 int Phase2, LPcmsCIEXYZ BlackPointOut,
-                             LPcmsCIEXYZ WhitePointOut,
-                             LPcmsCIEXYZ IlluminantOut,
-                             LPMAT3 ChromaticAdaptationMatrixOut,
-
-                 int DoBlackPointCompensation,
-                 double AdaptationState,
-                 _cmsADJFN *fn1,
-                 LPMAT3 m, LPVEC3 of)
+        // First profile is used as input unless devicelink or abstract
+        if ((i == 0) && !lIsDeviceLink) {
+            lIsInput = TRUE;
+        }
+        else {
+            // Else use profile in the input direction if current space is not PCS
+        lIsInput      = (CurrentColorSpace != cmsSigXYZData) &&
+                        (CurrentColorSpace != cmsSigLabData);
+        }
 
-{
-              switch (Phase2) {
+        Intent        = TheIntents[i];
 
-                     // From relative XYZ to Relative XYZ.
+        if (lIsInput || lIsDeviceLink) {
 
-                     case XYZRel:
+            ColorSpaceIn    = cmsGetColorSpace(hProfile);
+            ColorSpaceOut   = cmsGetPCS(hProfile);
+        }
+        else {
 
-                            if (Absolute)
-                            {
-                                   // From input relative to absolute, and then
-                                   // back to output relative
+            ColorSpaceIn    = cmsGetPCS(hProfile);
+            ColorSpaceOut   = cmsGetColorSpace(hProfile);
+        }
 
-                                   Rel2RelStepAbsCoefs(AdaptationState,
-                                                       BlackPointIn,
-                                                       WhitePointIn,
-                                                       IlluminantIn,
-                                                       ChromaticAdaptationMatrixIn,
-                                                       BlackPointOut,
-                                                       WhitePointOut,
-                                                       IlluminantOut,
-                                                       ChromaticAdaptationMatrixOut,
-                                                       m, of);
-                                   *fn1 = XYZ2XYZ;
+        if (!ColorSpaceIsCompatible(ColorSpaceIn, CurrentColorSpace)) {
+
+            cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "ColorSpace mismatch");
+            goto Error;
+        }
+
+        // If devicelink is found, then no custom intent is allowed and we can
+        // read the LUT to be applied. Settings don't apply here.
+        if (lIsDeviceLink) {
 
-                            }
-                            else
-                            {
-                                   // XYZ Relative to XYZ relative, no op required
-                                   *fn1 = NULL;
-                                   if (DoBlackPointCompensation) {
+            // Get the involved LUT from the profile
+            Lut = _cmsReadDevicelinkLUT(hProfile, Intent);
+            if (Lut == NULL) goto Error;
 
-                                      *fn1 = XYZ2XYZ;
-                                      ComputeBlackPointCompensationFactors(BlackPointIn,
-                                                                      WhitePointIn,
-                                                                      IlluminantIn,
-                                                                      BlackPointOut,
-                                                                      WhitePointOut,
-                                                                      IlluminantOut,
-                                                                      m, of);
-
-                                   }
-                            }
-                            break;
+            // What about abstract profiles?
+             if (ClassSig == cmsSigAbstractClass && i > 0) {
+                if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
+             }
+             else {
+                _cmsMAT3identity(&m);
+                _cmsVEC3init(&off, 0, 0, 0);
+             }
 
 
-                     // From relative XYZ to Relative Lab
-
-                     case LabRel:
-
-                            // First pass XYZ to absolute, then to relative and
-                            // finally to Lab. I use here D50 for output in order
-                            // to prepare the "to Lab" conversion.
-
-                            if (Absolute)
-                            {
+            if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
 
-                                Rel2RelStepAbsCoefs(AdaptationState,
-                                                    BlackPointIn,
-                                                    WhitePointIn,
-                                                    IlluminantIn,
-                                                    ChromaticAdaptationMatrixIn,
-                                                    BlackPointOut,
-                                                    WhitePointOut,
-                                                    IlluminantOut,
-                                                    ChromaticAdaptationMatrixOut,
-                                                    m, of);
+        }
+        else {
 
-                                *fn1 = XYZ2Lab;
-
-                            }
-                            else
-                            {
-                                   // Just Convert to Lab
-
-                                   MAT3identity(m);
-                                   VEC3init(of, 0, 0, 0);
-                                   *fn1 = XYZ2Lab;
+            if (lIsInput) {
+                // Input direction means non-pcs connection, so proceed like devicelinks
+                Lut = _cmsReadInputLUT(hProfile, Intent);
+                if (Lut == NULL) goto Error;
+            }
+            else {
 
-                                   if (DoBlackPointCompensation) {
-
-                                    ComputeBlackPointCompensationFactors(BlackPointIn,
-                                                                          WhitePointIn,
-                                                                          IlluminantIn,
-                                                                          BlackPointOut,
-                                                                          WhitePointOut,
-                                                                          IlluminantOut,
-                                                                          m, of);
-                                   }
-                            }
-                            break;
+                // Output direction means PCS connection. Intent may apply here
+                Lut = _cmsReadOutputLUT(hProfile, Intent);
+                if (Lut == NULL) goto Error;
 
 
-                     default: return FALSE;
-                     }
+                if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
+                if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
+
+            }
+        }
+
+        // Concatenate to the output LUT
+        cmsPipelineCat(Result, Lut);
+        cmsPipelineFree(Lut);
 
-              return TRUE;
+        // Update current space
+        CurrentColorSpace = ColorSpaceOut;
+    }
+
+    return Result;
+
+Error:
+
+    if (Result != NULL) cmsPipelineFree(Result);
+    return NULL;
+
+    cmsUNUSED_PARAMETER(dwFlags);
 }
 
 
+// Wrapper for DLL calling convention
+cmsPipeline*  CMSEXPORT _cmsDefaultICCintents(cmsContext     ContextID,
+                                              cmsUInt32Number nProfiles,
+                                              cmsUInt32Number TheIntents[],
+                                              cmsHPROFILE     hProfiles[],
+                                              cmsBool         BPC[],
+                                              cmsFloat64Number AdaptationStates[],
+                                              cmsUInt32Number dwFlags)
+{
+    return DefaultICCintents(ContextID, nProfiles, TheIntents, hProfiles, BPC, AdaptationStates, dwFlags);
+}
+
+// Black preserving intents ---------------------------------------------------------------------------------------------
+
+// Translate black-preserving intents to ICC ones
+static
+int TranslateNonICCIntents(int Intent)
+{
+    switch (Intent) {
+        case INTENT_PRESERVE_K_ONLY_PERCEPTUAL:
+        case INTENT_PRESERVE_K_PLANE_PERCEPTUAL:
+            return INTENT_PERCEPTUAL;
+
+        case INTENT_PRESERVE_K_ONLY_RELATIVE_COLORIMETRIC:
+        case INTENT_PRESERVE_K_PLANE_RELATIVE_COLORIMETRIC:
+            return INTENT_RELATIVE_COLORIMETRIC;
+
+        case INTENT_PRESERVE_K_ONLY_SATURATION:
+        case INTENT_PRESERVE_K_PLANE_SATURATION:
+            return INTENT_SATURATION;
+
+        default: return Intent;
+    }
+}
+
+// Sampler for Black-only preserving CMYK->CMYK transforms
+
+typedef struct {
+    cmsPipeline*    cmyk2cmyk;      // The original transform
+    cmsToneCurve*   KTone;          // Black-to-black tone curve
+
+} GrayOnlyParams;
+
+
+// Preserve black only if that is the only ink used
+static
+int BlackPreservingGrayOnlySampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
+{
+    GrayOnlyParams* bp = (GrayOnlyParams*) Cargo;
+
+    // If going across black only, keep black only
+    if (In[0] == 0 && In[1] == 0 && In[2] == 0) {
+
+        // TAC does not apply because it is black ink!
+        Out[0] = Out[1] = Out[2] = 0;
+        Out[3] = cmsEvalToneCurve16(bp->KTone, In[3]);
+        return TRUE;
+    }
+
+    // Keep normal transform for other colors
+    bp ->cmyk2cmyk ->Eval16Fn(In, Out, bp ->cmyk2cmyk->Data);
+    return TRUE;
+}
+
+// This is the entry for black-preserving K-only intents, which are non-ICC
+static
+cmsPipeline*  BlackPreservingKOnlyIntents(cmsContext     ContextID,
+                                          cmsUInt32Number nProfiles,
+                                          cmsUInt32Number TheIntents[],
+                                          cmsHPROFILE     hProfiles[],
+                                          cmsBool         BPC[],
+                                          cmsFloat64Number AdaptationStates[],
+                                          cmsUInt32Number dwFlags)
+{
+    GrayOnlyParams  bp;
+    cmsPipeline*    Result;
+    cmsUInt32Number ICCIntents[256];
+    cmsStage*         CLUT;
+    cmsUInt32Number i, nGridPoints;
 
 
-// From Lab Relative type LUT
+    // Sanity check
+    if (nProfiles < 1 || nProfiles > 255) return NULL;
 
-static
-int FromLabRelLUT(int Absolute,
-                             LPcmsCIEXYZ BlackPointIn,
-                             LPcmsCIEXYZ WhitePointIn,
-                             LPcmsCIEXYZ IlluminantIn,
-                             LPMAT3 ChromaticAdaptationMatrixIn,
-
-                 int Phase2, LPcmsCIEXYZ BlackPointOut,
-                             LPcmsCIEXYZ WhitePointOut,
-                             LPcmsCIEXYZ IlluminantOut,
-                             LPMAT3 ChromaticAdaptationMatrixOut,
+    // Translate black-preserving intents to ICC ones
+    for (i=0; i < nProfiles; i++)
+        ICCIntents[i] = TranslateNonICCIntents(TheIntents[i]);
 
-                int DoBlackPointCompensation,
-                double AdaptationState,
-
-                 _cmsADJFN *fn1,
-                 LPMAT3 m, LPVEC3 of)
-{
-
-          switch (Phase2) {
+    // Check for non-cmyk profiles
+    if (cmsGetColorSpace(hProfiles[0]) != cmsSigCmykData ||
+        cmsGetColorSpace(hProfiles[nProfiles-1]) != cmsSigCmykData)
+           return DefaultICCintents(ContextID, nProfiles, ICCIntents, hProfiles, BPC, AdaptationStates, dwFlags);
 
-              // From Lab Relative to XYZ Relative, very usual case
-
-              case XYZRel:
+    memset(&bp, 0, sizeof(bp));
 
-                  if (Absolute) {  // Absolute intent
-
-                            // From lab relative, to XYZ absolute, and then,
-                            // back to XYZ relative
+    // Allocate an empty LUT for holding the result
+    Result = cmsPipelineAlloc(ContextID, 4, 4);
+    if (Result == NULL) return NULL;
 
-                            Rel2RelStepAbsCoefs(AdaptationState,
-                                                BlackPointIn,
-                                                WhitePointIn,
-                                                cmsD50_XYZ(),
-                                                ChromaticAdaptationMatrixIn,
-                                                BlackPointOut,
-                                                WhitePointOut,
-                                                IlluminantOut,
-                                                ChromaticAdaptationMatrixOut,
-                                                m, of);
+    // Create a LUT holding normal ICC transform
+    bp.cmyk2cmyk = DefaultICCintents(ContextID,
+        nProfiles,
+        ICCIntents,
+        hProfiles,
+        BPC,
+        AdaptationStates,
+        dwFlags);
 
-                            *fn1 = Lab2XYZ;
+    if (bp.cmyk2cmyk == NULL) goto Error;
 
-                     }
-                     else
-                     {
-                            // From Lab relative, to XYZ relative.
-
-                            *fn1 = Lab2XYZ;
-                            if (DoBlackPointCompensation) {
+    // Now, compute the tone curve
+    bp.KTone = _cmsBuildKToneCurve(ContextID,
+        4096,
+        nProfiles,
+        ICCIntents,
+        hProfiles,
+        BPC,
+        AdaptationStates,
+        dwFlags);
 
-                                 ComputeBlackPointCompensationFactors(BlackPointIn,
-                                                                      WhitePointIn,
-                                                                      IlluminantIn,
-                                                                      BlackPointOut,
-                                                                      WhitePointOut,
-                                                                      IlluminantOut,
-                                                                      m, of);
-
-                            }
-                     }
-                     break;
+    if (bp.KTone == NULL) goto Error;
 
 
+    // How many gridpoints are we going to use?
+    nGridPoints = _cmsReasonableGridpointsByColorspace(cmsSigCmykData, dwFlags);
 
-              case LabRel:
+    // Create the CLUT. 16 bits
+    CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, 4, 4, NULL);
+    if (CLUT == NULL) goto Error;
+
+    // This is the one and only MPE in this LUT
+    cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT);
 
-                     if (Absolute) {
+    // Sample it. We cannot afford pre/post linearization this time.
+    if (!cmsStageSampleCLut16bit(CLUT, BlackPreservingGrayOnlySampler, (void*) &bp, 0))
+        goto Error;
 
-                             // First pass to XYZ using the input illuminant
-                             // * InIlluminant / D50, then to absolute. Then
-                             // to relative, but for input
+    // Get rid of xform and tone curve
+    cmsPipelineFree(bp.cmyk2cmyk);
+    cmsFreeToneCurve(bp.KTone);
+
+    return Result;
 
-                             Rel2RelStepAbsCoefs(AdaptationState,
-                                                 BlackPointIn,
-                                                 WhitePointIn, IlluminantIn,
-                                                 ChromaticAdaptationMatrixIn,
-                                                 BlackPointOut,
-                                                 WhitePointOut, cmsD50_XYZ(),
-                                                 ChromaticAdaptationMatrixOut,
-                                                 m, of);
-                             *fn1 = Lab2XYZ2Lab;
-                     }
-                     else
-                     {      // Lab -> Lab relative don't need any adjust unless
-                            // black point compensation
+Error:
+
+    if (bp.cmyk2cmyk != NULL) cmsPipelineFree(bp.cmyk2cmyk);
+    if (bp.KTone != NULL)  cmsFreeToneCurve(bp.KTone);
+    if (Result != NULL) cmsPipelineFree(Result);
+    return NULL;
+
+}
+
+// K Plane-preserving CMYK to CMYK ------------------------------------------------------------------------------------
 
-                            *fn1 = NULL;
-                             if (DoBlackPointCompensation) {
+typedef struct {
 
-                                 *fn1 = Lab2XYZ2Lab;
-                                 ComputeBlackPointCompensationFactors(BlackPointIn,
-                                                                      WhitePointIn,
-                                                                      IlluminantIn,
-                                                                      BlackPointOut,
-                                                                      WhitePointOut,
-                                                                      IlluminantOut,
-                                                                      m, of);
+    cmsPipeline*     cmyk2cmyk;     // The original transform
+    cmsHTRANSFORM    hProofOutput;  // Output CMYK to Lab (last profile)
+    cmsHTRANSFORM    cmyk2Lab;      // The input chain
+    cmsToneCurve*    KTone;         // Black-to-black tone curve
+    cmsPipeline*     LabK2cmyk;     // The output profile
+    cmsFloat64Number MaxError;
+
+    cmsHTRANSFORM    hRoundTrip;
+    cmsFloat64Number MaxTAC;
 
 
-                            }
-                     }
-                     break;
+} PreserveKPlaneParams;
 
 
-              default: return FALSE;
-              }
+// The CLUT will be stored at 16 bits, but calculations are performed at cmsFloat32Number precision
+static
+int BlackPreservingSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
+{
+    int i;
+    cmsFloat32Number Inf[4], Outf[4];
+    cmsFloat32Number LabK[4];
+    cmsFloat64Number SumCMY, SumCMYK, Error, Ratio;
+    cmsCIELab ColorimetricLab, BlackPreservingLab;
+    PreserveKPlaneParams* bp = (PreserveKPlaneParams*) Cargo;
+
+    // Convert from 16 bits to floating point
+    for (i=0; i < 4; i++)
+        Inf[i] = (cmsFloat32Number) (In[i] / 65535.0);
+
+    // Get the K across Tone curve
+    LabK[3] = cmsEvalToneCurveFloat(bp ->KTone, Inf[3]);
+
+    // If going across black only, keep black only
+    if (In[0] == 0 && In[1] == 0 && In[2] == 0) {
+
+        Out[0] = Out[1] = Out[2] = 0;
+        Out[3] = _cmsQuickSaturateWord(LabK[3] * 65535.0);
+        return TRUE;
+    }
+
+    // Try the original transform,
+    cmsPipelineEvalFloat( Inf, Outf, bp ->cmyk2cmyk);
+
+    // Store a copy of the floating point result into 16-bit
+    for (i=0; i < 4; i++)
+            Out[i] = _cmsQuickSaturateWord(Outf[i] * 65535.0);
+
+    // Maybe K is already ok (mostly on K=0)
+    if ( fabs(Outf[3] - LabK[3]) < (3.0 / 65535.0) ) {
+        return TRUE;
+    }
+
+    // K differ, mesure and keep Lab measurement for further usage
+    // this is done in relative colorimetric intent
+    cmsDoTransform(bp->hProofOutput, Out, &ColorimetricLab, 1);
 
-   return TRUE;
+    // Is not black only and the transform doesn't keep black.
+    // Obtain the Lab of output CMYK. After that we have Lab + K
+    cmsDoTransform(bp ->cmyk2Lab, Outf, LabK, 1);
+
+    // Obtain the corresponding CMY using reverse interpolation
+    // (K is fixed in LabK[3])
+    if (!cmsPipelineEvalReverseFloat(LabK, Outf, Outf, bp ->LabK2cmyk)) {
+
+        // Cannot find a suitable value, so use colorimetric xform
+        // which is already stored in Out[]
+        return TRUE;
+    }
+
+    // Make sure to pass thru K (which now is fixed)
+    Outf[3] = LabK[3];
+
+    // Apply TAC if needed
+    SumCMY   = Outf[0]  + Outf[1] + Outf[2];
+    SumCMYK  = SumCMY + Outf[3];
+
+    if (SumCMYK > bp ->MaxTAC) {
+
+        Ratio = 1 - ((SumCMYK - bp->MaxTAC) / SumCMY);
+        if (Ratio < 0)
+            Ratio = 0;
+    }
+    else
+       Ratio = 1.0;
+
+    Out[0] = _cmsQuickSaturateWord(Outf[0] * Ratio * 65535.0);     // C
+    Out[1] = _cmsQuickSaturateWord(Outf[1] * Ratio * 65535.0);     // M
+    Out[2] = _cmsQuickSaturateWord(Outf[2] * Ratio * 65535.0);     // Y
+    Out[3] = _cmsQuickSaturateWord(Outf[3] * 65535.0);
+
+    // Estimate the error (this goes 16 bits to Lab DBL)
+    cmsDoTransform(bp->hProofOutput, Out, &BlackPreservingLab, 1);
+    Error = cmsDeltaE(&ColorimetricLab, &BlackPreservingLab);
+    if (Error > bp -> MaxError)
+        bp->MaxError = Error;
+
+    return TRUE;
 }
 
+// This is the entry for black-plane preserving, which are non-ICC
+static
+cmsPipeline* BlackPreservingKPlaneIntents(cmsContext     ContextID,
+                                          cmsUInt32Number nProfiles,
+                                          cmsUInt32Number TheIntents[],
+                                          cmsHPROFILE     hProfiles[],
+                                          cmsBool         BPC[],
+                                          cmsFloat64Number AdaptationStates[],
+                                          cmsUInt32Number dwFlags)
+{
+    PreserveKPlaneParams bp;
+    cmsPipeline*    Result = NULL;
+    cmsUInt32Number ICCIntents[256];
+    cmsStage*         CLUT;
+    cmsUInt32Number i, nGridPoints;
+    cmsHPROFILE hLab;
 
-// This function does calculate the necessary conversion operations
-// needed from transpassing data from a LUT to a LUT. The conversion
-// is modeled as a pointer of function and two coefficients, a and b
-// The function is actually called only if not null pointer is provided,
-// and the two paramaters are passed in. There are several types of
-// conversions, but basically they do a linear scalling and a interchange
+    // Sanity check
+    if (nProfiles < 1 || nProfiles > 255) return NULL;
+
+    // Translate black-preserving intents to ICC ones
+    for (i=0; i < nProfiles; i++)
+        ICCIntents[i] = TranslateNonICCIntents(TheIntents[i]);
 
+    // Check for non-cmyk profiles
+    if (cmsGetColorSpace(hProfiles[0]) != cmsSigCmykData ||
+        cmsGetColorSpace(hProfiles[nProfiles-1]) != cmsSigCmykData)
+           return  DefaultICCintents(ContextID, nProfiles, ICCIntents, hProfiles, BPC, AdaptationStates, dwFlags);
+
+    // Allocate an empty LUT for holding the result
+    Result = cmsPipelineAlloc(ContextID, 4, 4);
+    if (Result == NULL) return NULL;
 
 
-// Main dispatcher
+    memset(&bp, 0, sizeof(bp));
 
-int cmsChooseCnvrt(int Absolute,
-                  int Phase1, LPcmsCIEXYZ BlackPointIn,
-                              LPcmsCIEXYZ WhitePointIn,
-                              LPcmsCIEXYZ IlluminantIn,
-                              LPMAT3 ChromaticAdaptationMatrixIn,
+    // We need the input LUT of the last profile, assuming this one is responsible of
+    // black generation. This LUT will be seached in inverse order.
+    bp.LabK2cmyk = _cmsReadInputLUT(hProfiles[nProfiles-1], INTENT_RELATIVE_COLORIMETRIC);
+    if (bp.LabK2cmyk == NULL) goto Cleanup;
+
+    // Get total area coverage (in 0..1 domain)
+    bp.MaxTAC = cmsDetectTAC(hProfiles[nProfiles-1]) / 100.0;
 
-                  int Phase2, LPcmsCIEXYZ BlackPointOut,
-                              LPcmsCIEXYZ WhitePointOut,
-                              LPcmsCIEXYZ IlluminantOut,
-                              LPMAT3 ChromaticAdaptationMatrixOut,
+    // Create a LUT holding normal ICC transform
+    bp.cmyk2cmyk = DefaultICCintents(ContextID,
+                                         nProfiles,
+                                         ICCIntents,
+                                         hProfiles,
+                                         BPC,
+                                         AdaptationStates,
+                                         dwFlags);
 
-                  int DoBlackPointCompensation,
-                  double AdaptationState,
-                  _cmsADJFN *fn1,
-                  LPWMAT3 wm, LPWVEC3 wof)
-{
-
-       int rc;
-       MAT3 m;
-       VEC3 of;
+    // Now the tone curve
+    bp.KTone = _cmsBuildKToneCurve(ContextID, 4096, nProfiles,
+                                   ICCIntents,
+                                   hProfiles,
+                                   BPC,
+                                   AdaptationStates,
+                                   dwFlags);
 
 
-       MAT3identity(&m);
-       VEC3init(&of, 0, 0, 0);
-
-       switch (Phase1) {
-
-       // Input LUT is giving XYZ relative values.
+    // To measure the output, Last profile to Lab
+    hLab = cmsCreateLab4ProfileTHR(ContextID, NULL);
+    bp.hProofOutput = cmsCreateTransformTHR(ContextID, hProfiles[nProfiles-1],
+                                         CHANNELS_SH(4)|BYTES_SH(2), hLab, TYPE_Lab_DBL,
+                                         INTENT_RELATIVE_COLORIMETRIC,
+                                         cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);
 
-       case XYZRel:  rc = FromXYZRelLUT(Absolute,
-                                          BlackPointIn,
-                                          WhitePointIn,
-                                          IlluminantIn,
-                                          ChromaticAdaptationMatrixIn,
-                                          Phase2,
-                                          BlackPointOut,
-                                          WhitePointOut,
-                                          IlluminantOut,
-                                          ChromaticAdaptationMatrixOut,
-                                          DoBlackPointCompensation,
-                                          AdaptationState,
-                                          fn1, &m, &of);
-                     break;
+    // Same as anterior, but lab in the 0..1 range
+    bp.cmyk2Lab = cmsCreateTransformTHR(ContextID, hProfiles[nProfiles-1],
+                                         FLOAT_SH(1)|CHANNELS_SH(4)|BYTES_SH(4), hLab,
+                                         FLOAT_SH(1)|CHANNELS_SH(3)|BYTES_SH(4),
+                                         INTENT_RELATIVE_COLORIMETRIC,
+                                         cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);
+    cmsCloseProfile(hLab);
 
+    // Error estimation (for debug only)
+    bp.MaxError = 0;
+
+    // How many gridpoints are we going to use?
+    nGridPoints = _cmsReasonableGridpointsByColorspace(cmsSigCmykData, dwFlags);
 
 
-       // Input LUT is giving Lab relative values
+    CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, 4, 4, NULL);
+    if (CLUT == NULL) goto Cleanup;
 
-       case LabRel:  rc =  FromLabRelLUT(Absolute,
-                                          BlackPointIn,
-                                          WhitePointIn,
-                                          IlluminantIn,
-                                          ChromaticAdaptationMatrixIn,
-                                          Phase2,
-                                          BlackPointOut,
-                                          WhitePointOut,
-                                          IlluminantOut,
-                                          ChromaticAdaptationMatrixOut,
-                                          DoBlackPointCompensation,
-                                          AdaptationState,
-                                          fn1, &m, &of);
-                     break;
+    cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT);
 
+    cmsStageSampleCLut16bit(CLUT, BlackPreservingSampler, (void*) &bp, 0);
 
-
+Cleanup:
 
-       // Unrecognized combination
-
-       default:    cmsSignalError(LCMS_ERRC_ABORTED, "(internal) Phase error");
-                   return FALSE;
-
-       }
-
-       MAT3toFix(wm, &m);
-       VEC3toFix(wof, &of);
+    if (bp.cmyk2cmyk) cmsPipelineFree(bp.cmyk2cmyk);
+    if (bp.cmyk2Lab) cmsDeleteTransform(bp.cmyk2Lab);
+    if (bp.hProofOutput) cmsDeleteTransform(bp.hProofOutput);
 
-       // Do some optimization -- discard conversion if identity parameters.
-
-       if (*fn1 == XYZ2XYZ || *fn1 == Lab2XYZ2Lab) {
+    if (bp.KTone) cmsFreeToneCurve(bp.KTone);
+    if (bp.LabK2cmyk) cmsPipelineFree(bp.LabK2cmyk);
 
-           if (IdentityParameters(wm, wof))
-               *fn1 = NULL;
-       }
-
-
-       return rc;
+    return Result;
 }
 
+// Link routines ------------------------------------------------------------------------------------------------------
 
+// Chain several profiles into a single LUT. It just checks the parameters and then calls the handler
+// for the first intent in chain. The handler may be user-defined. Is up to the handler to deal with the
+// rest of intents in chain. A maximum of 255 profiles at time are supported, which is pretty reasonable.
+cmsPipeline* _cmsLinkProfiles(cmsContext     ContextID,
+                              cmsUInt32Number nProfiles,
+                              cmsUInt32Number TheIntents[],
+                              cmsHPROFILE     hProfiles[],
+                              cmsBool         BPC[],
+                              cmsFloat64Number AdaptationStates[],
+                              cmsUInt32Number dwFlags)
+{
+    cmsUInt32Number i;
+    cmsIntentsList* Intent;
 
+    // Make sure a reasonable number of profiles is provided
+    if (nProfiles <= 0 || nProfiles > 255) {
+         cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't link '%d' profiles", nProfiles);
+        return NULL;
+    }
+
+    for (i=0; i < nProfiles; i++) {
+
+        // Check if black point is really needed or allowed. Note that
+        // following Adobe's document:
+        // BPC does not apply to devicelink profiles, nor to abs colorimetric,
+        // and applies always on V4 perceptual and saturation.
+
+        if (TheIntents[i] == INTENT_ABSOLUTE_COLORIMETRIC)
+            BPC[i] = FALSE;
+
+        if (TheIntents[i] == INTENT_PERCEPTUAL || TheIntents[i] == INTENT_SATURATION) {
+
+            // Force BPC for V4 profiles in perceptual and saturation
+            if (cmsGetProfileVersion(hProfiles[i]) >= 4.0)
+                BPC[i] = TRUE;
+        }
+    }
+
+    // Search for a handler. The first intent in the chain defines the handler. That would
+    // prevent using multiple custom intents in a multiintent chain, but the behaviour of
+    // this case would present some issues if the custom intent tries to do things like
+    // preserve primaries. This solution is not perfect, but works well on most cases.
+
+    Intent = SearchIntent(TheIntents[0]);
+    if (Intent == NULL) {
+        cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported intent '%d'", TheIntents[0]);
+        return NULL;
+    }
+
+    // Call the handler
+    return Intent ->Link(ContextID, nProfiles, TheIntents, hProfiles, BPC, AdaptationStates, dwFlags);
+}
+
+// -------------------------------------------------------------------------------------------------
+
+// Get information about available intents. nMax is the maximum space for the supplied "Codes"
+// and "Descriptions" the function returns the total number of intents, which may be greater
+// than nMax, although the matrices are not populated beyond this level.
+cmsUInt32Number CMSEXPORT cmsGetSupportedIntents(cmsUInt32Number nMax, cmsUInt32Number* Codes, char** Descriptions)
+{
+    cmsIntentsList* pt;
+    cmsUInt32Number nIntents;
+
+    for (nIntents=0, pt = Intents; pt != NULL; pt = pt -> Next)
+    {
+        if (nIntents < nMax) {
+            if (Codes != NULL)
+                Codes[nIntents] = pt ->Intent;
+
+            if (Descriptions != NULL)
+                Descriptions[nIntents] = pt ->Description;
+        }
+
+        nIntents++;
+    }
+
+    return nIntents;
+}
+
+// The plug-in registration. User can add new intents or override default routines
+cmsBool  _cmsRegisterRenderingIntentPlugin(cmsPluginBase* Data)
+{
+    cmsPluginRenderingIntent* Plugin = (cmsPluginRenderingIntent*) Data;
+    cmsIntentsList* fl;
+
+    // Do we have to reset the intents?
+    if (Data == NULL) {
+
+       Intents = DefaultIntents;
+       return TRUE;
+    }
+
+    fl = SearchIntent(Plugin ->Intent);
+
+    if (fl == NULL) {
+        fl = (cmsIntentsList*) _cmsPluginMalloc(sizeof(cmsIntentsList));
+        if (fl == NULL) return FALSE;
+    }
+
+    fl ->Intent  = Plugin ->Intent;
+    strncpy(fl ->Description, Plugin ->Description, 255);
+    fl ->Description[255] = 0;
+
+    fl ->Link    = Plugin ->Link;
+
+    fl ->Next = Intents;
+    Intents = fl;
+
+    return TRUE;
+}
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmserr.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmserr.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,92 +49,399 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
 
+#include "lcms2_internal.h"
+
+// I am so tired about incompatibilities on those functions that here are some replacements
+// that hopefully would be fully portable.
+
+// compare two strings ignoring case
+int CMSEXPORT cmsstrcasecmp(const char* s1, const char* s2)
+{
+         register const unsigned char *us1 = (const unsigned char *)s1,
+                                      *us2 = (const unsigned char *)s2;
 
-#include "lcms.h"
+        while (toupper(*us1) == toupper(*us2++))
+                if (*us1++ == '\0')
+                        return (0);
+        return (toupper(*us1) - toupper(*--us2));
+}
 
+// long int because C99 specifies ftell in such way (7.19.9.2)
+long int CMSEXPORT cmsfilelength(FILE* f)
+{
+    long int n;
+
+    if (fseek(f, 0, SEEK_END) != 0) {
+        return -1;
+    }
+    n = ftell(f);
+    fseek(f, 0, SEEK_SET);
+
+    return n;
+}
 
-// As a rule, only the functions visible from API can signal
-// errors.
+// Memory handling ------------------------------------------------------------------
+//
+// This is the interface to low-level memory management routines. By default a simple
+// wrapping to malloc/free/realloc is provided, although there is a limit on the max
+// amount of memoy that can be reclaimed. This is mostly as a safety feature to
+// prevent bogus or malintentionated code to allocate huge blocks that otherwise lcms
+// would never need.
+
+#define MAX_MEMORY_FOR_ALLOC  ((cmsUInt32Number)(1024U*1024U*512U))
+
+// User may override this behaviour by using a memory plug-in, which basically replaces
+// the default memory management functions. In this case, no check is performed and it
+// is up to the plug-in writter to keep in the safe side. There are only three functions
+// required to be implemented: malloc, realloc and free, although the user may want to
+// replace the optional mallocZero, calloc and dup as well.
+
+cmsBool   _cmsRegisterMemHandlerPlugin(cmsPluginBase* Plugin);
+
+// *********************************************************************************
 
-void cdecl cmsSignalError(int ErrorCode, const char *ErrorText, ...);
+// This is the default memory allocation function. It does a very coarse
+// check of amout of memory, just to prevent exploits
+static
+void* _cmsMallocDefaultFn(cmsContext ContextID, cmsUInt32Number size)
+{
+    if (size > MAX_MEMORY_FOR_ALLOC) return NULL;  // Never allow over maximum
+
+    return (void*) malloc(size);
 
-int  LCMSEXPORT cmsErrorAction(int lAbort);
-void LCMSEXPORT cmsSetErrorHandler(cmsErrorHandlerFunction Fn);
+    cmsUNUSED_PARAMETER(ContextID);
+}
+
+// Generic allocate & zero
+static
+void* _cmsMallocZeroDefaultFn(cmsContext ContextID, cmsUInt32Number size)
+{
+    void *pt = _cmsMalloc(ContextID, size);
+    if (pt == NULL) return NULL;
+
+    memset(pt, 0, size);
+    return pt;
+}
 
 
-// ******************************************************************
-
-static int nDoAbort = LCMS_ERROR_ABORT;
-static cmsErrorHandlerFunction UserErrorHandler = (cmsErrorHandlerFunction) NULL;
-
+// The default free function. The only check proformed is against NULL pointers
+static
+void _cmsFreeDefaultFn(cmsContext ContextID, void *Ptr)
+{
+    // free(NULL) is defined a no-op by C99, therefore it is safe to
+    // avoid the check, but it is here just in case...
 
-int LCMSEXPORT cmsErrorAction(int nAction)
-{
-       int nOld = nDoAbort;
-       nDoAbort = nAction;
+    if (Ptr) free(Ptr);
 
-       return nOld;
+    cmsUNUSED_PARAMETER(ContextID);
 }
 
-void LCMSEXPORT cmsSetErrorHandler(cmsErrorHandlerFunction Fn)
+// The default realloc function. Again it check for exploits. If Ptr is NULL,
+// realloc behaves the same way as malloc and allocates a new block of size bytes.
+static
+void* _cmsReallocDefaultFn(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
 {
-       UserErrorHandler = Fn;
+
+    if (size > MAX_MEMORY_FOR_ALLOC) return NULL;  // Never realloc over 512Mb
+
+    return realloc(Ptr, size);
+
+    cmsUNUSED_PARAMETER(ContextID);
 }
 
 
-// Default error handler
+// The default calloc function. Allocates an array of num elements, each one of size bytes
+// all memory is initialized to zero.
+static
+void* _cmsCallocDefaultFn(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)
+{
+    cmsUInt32Number Total = num * size;
+
+    // Check for overflow
+    if (Total < num || Total < size) {
+        return NULL;
+    }
+
+    if (Total > MAX_MEMORY_FOR_ALLOC) return NULL;  // Never alloc over 512Mb
+
+    return _cmsMallocZero(ContextID, Total);
+}
+
+// Generic block duplication
+static
+void* _cmsDupDefaultFn(cmsContext ContextID, const void* Org, cmsUInt32Number size)
+{
+    void* mem;
+
+    if (size > MAX_MEMORY_FOR_ALLOC) return NULL;  // Never dup over 512Mb
+
+    mem = _cmsMalloc(ContextID, size);
+
+    if (mem != NULL && Org != NULL)
+        memmove(mem, Org, size);
+
+    return mem;
+}
+
+// Pointers to malloc and _cmsFree functions in current environment
+static void * (* MallocPtr)(cmsContext ContextID, cmsUInt32Number size)                     = _cmsMallocDefaultFn;
+static void * (* MallocZeroPtr)(cmsContext ContextID, cmsUInt32Number size)                 = _cmsMallocZeroDefaultFn;
+static void   (* FreePtr)(cmsContext ContextID, void *Ptr)                                  = _cmsFreeDefaultFn;
+static void * (* ReallocPtr)(cmsContext ContextID, void *Ptr, cmsUInt32Number NewSize)      = _cmsReallocDefaultFn;
+static void * (* CallocPtr)(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)= _cmsCallocDefaultFn;
+static void * (* DupPtr)(cmsContext ContextID, const void* Org, cmsUInt32Number size)       = _cmsDupDefaultFn;
+
+// Plug-in replacement entry
+cmsBool  _cmsRegisterMemHandlerPlugin(cmsPluginBase *Data)
+{
+    cmsPluginMemHandler* Plugin = (cmsPluginMemHandler*) Data;
+
+    // NULL forces to reset to defaults
+    if (Data == NULL) {
+
+        MallocPtr    = _cmsMallocDefaultFn;
+        MallocZeroPtr= _cmsMallocZeroDefaultFn;
+        FreePtr      = _cmsFreeDefaultFn;
+        ReallocPtr   = _cmsReallocDefaultFn;
+        CallocPtr    = _cmsCallocDefaultFn;
+        DupPtr       = _cmsDupDefaultFn;
+        return TRUE;
+    }
+
+    // Check for required callbacks
+    if (Plugin -> MallocPtr == NULL ||
+        Plugin -> FreePtr == NULL ||
+        Plugin -> ReallocPtr == NULL) return FALSE;
+
+    // Set replacement functions
+    MallocPtr  = Plugin -> MallocPtr;
+    FreePtr    = Plugin -> FreePtr;
+    ReallocPtr = Plugin -> ReallocPtr;
+
+    if (Plugin ->MallocZeroPtr != NULL) MallocZeroPtr = Plugin ->MallocZeroPtr;
+    if (Plugin ->CallocPtr != NULL)     CallocPtr     = Plugin -> CallocPtr;
+    if (Plugin ->DupPtr != NULL)        DupPtr        = Plugin -> DupPtr;
+
+    return TRUE;
+}
+
+// Generic allocate
+void* CMSEXPORT _cmsMalloc(cmsContext ContextID, cmsUInt32Number size)
+{
+    return MallocPtr(ContextID, size);
+}
+
+// Generic allocate & zero
+void* CMSEXPORT _cmsMallocZero(cmsContext ContextID, cmsUInt32Number size)
+{
+    return MallocZeroPtr(ContextID, size);
+}
+
+// Generic calloc
+void* CMSEXPORT _cmsCalloc(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)
+{
+    return CallocPtr(ContextID, num, size);
+}
+
+// Generic reallocate
+void* CMSEXPORT _cmsRealloc(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
+{
+    return ReallocPtr(ContextID, Ptr, size);
+}
+
+// Generic free memory
+void CMSEXPORT _cmsFree(cmsContext ContextID, void* Ptr)
+{
+    if (Ptr != NULL) FreePtr(ContextID, Ptr);
+}
+
+// Generic block duplication
+void* CMSEXPORT _cmsDupMem(cmsContext ContextID, const void* Org, cmsUInt32Number size)
+{
+    return DupPtr(ContextID, Org, size);
+}
+
+// ********************************************************************************************
+
+// Sub allocation takes care of many pointers of small size. The memory allocated in
+// this way have be freed at once. Next function allocates a single chunk for linked list
+// I prefer this method over realloc due to the big inpact on xput realloc may have if
+// memory is being swapped to disk. This approach is safer (although thats not true on any platform)
+static
+_cmsSubAllocator_chunk* _cmsCreateSubAllocChunk(cmsContext ContextID, cmsUInt32Number Initial)
+{
+    _cmsSubAllocator_chunk* chunk;
+
+    // Create the container
+    chunk = (_cmsSubAllocator_chunk*) _cmsMallocZero(ContextID, sizeof(_cmsSubAllocator_chunk));
+    if (chunk == NULL) return NULL;
+
+    // Initialize values
+    chunk ->Block     = (cmsUInt8Number*) _cmsMalloc(ContextID, Initial);
+    if (chunk ->Block == NULL) {
+
+        // Something went wrong
+        _cmsFree(ContextID, chunk);
+        return NULL;
+    }
+
+    // 20K by default
+    if (Initial == 0)
+        Initial = 20*1024;
+
+    chunk ->BlockSize = Initial;
+    chunk ->Used      = 0;
+    chunk ->next      = NULL;
+
+    return chunk;
+}
+
+// The suballocated is nothing but a pointer to the first element in the list. We also keep
+// the thread ID in this structure.
+_cmsSubAllocator* _cmsCreateSubAlloc(cmsContext ContextID, cmsUInt32Number Initial)
+{
+    _cmsSubAllocator* sub;
+
+    // Create the container
+    sub = (_cmsSubAllocator*) _cmsMallocZero(ContextID, sizeof(_cmsSubAllocator));
+    if (sub == NULL) return NULL;
+
+    sub ->ContextID = ContextID;
+
+    sub ->h = _cmsCreateSubAllocChunk(ContextID, Initial);
+    if (sub ->h == NULL) {
+        _cmsFree(ContextID, sub);
+        return NULL;
+    }
+
+    return sub;
+}
 
 
-void cmsSignalError(int ErrorCode, const char *ErrorText, ...)
+// Get rid of whole linked list
+void _cmsSubAllocDestroy(_cmsSubAllocator* sub)
 {
-       va_list args;
+    _cmsSubAllocator_chunk *chunk, *n;
+
+    for (chunk = sub ->h; chunk != NULL; chunk = n) {
+
+        n = chunk->next;
+        if (chunk->Block != NULL) _cmsFree(sub ->ContextID, chunk->Block);
+        _cmsFree(sub ->ContextID, chunk);
+    }
 
-       if (nDoAbort == LCMS_ERROR_IGNORE) return;
+    // Free the header
+    _cmsFree(sub ->ContextID, sub);
+}
+
 
-        va_start(args, ErrorText);
+// Get a pointer to small memory block.
+void*  _cmsSubAlloc(_cmsSubAllocator* sub, cmsUInt32Number size)
+{
+    cmsUInt32Number Free = sub -> h ->BlockSize - sub -> h -> Used;
+    cmsUInt8Number* ptr;
 
-        if (UserErrorHandler != NULL) {
+    size = _cmsALIGNLONG(size);
+
+    // Check for memory. If there is no room, allocate a new chunk of double memory size.
+    if (size > Free) {
 
-            char Buffer[1024];
+        _cmsSubAllocator_chunk* chunk;
+        cmsUInt32Number newSize;
+
+        newSize = sub -> h ->BlockSize * 2;
+        if (newSize < size) newSize = size;
 
-            vsnprintf(Buffer, 1023, ErrorText, args);
-            va_end(args);
+        chunk = _cmsCreateSubAllocChunk(sub -> ContextID, newSize);
+        if (chunk == NULL) return NULL;
+
+        // Link list
+        chunk ->next = sub ->h;
+        sub ->h    = chunk;
+
+    }
 
-            if (UserErrorHandler(ErrorCode, Buffer)) {
+    ptr =  sub -> h ->Block + sub -> h ->Used;
+    sub -> h -> Used += size;
+
+    return (void*) ptr;
+}
+
+// Error logging ******************************************************************
 
-                return;
-                }
-         }
-
-#if defined( __CONSOLE__ ) || defined( NON_WINDOWS )
+// There is no error handling at all. When a funtion fails, it returns proper value.
+// For example, all create functions does return NULL on failure. Other return FALSE
+// It may be interesting, for the developer, to know why the function is failing.
+// for that reason, lcms2 does offer a logging function. This function does recive
+// a ENGLISH string with some clues on what is going wrong. You can show this
+// info to the end user, or just create some sort of log.
+// The logging function should NOT terminate the program, as this obviously can leave
+// resources. It is the programmer's responsability to check each function return code
+// to make sure it didn't fail.
 
-              fprintf(stderr, "lcms: Error #%d; ", ErrorCode);
-              vfprintf(stderr, ErrorText, args);
-              fprintf(stderr, "\n");
-              va_end(args);
+// Error messages are limited to MAX_ERROR_MESSAGE_LEN
+
+#define MAX_ERROR_MESSAGE_LEN   1024
+
+// ---------------------------------------------------------------------------------------------------------
+
+// This is our default log error
+static void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text);
+
+// The current handler in actual environment
+static cmsLogErrorHandlerFunction LogErrorHandler   = DefaultLogErrorHandlerFunction;
 
-              if (nDoAbort == LCMS_ERROR_ABORT) exit(1);
-#else
-              {
-              char Buffer1[1024];
-              char Buffer2[256];
+// The default error logger does nothing.
+static
+void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text)
+{
+    // fprintf(stderr, "[lcms]: %s\n", Text);
+    // fflush(stderr);
+
+     cmsUNUSED_PARAMETER(ContextID);
+     cmsUNUSED_PARAMETER(ErrorCode);
+     cmsUNUSED_PARAMETER(Text);
+}
 
-              snprintf(Buffer1,  767, "Error #%x; ", ErrorCode);
-              vsnprintf(Buffer2, 255, ErrorText, args);
-              strcat(Buffer1, Buffer2);
-              MessageBox(NULL, Buffer1, "Little cms",
-                                          MB_OK|MB_ICONSTOP|MB_TASKMODAL);
-              va_end(args);
+// Change log error
+void CMSEXPORT cmsSetLogErrorHandler(cmsLogErrorHandlerFunction Fn)
+{
+    if (Fn == NULL)
+        LogErrorHandler = DefaultLogErrorHandlerFunction;
+    else
+        LogErrorHandler = Fn;
+}
 
-              if (nDoAbort == LCMS_ERROR_ABORT) {
+// Log an error
+// ErrorText is a text holding an english description of error.
+void CMSEXPORT cmsSignalError(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *ErrorText, ...)
+{
+    va_list args;
+    char Buffer[MAX_ERROR_MESSAGE_LEN];
+
+    va_start(args, ErrorText);
+    vsnprintf(Buffer, MAX_ERROR_MESSAGE_LEN-1, ErrorText, args);
+    va_end(args);
 
-#ifdef __BORLANDC__
-                    _cexit();
-#endif
+    // Call handler
+    LogErrorHandler(ContextID, ErrorCode, Buffer);
+}
+
+// Utility function to print signatures
+void _cmsTagSignature2String(char String[5], cmsTagSignature sig)
+{
+    cmsUInt32Number be;
 
-                  FatalAppExit(0, "lcms is terminating application");
-              }
-              }
-#endif
+    // Convert to big endian
+    be = _cmsAdjustEndianess32((cmsUInt32Number) sig);
+
+    // Move chars
+    memmove(String, &be, 4);
+
+    // Make sure of terminator
+    String[4] = 0;
 }
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,448 +49,851 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
+//
+//---------------------------------------------------------------------------------
+//
+#include "lcms2_internal.h"
 
-#include "lcms.h"
-
-// Gamma handling.
+// Tone curves are powerful constructs that can contain curves specified in diverse ways.
+// The curve is stored in segments, where each segment can be sampled or specified by parameters.
+// a 16.bit simplification of the *whole* curve is kept for optimization purposes. For float operation,
+// each segment is evaluated separately. Plug-ins may be used to define new parametric schemes,
+// each plug-in may define up to MAX_TYPES_IN_LCMS_PLUGIN functions types. For defining a function,
+// the plug-in should provide the type id, how many parameters each type has, and a pointer to
+// a procedure that evaluates the function. In the case of reverse evaluation, the evaluator will
+// be called with the type id as a negative value, and a sampled version of the reversed curve
+// will be built.
 
-LPGAMMATABLE LCMSEXPORT cmsAllocGamma(int nEntries);
-void         LCMSEXPORT cmsFreeGamma(LPGAMMATABLE Gamma);
-void         LCMSEXPORT cmsFreeGammaTriple(LPGAMMATABLE Gamma[3]);
-LPGAMMATABLE LCMSEXPORT cmsBuildGamma(int nEntries, double Gamma);
-LPGAMMATABLE LCMSEXPORT cmsDupGamma(LPGAMMATABLE Src);
-LPGAMMATABLE LCMSEXPORT cmsReverseGamma(int nResultSamples, LPGAMMATABLE InGamma);
-LPGAMMATABLE LCMSEXPORT cmsBuildParametricGamma(int nEntries, int Type, double Params[]);
-LPGAMMATABLE LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma, LPGAMMATABLE OutGamma);
-LPGAMMATABLE LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma, LPGAMMATABLE OutGamma, int nPoints);
-LCMSBOOL         LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
+// ----------------------------------------------------------------- Implementation
+// Maxim number of nodes
+#define MAX_NODES_IN_CURVE   4097
+#define MINUS_INF            (-1E22F)
+#define PLUS_INF             (+1E22F)
+
+// The list of supported parametric curves
+typedef struct _cmsParametricCurvesCollection_st {
 
-LCMSBOOL         cdecl _cmsSmoothEndpoints(LPWORD Table, int nPoints);
+    int nFunctions;                                     // Number of supported functions in this chunk
+    int FunctionTypes[MAX_TYPES_IN_LCMS_PLUGIN];        // The identification types
+    int ParameterCount[MAX_TYPES_IN_LCMS_PLUGIN];       // Number of parameters for each function
+    cmsParametricCurveEvaluator    Evaluator;           // The evaluator
+
+    struct _cmsParametricCurvesCollection_st* Next; // Next in list
+
+} _cmsParametricCurvesCollection;
 
 
-// Sampled curves
+// This is the default (built-in) evaluator
+static cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R);
 
-LPSAMPLEDCURVE cdecl cmsAllocSampledCurve(int nItems);
-void           cdecl cmsFreeSampledCurve(LPSAMPLEDCURVE p);
-void           cdecl cmsEndpointsOfSampledCurve(LPSAMPLEDCURVE p, double* Min, double* Max);
-void           cdecl cmsClampSampledCurve(LPSAMPLEDCURVE p, double Min, double Max);
-LCMSBOOL       cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
-void           cdecl cmsRescaleSampledCurve(LPSAMPLEDCURVE p, double Min, double Max, int nPoints);
+// The built-in list
+static _cmsParametricCurvesCollection DefaultCurves = {
+    9,                                  // # of curve types
+    { 1, 2, 3, 4, 5, 6, 7, 8, 108 },    // Parametric curve ID
+    { 1, 3, 4, 5, 7, 4, 5, 5, 1 },      // Parameters by type
+    DefaultEvalParametricFn,            // Evaluator
+    NULL                                // Next in chain
+};
+
+// The linked list head
+static _cmsParametricCurvesCollection* ParametricCurves = &DefaultCurves;
+
+// As a way to install new parametric curves
+cmsBool _cmsRegisterParametricCurvesPlugin(cmsPluginBase* Data)
+{
+    cmsPluginParametricCurves* Plugin = (cmsPluginParametricCurves*) Data;
+    _cmsParametricCurvesCollection* fl;
+
+    if (Data == NULL) {
 
-LPSAMPLEDCURVE cdecl cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints);
+          ParametricCurves =  &DefaultCurves;
+          return TRUE;
+    }
 
-double LCMSEXPORT cmsEstimateGamma(LPGAMMATABLE t);
-double LCMSEXPORT cmsEstimateGammaEx(LPWORD GammaTable, int nEntries, double Thereshold);
+    fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(sizeof(_cmsParametricCurvesCollection));
+    if (fl == NULL) return FALSE;
+
+    // Copy the parameters
+    fl ->Evaluator  = Plugin ->Evaluator;
+    fl ->nFunctions = Plugin ->nFunctions;
 
-// ----------------------------------------------------------------------------------------
+    // Make sure no mem overwrites
+    if (fl ->nFunctions > MAX_TYPES_IN_LCMS_PLUGIN)
+        fl ->nFunctions = MAX_TYPES_IN_LCMS_PLUGIN;
 
+    // Copy the data
+    memmove(fl->FunctionTypes,  Plugin ->FunctionTypes,   fl->nFunctions * sizeof(cmsUInt32Number));
+    memmove(fl->ParameterCount, Plugin ->ParameterCount,  fl->nFunctions * sizeof(cmsUInt32Number));
 
-#define MAX_KNOTS   4096
-typedef float vec[MAX_KNOTS+1];
+    // Keep linked list
+    fl ->Next = ParametricCurves;
+    ParametricCurves = fl;
+
+    // All is ok
+    return TRUE;
+}
 
 
-// Ciclic-redundant-check for assuring table is a true representation of parametric curve
-
-// The usual polynomial, which is used for AAL5, FDDI, and probably Ethernet
-#define QUOTIENT 0x04c11db7
-
+// Search in type list, return position or -1 if not found
 static
-unsigned int Crc32(unsigned int result, LPVOID ptr, int len)
+int IsInSet(int Type, _cmsParametricCurvesCollection* c)
 {
-    int          i,j;
-    BYTE         octet;
-    LPBYTE       data = (LPBYTE) ptr;
+    int i;
 
-    for (i=0; i < len; i++) {
+    for (i=0; i < c ->nFunctions; i++)
+        if (abs(Type) == c ->FunctionTypes[i]) return i;
+
+    return -1;
+}
+
 
-        octet = *data++;
-
-        for (j=0; j < 8; j++) {
-
-            if (result & 0x80000000) {
+// Search for the collection which contains a specific type
+static
+_cmsParametricCurvesCollection *GetParametricCurveByType(int Type, int* index)
+{
+    _cmsParametricCurvesCollection* c;
+    int Position;
 
-                result = (result << 1) ^ QUOTIENT ^ (octet >> 7);
-            }
-            else
-            {
-                result = (result << 1) ^ (octet >> 7);
-            }
-            octet <<= 1;
+    for (c = ParametricCurves; c != NULL; c = c ->Next) {
+
+        Position = IsInSet(Type, c);
+
+        if (Position != -1) {
+            if (index != NULL)
+                *index = Position;
+            return c;
         }
     }
 
-    return result;
+    return NULL;
 }
 
-// Get CRC of gamma table
+// Low level allocate, which takes care of memory details. nEntries may be zero, and in this case
+// no optimation curve is computed. nSegments may also be zero in the inverse case, where only the
+// optimization curve is given. Both features simultaneously is an error
+static
+cmsToneCurve* AllocateToneCurveStruct(cmsContext ContextID, cmsInt32Number nEntries,
+                                      cmsInt32Number nSegments, const cmsCurveSegment* Segments,
+                                      const cmsUInt16Number* Values)
+{
+    cmsToneCurve* p;
+    int i;
+
+    // We allow huge tables, which are then restricted for smoothing operations
+    if (nEntries > 65530 || nEntries < 0) {
+        cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve of more than 65530 entries");
+        return NULL;
+    }
 
-unsigned int _cmsCrc32OfGammaTable(LPGAMMATABLE Table)
-{
-    unsigned int crc = ~0U;
+    if (nEntries <= 0 && nSegments <= 0) {
+        cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve with zero segments and no table");
+        return NULL;
+    }
+
+    // Allocate all required pointers, etc.
+    p = (cmsToneCurve*) _cmsMallocZero(ContextID, sizeof(cmsToneCurve));
+    if (!p) return NULL;
+
+    // In this case, there are no segments
+    if (nSegments <= 0) {
+        p ->Segments = NULL;
+        p ->Evals = NULL;
+    }
+    else {
+        p ->Segments = (cmsCurveSegment*) _cmsCalloc(ContextID, nSegments, sizeof(cmsCurveSegment));
+        if (p ->Segments == NULL) goto Error;
+
+        p ->Evals    = (cmsParametricCurveEvaluator*) _cmsCalloc(ContextID, nSegments, sizeof(cmsParametricCurveEvaluator));
+        if (p ->Evals == NULL) goto Error;
+    }
+
+    p -> nSegments = nSegments;
 
-    crc = Crc32(crc, &Table -> Seed.Type,  sizeof(int));
-    crc = Crc32(crc, Table ->Seed.Params,  sizeof(double)*10);
-    crc = Crc32(crc, &Table ->nEntries,    sizeof(int));
-    crc = Crc32(crc, Table ->GammaTable,   sizeof(WORD) * Table -> nEntries);
+    // This 16-bit table contains a limited precision representation of the whole curve and is kept for
+    // increasing xput on certain operations.
+    if (nEntries <= 0) {
+        p ->Table16 = NULL;
+    }
+    else {
+       p ->Table16 = (cmsUInt16Number*)  _cmsCalloc(ContextID, nEntries, sizeof(cmsUInt16Number));
+       if (p ->Table16 == NULL) goto Error;
+    }
+
+    p -> nEntries  = nEntries;
+
+    // Initialize members if requested
+    if (Values != NULL && (nEntries > 0)) {
+
+        for (i=0; i < nEntries; i++)
+            p ->Table16[i] = Values[i];
+    }
+
+    // Initialize the segments stuff. The evaluator for each segment is located and a pointer to it
+    // is placed in advance to maximize performance.
+    if (Segments != NULL && (nSegments > 0)) {
+
+        _cmsParametricCurvesCollection *c;
+
+        p ->SegInterp = (cmsInterpParams**) _cmsCalloc(ContextID, nSegments, sizeof(cmsInterpParams*));
+        if (p ->SegInterp == NULL) goto Error;
 
-    return ~crc;
+        for (i=0; i< nSegments; i++) {
+
+            // Type 0 is a special marker for table-based curves
+            if (Segments[i].Type == 0)
+                p ->SegInterp[i] = _cmsComputeInterpParams(ContextID, Segments[i].nGridPoints, 1, 1, NULL, CMS_LERP_FLAGS_FLOAT);
+
+            memmove(&p ->Segments[i], &Segments[i], sizeof(cmsCurveSegment));
+
+            if (Segments[i].Type == 0 && Segments[i].SampledPoints != NULL)
+                p ->Segments[i].SampledPoints = (cmsFloat32Number*) _cmsDupMem(ContextID, Segments[i].SampledPoints, sizeof(cmsFloat32Number) * Segments[i].nGridPoints);
+            else
+                p ->Segments[i].SampledPoints = NULL;
+
 
+            c = GetParametricCurveByType(Segments[i].Type, NULL);
+            if (c != NULL)
+                    p ->Evals[i] = c ->Evaluator;
+        }
+    }
+
+    p ->InterpParams = _cmsComputeInterpParams(ContextID, p ->nEntries, 1, 1, p->Table16, CMS_LERP_FLAGS_16BITS);
+    return p;
+
+Error:
+    if (p -> Segments) _cmsFree(ContextID, p ->Segments);
+    if (p -> Evals) _cmsFree(ContextID, p -> Evals);
+    if (p ->Table16) _cmsFree(ContextID, p ->Table16);
+    _cmsFree(ContextID, p);
+    return NULL;
 }
 
 
-LPGAMMATABLE LCMSEXPORT cmsAllocGamma(int nEntries)
+// Parametric Fn using floating point
+static
+cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R)
 {
-       LPGAMMATABLE p;
-       size_t size;
+    cmsFloat64Number e, Val, disc;
+
+    switch (Type) {
+
+    // X = Y ^ Gamma
+    case 1:
+        if (R < 0)
+            Val = 0;
+        else
+            Val = pow(R, Params[0]);
+        break;
+
+    // Type 1 Reversed: X = Y ^1/gamma
+    case -1:
+        if (R < 0)
+            Val = 0;
+        else
+            Val = pow(R, 1/Params[0]);
+        break;
+
+    // CIE 122-1966
+    // Y = (aX + b)^Gamma  | X >= -b/a
+    // Y = 0               | else
+    case 2:
+        disc = -Params[2] / Params[1];
+
+        if (R >= disc ) {
+
+            e = Params[1]*R + Params[2];
+
+            if (e > 0)
+                Val = pow(e, Params[0]);
+            else
+                Val = 0;
+        }
+        else
+            Val = 0;
+        break;
+
+     // Type 2 Reversed
+     // X = (Y ^1/g  - b) / a
+     case -2:
+         if (R < 0)
+             Val = 0;
+         else
+             Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
+
+         if (Val < 0)
+              Val = 0;
+         break;
+
 
-       if (nEntries > 65530 || nEntries <= 0) {
-                cmsSignalError(LCMS_ERRC_ABORTED, "Couldn't create gammatable of more than 65530 entries");
-                return NULL;
-       }
+    // IEC 61966-3
+    // Y = (aX + b)^Gamma | X <= -b/a
+    // Y = c              | else
+    case 3:
+        disc = -Params[2] / Params[1];
+        if (disc < 0)
+            disc = 0;
+
+        if (R >= disc) {
+
+            e = Params[1]*R + Params[2];
+
+            if (e > 0)
+                Val = pow(e, Params[0]) + Params[3];
+            else
+                Val = 0;
+        }
+        else
+            Val = Params[3];
+        break;
+
+
+    // Type 3 reversed
+    // X=((Y-c)^1/g - b)/a      | (Y>=c)
+    // X=-b/a                   | (Y<c)
+    case -3:
+        if (R >= Params[3])  {
+
+            e = R - Params[3];
+
+            if (e > 0)
+                Val = (pow(e, 1/Params[0]) - Params[2]) / Params[1];
+            else
+                Val = 0;
+        }
+        else {
+            Val = -Params[2] / Params[1];
+        }
+        break;
+
+
+    // IEC 61966-2.1 (sRGB)
+    // Y = (aX + b)^Gamma | X >= d
+    // Y = cX             | X < d
+    case 4:
+        if (R >= Params[4]) {
+
+            e = Params[1]*R + Params[2];
+
+            if (e > 0)
+                Val = pow(e, Params[0]);
+            else
+                Val = 0;
+        }
+        else
+            Val = R * Params[3];
+        break;
+
+    // Type 4 reversed
+    // X=((Y^1/g-b)/a)    | Y >= (ad+b)^g
+    // X=Y/c              | Y< (ad+b)^g
+    case -4:
+        e = Params[1] * Params[4] + Params[2];
+        if (e < 0)
+            disc = 0;
+        else
+            disc = pow(e, Params[0]);
 
-       size = sizeof(GAMMATABLE) + (sizeof(WORD) * (nEntries-1));
+        if (R >= disc) {
+
+            Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
+        }
+        else {
+            Val = R / Params[3];
+        }
+        break;
+
+
+    // Y = (aX + b)^Gamma + e | X >= d
+    // Y = cX + f             | X < d
+    case 5:
+        if (R >= Params[4]) {
+
+            e = Params[1]*R + Params[2];
+
+            if (e > 0)
+                Val = pow(e, Params[0]) + Params[5];
+            else
+                Val = 0;
+        }
+        else
+            Val = R*Params[3] + Params[6];
+        break;
+
 
-       p = (LPGAMMATABLE) _cmsMalloc(size);
-       if (!p) return NULL;
+    // Reversed type 5
+    // X=((Y-e)1/g-b)/a   | Y >=(ad+b)^g+e), cd+f
+    // X=(Y-f)/c          | else
+    case -5:
+
+        disc = Params[3] * Params[4] + Params[6];
+        if (R >= disc) {
+
+            e = R - Params[5];
+            if (e < 0)
+                Val = 0;
+            else
+                Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1];
+        }
+        else {
+            Val = (R - Params[6]) / Params[3];
+        }
+        break;
+
+
+    // Types 6,7,8 comes from segmented curves as described in ICCSpecRevision_02_11_06_Float.pdf
+    // Type 6 is basically identical to type 5 without d
+
+    // Y = (a * X + b) ^ Gamma + c
+    case 6:
+        e = Params[1]*R + Params[2];
+
+        if (e < 0)
+            Val = 0;
+        else
+            Val = pow(e, Params[0]) + Params[3];
+        break;
 
-       ZeroMemory(p, size);
+    // ((Y - c) ^1/Gamma - b) / a
+    case -6:
+        e = R - Params[3];
+        if (e < 0)
+            Val = 0;
+        else
+        Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1];
+        break;
+
+
+    // Y = a * log (b * X^Gamma + c) + d
+    case 7:
+
+       e = Params[2] * pow(R, Params[0]) + Params[3];
+       if (e <= 0)
+           Val = 0;
+       else
+           Val = Params[1]*log10(e) + Params[4];
+       break;
+
+    // (Y - d) / a = log(b * X ^Gamma + c)
+    // pow(10, (Y-d) / a) = b * X ^Gamma + c
+    // pow((pow(10, (Y-d) / a) - c) / b, 1/g) = X
+    case -7:
+       Val = pow((pow(10.0, (R-Params[4]) / Params[1]) - Params[3]) / Params[2], 1.0 / Params[0]);
+       break;
+
 
-       p -> Seed.Type     = 0;
-       p -> nEntries = nEntries;
+   //Y = a * b^(c*X+d) + e
+   case 8:
+       Val = (Params[0] * pow(Params[1], Params[2] * R + Params[3]) + Params[4]);
+       break;
+
+
+   // Y = (log((y-e) / a) / log(b) - d ) / c
+   // a=0, b=1, c=2, d=3, e=4,
+   case -8:
+
+       disc = R - Params[4];
+       if (disc < 0) Val = 0;
+       else
+           Val = (log(disc / Params[0]) / log(Params[1]) - Params[3]) / Params[2];
+       break;
 
-       return p;
+   // S-Shaped: (1 - (1-x)^1/g)^1/g
+   case 108:
+      Val = pow(1.0 - pow(1 - R, 1/Params[0]), 1/Params[0]);
+      break;
+
+    // y = (1 - (1-x)^1/g)^1/g
+    // y^g = (1 - (1-x)^1/g)
+    // 1 - y^g = (1-x)^1/g
+    // (1 - y^g)^g = 1 - x
+    // 1 - (1 - y^g)^g
+    case -108:
+        Val = 1 - pow(1 - pow(R, Params[0]), Params[0]);
+        break;
+
+    default:
+        // Unsupported parametric curve. Should never reach here
+        return 0;
+    }
+
+    return Val;
 }
 
-void LCMSEXPORT cmsFreeGamma(LPGAMMATABLE Gamma)
+// Evaluate a segmented funtion for a single value. Return -1 if no valid segment found .
+// If fn type is 0, perform an interpolation on the table
+static
+cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R)
 {
-       if (Gamma)  _cmsFree(Gamma);
-}
-
-
+    int i;
 
-void LCMSEXPORT cmsFreeGammaTriple(LPGAMMATABLE Gamma[3])
-{
-    cmsFreeGamma(Gamma[0]);
-    cmsFreeGamma(Gamma[1]);
-    cmsFreeGamma(Gamma[2]);
-    Gamma[0] = Gamma[1] = Gamma[2] = NULL;
-}
+    for (i = g ->nSegments-1; i >= 0 ; --i) {
 
+        // Check for domain
+        if ((R > g ->Segments[i].x0) && (R <= g ->Segments[i].x1)) {
+
+            // Type == 0 means segment is sampled
+            if (g ->Segments[i].Type == 0) {
 
-
-// Duplicate a gamma table
+                cmsFloat32Number R1 = (cmsFloat32Number) (R - g ->Segments[i].x0);
+                cmsFloat32Number Out;
 
-LPGAMMATABLE  LCMSEXPORT cmsDupGamma(LPGAMMATABLE In)
-{
-       LPGAMMATABLE Ptr;
-       size_t size;
+                // Setup the table (TODO: clean that)
+                g ->SegInterp[i]-> Table = g ->Segments[i].SampledPoints;
+
+                g ->SegInterp[i] -> Interpolation.LerpFloat(&R1, &Out, g ->SegInterp[i]);
 
-       Ptr = cmsAllocGamma(In -> nEntries);
-       if (Ptr == NULL) return NULL;
+                return Out;
+            }
+            else
+                return g ->Evals[i](g->Segments[i].Type, g ->Segments[i].Params, R);
+        }
+    }
 
-       size = sizeof(GAMMATABLE) + (sizeof(WORD) * (In -> nEntries-1));
-
-       CopyMemory(Ptr, In, size);
-       return Ptr;
+    return MINUS_INF;
 }
 
 
-// Handle gamma using interpolation tables. The resulting curves can become
-// very stange, but are pleasent to eye.
-
-LPGAMMATABLE LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma,
-                          LPGAMMATABLE OutGamma)
+// Create an empty gamma curve, by using tables. This specifies only the limited-precision part, and leaves the
+// floating point description empty.
+cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsInt32Number nEntries, const cmsUInt16Number Values[])
 {
-       register int i;
-       L16PARAMS L16In, L16Out;
-       LPWORD InPtr, OutPtr;
-       LPGAMMATABLE p;
-
-       p = cmsAllocGamma(256);
-       if (!p) return NULL;
+    return AllocateToneCurveStruct(ContextID, nEntries, 0, NULL, Values);
+}
 
-       cmsCalcL16Params(InGamma -> nEntries, &L16In);
-       InPtr  = InGamma -> GammaTable;
-
-       cmsCalcL16Params(OutGamma -> nEntries, &L16Out);
-       OutPtr = OutGamma-> GammaTable;
-
-       for (i=0; i < 256; i++)
-       {
-              WORD wValIn, wValOut;
-
-              wValIn  = cmsLinearInterpLUT16(RGB_8_TO_16(i), InPtr, &L16In);
-              wValOut = cmsReverseLinearInterpLUT16(wValIn, OutPtr, &L16Out);
-
-              p -> GammaTable[i] = wValOut;
-       }
-
-       return p;
+static
+int EntriesByGamma(cmsFloat64Number Gamma)
+{
+    if (fabs(Gamma - 1.0) < 0.001) return 2;
+    return 4096;
 }
 
 
+// Create a segmented gamma, fill the table
+cmsToneCurve* CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID,
+                                                   cmsInt32Number nSegments, const cmsCurveSegment Segments[])
+{
+    int i;
+    cmsFloat64Number R, Val;
+    cmsToneCurve* g;
+    int nGridPoints = 4096;
 
-// New method, using smoothed parametric curves. This works FAR better.
-// We want to get
-//
-//      y = f(g^-1(x))      ; f = ingamma, g = outgamma
-//
-// And this can be parametrized as
-//
-//      y = f(t)
-//      x = g(t)
+    _cmsAssert(Segments != NULL);
+
+    // Optimizatin for identity curves.
+    if (nSegments == 1 && Segments[0].Type == 1) {
+
+        nGridPoints = EntriesByGamma(Segments[0].Params[0]);
+    }
+
+    g = AllocateToneCurveStruct(ContextID, nGridPoints, nSegments, Segments, NULL);
+    if (g == NULL) return NULL;
+
+    // Once we have the floating point version, we can approximate a 16 bit table of 4096 entries
+    // for performance reasons. This table would normally not be used except on 8/16 bits transforms.
+    for (i=0; i < nGridPoints; i++) {
+
+        R   = (cmsFloat64Number) i / (nGridPoints-1);
 
+        Val = EvalSegmentedFn(g, R);
 
-LPGAMMATABLE LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma,
-                                       LPGAMMATABLE OutGamma, int nPoints)
+        // Round and saturate
+        g ->Table16[i] = _cmsQuickSaturateWord(Val * 65535.0);
+    }
+
+    return g;
+}
+
+// Use a segmented curve to store the floating point table
+cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[])
 {
+    cmsCurveSegment Seg[2];
+
+    // Initialize segmented curve part up to 0
+    Seg[0].x0 = -1;
+    Seg[0].x1 = 0;
+    Seg[0].Type = 6;
 
-    LPSAMPLEDCURVE x, y, r;
-    LPGAMMATABLE res;
+    Seg[0].Params[0] = 1;
+    Seg[0].Params[1] = 0;
+    Seg[0].Params[2] = 0;
+    Seg[0].Params[3] = 0;
+    Seg[0].Params[4] = 0;
 
-    x = cmsConvertGammaToSampledCurve(InGamma,  nPoints);
-    y = cmsConvertGammaToSampledCurve(OutGamma, nPoints);
-    r = cmsJoinSampledCurves(y, x, nPoints);
+    // From zero to any
+    Seg[1].x0 = 0;
+    Seg[1].x1 = 1.0;
+    Seg[1].Type = 0;
 
-    // Does clean "hair"
-    cmsSmoothSampledCurve(r, 0.001);
+    Seg[1].nGridPoints = nEntries;
+    Seg[1].SampledPoints = (cmsFloat32Number*) values;
+
+    return cmsBuildSegmentedToneCurve(ContextID, 2, Seg);
+}
 
-    cmsClampSampledCurve(r, 0.0, 65535.0);
+// Parametric curves
+//
+// Parameters goes as: Curve, a, b, c, d, e, f
+// Type is the ICC type +1
+// if type is negative, then the curve is analyticaly inverted
+cmsToneCurve* CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[])
+{
+    cmsCurveSegment Seg0;
+    int Pos = 0;
+    cmsUInt32Number size;
+    _cmsParametricCurvesCollection* c = GetParametricCurveByType(Type, &Pos);
 
-    cmsFreeSampledCurve(x);
-    cmsFreeSampledCurve(y);
+    _cmsAssert(Params != NULL);
 
-    res = cmsConvertSampledCurveToGamma(r, 65535.0);
-    cmsFreeSampledCurve(r);
+    if (c == NULL) {
+         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type);
+        return NULL;
+    }
+
+    memset(&Seg0, 0, sizeof(Seg0));
 
-    return res;
+    Seg0.x0   = MINUS_INF;
+    Seg0.x1   = PLUS_INF;
+    Seg0.Type = Type;
+
+    size = c->ParameterCount[Pos] * sizeof(cmsFloat64Number);
+    memmove(Seg0.Params, Params, size);
+
+    return cmsBuildSegmentedToneCurve(ContextID, 1, &Seg0);
 }
 
 
 
-// Reverse a gamma table
-
-LPGAMMATABLE LCMSEXPORT cmsReverseGamma(int nResultSamples, LPGAMMATABLE InGamma)
+// Build a gamma table based on gamma constant
+cmsToneCurve* CMSEXPORT cmsBuildGamma(cmsContext ContextID, cmsFloat64Number Gamma)
 {
-       register int i;
-       L16PARAMS L16In;
-       LPWORD InPtr;
-       LPGAMMATABLE p;
-
-       // Try to reverse it analytically whatever possible
-       if (InGamma -> Seed.Type > 0 && InGamma -> Seed.Type <= 5 &&
-            _cmsCrc32OfGammaTable(InGamma) == InGamma -> Seed.Crc32) {
-
-                return cmsBuildParametricGamma(nResultSamples, -(InGamma -> Seed.Type), InGamma ->Seed.Params);
-       }
+    return cmsBuildParametricToneCurve(ContextID, 1, &Gamma);
+}
 
 
-       // Nope, reverse the table
-       p = cmsAllocGamma(nResultSamples);
-       if (!p) return NULL;
+// Free all memory taken by the gamma curve
+void CMSEXPORT cmsFreeToneCurve(cmsToneCurve* Curve)
+{
+    cmsContext ContextID;
+
+    if (Curve == NULL) return;
+
+    ContextID = Curve ->InterpParams->ContextID;
+
+    _cmsFreeInterpParams(Curve ->InterpParams);
 
-       cmsCalcL16Params(InGamma -> nEntries, &L16In);
-       InPtr  = InGamma -> GammaTable;
+    if (Curve -> Table16)
+        _cmsFree(ContextID, Curve ->Table16);
+
+    if (Curve ->Segments) {
+
+        cmsUInt32Number i;
+
+        for (i=0; i < Curve ->nSegments; i++) {
+
+            if (Curve ->Segments[i].SampledPoints) {
+                _cmsFree(ContextID, Curve ->Segments[i].SampledPoints);
+            }
 
-       for (i=0; i < nResultSamples; i++)
-       {
-              WORD wValIn, wValOut;
+            if (Curve ->SegInterp[i] != 0)
+                _cmsFreeInterpParams(Curve->SegInterp[i]);
+        }
+
+        _cmsFree(ContextID, Curve ->Segments);
+        _cmsFree(ContextID, Curve ->SegInterp);
+    }
+
+    if (Curve -> Evals)
+        _cmsFree(ContextID, Curve -> Evals);
 
-              wValIn = _cmsQuantizeVal(i, nResultSamples);
-              wValOut = cmsReverseLinearInterpLUT16(wValIn, InPtr, &L16In);
-              p -> GammaTable[i] = wValOut;
-       }
+    if (Curve) _cmsFree(ContextID, Curve);
+}
+
+// Utility function, free 3 gamma tables
+void CMSEXPORT cmsFreeToneCurveTriple(cmsToneCurve* Curve[3])
+{
+
+    _cmsAssert(Curve != NULL);
+
+    if (Curve[0] != NULL) cmsFreeToneCurve(Curve[0]);
+    if (Curve[1] != NULL) cmsFreeToneCurve(Curve[1]);
+    if (Curve[2] != NULL) cmsFreeToneCurve(Curve[2]);
+
+    Curve[0] = Curve[1] = Curve[2] = NULL;
+}
 
 
-       return p;
+// Duplicate a gamma table
+cmsToneCurve* CMSEXPORT cmsDupToneCurve(const cmsToneCurve* In)
+{
+    if (In == NULL) return NULL;
+
+    return  AllocateToneCurveStruct(In ->InterpParams ->ContextID, In ->nEntries, In ->nSegments, In ->Segments, In ->Table16);
+}
+
+// Joins two curves for X and Y. Curves should be monotonic.
+// We want to get
+//
+//      y = Y^-1(X(t))
+//
+cmsToneCurve* CMSEXPORT cmsJoinToneCurve(cmsContext ContextID,
+                                      const cmsToneCurve* X,
+                                      const cmsToneCurve* Y, cmsUInt32Number nResultingPoints)
+{
+    cmsToneCurve* out = NULL;
+    cmsToneCurve* Yreversed = NULL;
+    cmsFloat32Number t, x;
+    cmsFloat32Number* Res = NULL;
+    cmsUInt32Number i;
+
+
+    _cmsAssert(X != NULL);
+    _cmsAssert(Y != NULL);
+
+    Yreversed = cmsReverseToneCurveEx(nResultingPoints, Y);
+    if (Yreversed == NULL) goto Error;
+
+    Res = (cmsFloat32Number*) _cmsCalloc(ContextID, nResultingPoints, sizeof(cmsFloat32Number));
+    if (Res == NULL) goto Error;
+
+    //Iterate
+    for (i=0; i <  nResultingPoints; i++) {
+
+        t = (cmsFloat32Number) i / (nResultingPoints-1);
+        x = cmsEvalToneCurveFloat(X,  t);
+        Res[i] = cmsEvalToneCurveFloat(Yreversed, x);
+    }
+
+    // Allocate space for output
+    out = cmsBuildTabulatedToneCurveFloat(ContextID, nResultingPoints, Res);
+
+Error:
+
+    if (Res != NULL) _cmsFree(ContextID, Res);
+    if (Yreversed != NULL) cmsFreeToneCurve(Yreversed);
+
+    return out;
 }
 
 
 
-// Parametric curves
-//
-// Parameters goes as: Gamma, a, b, c, d, e, f
-// Type is the ICC type +1
-// if type is negative, then the curve is analyticaly inverted
-
-LPGAMMATABLE LCMSEXPORT cmsBuildParametricGamma(int nEntries, int Type, double Params[])
+// Get the surrounding nodes. This is tricky on non-monotonic tables
+static
+int GetInterval(cmsFloat64Number In, const cmsUInt16Number LutTable[], const struct _cms_interp_struc* p)
 {
-        LPGAMMATABLE Table;
-        double R, Val, dval, e;
-        int i;
-        int ParamsByType[] = { 0, 1, 3, 4, 5, 7 };
-
-        Table = cmsAllocGamma(nEntries);
-        if (NULL == Table) return NULL;
-
-        Table -> Seed.Type = Type;
+    int i;
+    int y0, y1;
 
-        CopyMemory(Table ->Seed.Params, Params, ParamsByType[abs(Type)] * sizeof(double));
-
+    // A 1 point table is not allowed
+    if (p -> Domain[0] < 1) return -1;
 
-        for (i=0; i < nEntries; i++) {
-
-                R   = (double) i / (nEntries-1);
-
-                switch (Type) {
+    // Let's see if ascending or descending.
+    if (LutTable[0] < LutTable[p ->Domain[0]]) {
 
-                // X = Y ^ Gamma
-                case 1:
-                      Val = pow(R, Params[0]);
-                      break;
+        // Table is overall ascending
+        for (i=p->Domain[0]-1; i >=0; --i) {
 
-                // Type 1 Reversed: X = Y ^1/gamma
-                case -1:
-                      Val = pow(R, 1/Params[0]);
-                      break;
+            y0 = LutTable[i];
+            y1 = LutTable[i+1];
 
-                // CIE 122-1966
-                // Y = (aX + b)^Gamma  | X >= -b/a
-                // Y = 0               | else
-                case 2:
-                    if (R >= -Params[2] / Params[1]) {
-
-                              e = Params[1]*R + Params[2];
-
-                              if (e > 0)
-                                Val = pow(e, Params[0]);
-                              else
-                                Val = 0;
-                    }
-                    else
-                              Val = 0;
-                      break;
-
-                // Type 2 Reversed
-                // X = (Y ^1/g  - b) / a
-                case -2:
+            if (y0 <= y1) { // Increasing
+                if (In >= y0 && In <= y1) return i;
+            }
+            else
+                if (y1 < y0) { // Decreasing
+                    if (In >= y1 && In <= y0) return i;
+                }
+        }
+    }
+    else {
+        // Table is overall descending
+        for (i=0; i < (int) p -> Domain[0]; i++) {
 
-                    Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
-                    if (Val < 0)
-                            Val = 0;
-                    break;
-
-
-                // IEC 61966-3
-                // Y = (aX + b)^Gamma | X <= -b/a
-                // Y = c              | else
-                case 3:
-                    if (R >= -Params[2] / Params[1]) {
+            y0 = LutTable[i];
+            y1 = LutTable[i+1];
 
-                      e = Params[1]*R + Params[2];
-                      Val = pow(e, Params[0]) + Params[3];
-                    }
-                    else
-                      Val = Params[3];
-                    break;
+            if (y0 <= y1) { // Increasing
+                if (In >= y0 && In <= y1) return i;
+            }
+            else
+                if (y1 < y0) { // Decreasing
+                    if (In >= y1 && In <= y0) return i;
+                }
+        }
+    }
 
-
-                // Type 3 reversed
-                // X=((Y-c)^1/g - b)/a      | (Y>=c)
-                // X=-b/a                   | (Y<c)
+    return -1;
+}
 
-                case -3:
-                    if (R >= Params[3])  {
-                        e = R - Params[3];
-                        Val = (pow(e, 1/Params[0]) - Params[2]) / Params[1];
-                        if (Val < 0) Val = 0;
-                    }
-                    else {
-                        Val = -Params[2] / Params[1];
-                    }
-                    break;
+// Reverse a gamma table
+cmsToneCurve* CMSEXPORT cmsReverseToneCurveEx(cmsInt32Number nResultSamples, const cmsToneCurve* InCurve)
+{
+    cmsToneCurve *out;
+    cmsFloat64Number a = 1, b = 0, y, x1, y1, x2, y2;
+    int i, j;
+    int Ascending;
 
+    _cmsAssert(InCurve != NULL);
 
-                // IEC 61966-2.1 (sRGB)
-                // Y = (aX + b)^Gamma | X >= d
-                // Y = cX             | X < d
-                case 4:
-                    if (R >= Params[4]) {
+    // Try to reverse it analytically whatever possible
+    if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 && InCurve -> Segments[0].Type <= 5) {
 
-                              e = Params[1]*R + Params[2];
-                              if (e > 0)
-                                Val = pow(e, Params[0]);
-                              else
-                                Val = 0;
-                    }
-                      else
-                              Val = R * Params[3];
-                      break;
+        return cmsBuildParametricToneCurve(InCurve ->InterpParams->ContextID,
+                                       -(InCurve -> Segments[0].Type),
+                                       InCurve -> Segments[0].Params);
+    }
 
-                // Type 4 reversed
-                // X=((Y^1/g-b)/a)    | Y >= (ad+b)^g
-                // X=Y/c              | Y< (ad+b)^g
-
-                case -4:
-                    if (R >= pow(Params[1] * Params[4] + Params[2], Params[0])) {
+    // Nope, reverse the table.
+    out = cmsBuildTabulatedToneCurve16(InCurve ->InterpParams->ContextID, nResultSamples, NULL);
+    if (out == NULL)
+        return NULL;
 
-                        Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
-                    }
-                    else {
-                        Val = R / Params[3];
-                    }
-                    break;
-
+    // We want to know if this is an ascending or descending table
+    Ascending = !cmsIsToneCurveDescending(InCurve);
 
+    // Iterate across Y axis
+    for (i=0; i <  nResultSamples; i++) {
 
-                // Y = (aX + b)^Gamma + e | X <= d
-                // Y = cX + f             | else
-                case 5:
-                    if (R >= Params[4]) {
+        y = (cmsFloat64Number) i * 65535.0 / (nResultSamples - 1);
 
-                        e = Params[1]*R + Params[2];
-                        Val = pow(e, Params[0]) + Params[5];
-                    }
-                    else
-                        Val = R*Params[3] + Params[6];
-                    break;
+        // Find interval in which y is within.
+        j = GetInterval(y, InCurve->Table16, InCurve->InterpParams);
+        if (j >= 0) {
 
-
-                // Reversed type 5
-                // X=((Y-e)1/g-b)/a   | Y >=(ad+b)^g+e)
-                // X=(Y-f)/c          | else
-                case -5:
-
-                if (R >= pow(Params[1] * Params[4], Params[0]) + Params[5]) {
+            // Get limits of interval
+            x1 = InCurve ->Table16[j];
+            x2 = InCurve ->Table16[j+1];
 
-                    Val = pow(R - Params[5], 1/Params[0]) - Params[2] / Params[1];
-                }
-                else {
-                    Val = (R - Params[6]) / Params[3];
-                }
-                break;
+            y1 = (cmsFloat64Number) (j * 65535.0) / (InCurve ->nEntries - 1);
+            y2 = (cmsFloat64Number) ((j+1) * 65535.0 ) / (InCurve ->nEntries - 1);
+
+            // If collapsed, then use any
+            if (x1 == x2) {
 
-                default:
-                        cmsSignalError(LCMS_ERRC_ABORTED, "Unsupported parametric curve type=%d", abs(Type)-1);
-                        cmsFreeGamma(Table);
-                        return NULL;
-                }
+                out ->Table16[i] = _cmsQuickSaturateWord(Ascending ? y2 : y1);
+                continue;
 
+            } else {
 
-        // Saturate
-
-        dval = Val * 65535.0 + .5;
-        if (dval > 65535.) dval = 65535.0;
-        if (dval < 0) dval = 0;
-
-        Table->GammaTable[i] = (WORD) floor(dval);
+                // Interpolate
+                a = (y2 - y1) / (x2 - x1);
+                b = y2 - a * x2;
+            }
         }
 
-        Table -> Seed.Crc32 = _cmsCrc32OfGammaTable(Table);
+        out ->Table16[i] = _cmsQuickSaturateWord(a* y + b);
+    }
 
-        return Table;
+    return out;
 }
 
-// Build a gamma table based on gamma constant
-
-LPGAMMATABLE LCMSEXPORT cmsBuildGamma(int nEntries, double Gamma)
+// Reverse a gamma table
+cmsToneCurve* CMSEXPORT cmsReverseToneCurve(const cmsToneCurve* InGamma)
 {
-    return cmsBuildParametricGamma(nEntries, 1, &Gamma);
+    _cmsAssert(InGamma != NULL);
+
+    return cmsReverseToneCurveEx(InGamma -> nEntries, InGamma);
 }
 
-
-
 // From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite
 // differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.
 //
@@ -499,485 +903,264 @@
 //   Input:  smoothing parameter (lambda), length (m).
 //   Output: smoothed vector (z): vector from 1 to m.
 
-
 static
-void smooth2(vec w, vec y, vec z, float lambda, int m)
+cmsBool smooth2(cmsContext ContextID, cmsFloat32Number w[], cmsFloat32Number y[], cmsFloat32Number z[], cmsFloat32Number lambda, int m)
 {
-  int i, i1, i2;
-  vec c, d, e;
-  d[1] = w[1] + lambda;
-  c[1] = -2 * lambda / d[1];
-  e[1] = lambda /d[1];
-  z[1] = w[1] * y[1];
-  d[2] = w[2] + 5 * lambda - d[1] * c[1] *  c[1];
-  c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2];
-  e[2] = lambda / d[2];
-  z[2] = w[2] * y[2] - c[1] * z[1];
-  for (i = 3; i < m - 1; i++) {
-    i1 = i - 1; i2 = i - 2;
-    d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
-    c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i];
-    e[i] = lambda / d[i];
-    z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2];
-  }
-  i1 = m - 2; i2 = m - 3;
-  d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
-  c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1];
-  z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2];
-  i1 = m - 1; i2 = m - 2;
-  d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
-  z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m];
-  z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];
-  for (i = m - 2; 1<= i; i--)
-     z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];
+    int i, i1, i2;
+    cmsFloat32Number *c, *d, *e;
+    cmsBool st;
+
+
+    c = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
+    d = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
+    e = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
+
+    if (c != NULL && d != NULL && e != NULL) {
+
+
+    d[1] = w[1] + lambda;
+    c[1] = -2 * lambda / d[1];
+    e[1] = lambda /d[1];
+    z[1] = w[1] * y[1];
+    d[2] = w[2] + 5 * lambda - d[1] * c[1] *  c[1];
+    c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2];
+    e[2] = lambda / d[2];
+    z[2] = w[2] * y[2] - c[1] * z[1];
+
+    for (i = 3; i < m - 1; i++) {
+        i1 = i - 1; i2 = i - 2;
+        d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
+        c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i];
+        e[i] = lambda / d[i];
+        z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2];
+    }
+
+    i1 = m - 2; i2 = m - 3;
+
+    d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
+    c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1];
+    z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2];
+    i1 = m - 1; i2 = m - 2;
+
+    d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
+    z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m];
+    z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];
+
+    for (i = m - 2; 1<= i; i--)
+        z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];
+
+      st = TRUE;
+    }
+    else st = FALSE;
+
+    if (c != NULL) _cmsFree(ContextID, c);
+    if (d != NULL) _cmsFree(ContextID, d);
+    if (e != NULL) _cmsFree(ContextID, e);
+
+    return st;
 }
 
-
-
-// Smooths a curve sampled at regular intervals
-
-LCMSBOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda)
-
+// Smooths a curve sampled at regular intervals.
+cmsBool  CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda)
 {
-    vec w, y, z;
+    cmsFloat32Number w[MAX_NODES_IN_CURVE], y[MAX_NODES_IN_CURVE], z[MAX_NODES_IN_CURVE];
     int i, nItems, Zeros, Poles;
 
+    if (Tab == NULL) return FALSE;
 
-    if (cmsIsLinear(Tab->GammaTable, Tab->nEntries)) return FALSE; // Nothing to do
+    if (cmsIsToneCurveLinear(Tab)) return FALSE; // Nothing to do
 
     nItems = Tab -> nEntries;
 
-    if (nItems > MAX_KNOTS) {
-                cmsSignalError(LCMS_ERRC_ABORTED, "cmsSmoothGamma: too many points.");
-                return FALSE;
-                }
+    if (nItems >= MAX_NODES_IN_CURVE) {
+        cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: too many points.");
+        return FALSE;
+    }
 
-    ZeroMemory(w, nItems * sizeof(float));
-    ZeroMemory(y, nItems * sizeof(float));
-    ZeroMemory(z, nItems * sizeof(float));
+    memset(w, 0, nItems * sizeof(cmsFloat32Number));
+    memset(y, 0, nItems * sizeof(cmsFloat32Number));
+    memset(z, 0, nItems * sizeof(cmsFloat32Number));
 
     for (i=0; i < nItems; i++)
     {
-        y[i+1] = (float) Tab -> GammaTable[i];
+        y[i+1] = (cmsFloat32Number) Tab -> Table16[i];
         w[i+1] = 1.0;
     }
 
-    smooth2(w, y, z, (float) lambda, nItems);
+    if (!smooth2(Tab ->InterpParams->ContextID, w, y, z, (cmsFloat32Number) lambda, nItems)) return FALSE;
 
     // Do some reality - checking...
     Zeros = Poles = 0;
     for (i=nItems; i > 1; --i) {
 
-            if (z[i] == 0.) Zeros++;
-            if (z[i] >= 65535.) Poles++;
-            if (z[i] < z[i-1]) return FALSE; // Non-Monotonic
+        if (z[i] == 0.) Zeros++;
+        if (z[i] >= 65535.) Poles++;
+        if (z[i] < z[i-1]) return FALSE; // Non-Monotonic
     }
 
     if (Zeros > (nItems / 3)) return FALSE;  // Degenerated, mostly zeros
     if (Poles > (nItems / 3)) return FALSE;  // Degenerated, mostly poles
 
     // Seems ok
-
     for (i=0; i < nItems; i++) {
 
-        // Clamp to WORD
+        // Clamp to cmsUInt16Number
+        Tab -> Table16[i] = _cmsQuickSaturateWord(z[i+1]);
+    }
+
+    return TRUE;
+}
 
-        float v = z[i+1];
+// Is a table linear? Do not use parametric since we cannot guarantee some weird parameters resulting
+// in a linear table. This way assures it is linear in 12 bits, which should be enought in most cases.
+cmsBool CMSEXPORT cmsIsToneCurveLinear(const cmsToneCurve* Curve)
+{
+    cmsUInt32Number i;
+    int diff;
+
+    _cmsAssert(Curve != NULL);
+
+    for (i=0; i < Curve ->nEntries; i++) {
+
+        diff = abs((int) Curve->Table16[i] - (int) _cmsQuantizeVal(i, Curve ->nEntries));
+        if (diff > 0x0f)
+            return FALSE;
+    }
 
-        if (v < 0) v = 0;
-        if (v > 65535.) v = 65535.;
+    return TRUE;
+}
+
+// Same, but for monotonicity
+cmsBool  CMSEXPORT cmsIsToneCurveMonotonic(const cmsToneCurve* t)
+{
+    int n;
+    int i, last;
+
+    _cmsAssert(t != NULL);
 
-        Tab -> GammaTable[i] = (WORD) floor(v + .5);
-        }
+    n    = t ->nEntries;
+    last = t ->Table16[n-1];
+
+    for (i = n-2; i >= 0; --i) {
+
+        if (t ->Table16[i] > last)
+
+            return FALSE;
+        else
+            last = t ->Table16[i];
+
+    }
 
     return TRUE;
 }
 
+// Same, but for descending tables
+cmsBool  CMSEXPORT cmsIsToneCurveDescending(const cmsToneCurve* t)
+{
+    _cmsAssert(t != NULL);
 
-// Check if curve is exponential, return gamma if so.
+    return t ->Table16[0] > t ->Table16[t ->nEntries-1];
+}
+
+
+// Another info fn: is out gamma table multisegment?
+cmsBool  CMSEXPORT cmsIsToneCurveMultisegment(const cmsToneCurve* t)
+{
+    _cmsAssert(t != NULL);
+
+    return t -> nSegments > 1;
+}
+
+cmsInt32Number  CMSEXPORT cmsGetToneCurveParametricType(const cmsToneCurve* t)
+{
+    _cmsAssert(t != NULL);
+
+    if (t -> nSegments != 1) return 0;
+    return t ->Segments[0].Type;
+}
+
+// We need accuracy this time
+cmsFloat32Number CMSEXPORT cmsEvalToneCurveFloat(const cmsToneCurve* Curve, cmsFloat32Number v)
+{
+    _cmsAssert(Curve != NULL);
+
+    // Check for 16 bits table. If so, this is a limited-precision tone curve
+    if (Curve ->nSegments == 0) {
+
+        cmsUInt16Number In, Out;
+
+        In = (cmsUInt16Number) _cmsQuickSaturateWord(v * 65535.0);
+        Out = cmsEvalToneCurve16(Curve, In);
 
-double LCMSEXPORT cmsEstimateGammaEx(LPWORD GammaTable, int nEntries, double Thereshold)
+        return (cmsFloat32Number) (Out / 65535.0);
+    }
+
+    return (cmsFloat32Number) EvalSegmentedFn(Curve, v);
+}
+
+// We need xput over here
+cmsUInt16Number CMSEXPORT cmsEvalToneCurve16(const cmsToneCurve* Curve, cmsUInt16Number v)
 {
-    double gamma, sum, sum2;
-    double n, x, y, Std;
-    int i;
+    cmsUInt16Number out;
+
+    _cmsAssert(Curve != NULL);
+
+    Curve ->InterpParams ->Interpolation.Lerp16(&v, &out, Curve ->InterpParams);
+    return out;
+}
+
+
+// Least squares fitting.
+// A mathematical procedure for finding the best-fitting curve to a given set of points by
+// minimizing the sum of the squares of the offsets ("the residuals") of the points from the curve.
+// The sum of the squares of the offsets is used instead of the offset absolute values because
+// this allows the residuals to be treated as a continuous differentiable quantity.
+//
+// y = f(x) = x ^ g
+//
+// R  = (yi - (xi^g))
+// R2 = (yi - (xi^g))2
+// SUM R2 = SUM (yi - (xi^g))2
+//
+// dR2/dg = -2 SUM x^g log(x)(y - x^g)
+// solving for dR2/dg = 0
+//
+// g = 1/n * SUM(log(y) / log(x))
+
+cmsFloat64Number CMSEXPORT cmsEstimateGamma(const cmsToneCurve* t, cmsFloat64Number Precision)
+{
+    cmsFloat64Number gamma, sum, sum2;
+    cmsFloat64Number n, x, y, Std;
+    cmsUInt32Number i;
+
+    _cmsAssert(t != NULL);
 
     sum = sum2 = n = 0;
 
-    // Does exclude endpoints
-    for (i=1; i < nEntries - 1; i++) {
+    // Excluding endpoints
+    for (i=1; i < (MAX_NODES_IN_CURVE-1); i++) {
 
-            x = (double) i / (nEntries - 1);
-            y = (double) GammaTable[i] / 65535.;
+        x = (cmsFloat64Number) i / (MAX_NODES_IN_CURVE-1);
+        y = (cmsFloat64Number) cmsEvalToneCurveFloat(t, (cmsFloat32Number) x);
 
-            // Avoid 7% on lower part to prevent
-            // artifacts due to linear ramps
+        // Avoid 7% on lower part to prevent
+        // artifacts due to linear ramps
 
-            if (y > 0. && y < 1. && x > 0.07) {
+        if (y > 0. && y < 1. && x > 0.07) {
 
             gamma = log(y) / log(x);
             sum  += gamma;
             sum2 += gamma * gamma;
             n++;
-            }
-
+        }
     }
 
     // Take a look on SD to see if gamma isn't exponential at all
     Std = sqrt((n * sum2 - sum * sum) / (n*(n-1)));
 
-
-    if (Std > Thereshold)
+    if (Std > Precision)
         return -1.0;
 
     return (sum / n);   // The mean
 }
 
-
-double LCMSEXPORT cmsEstimateGamma(LPGAMMATABLE t)
-{
-        return cmsEstimateGammaEx(t->GammaTable, t->nEntries, 0.7);
-}
-
-
-// -----------------------------------------------------------------Sampled curves
-
-// Allocate a empty curve
-
-LPSAMPLEDCURVE cmsAllocSampledCurve(int nItems)
-{
-    LPSAMPLEDCURVE pOut;
-
-    pOut = (LPSAMPLEDCURVE) _cmsMalloc(sizeof(SAMPLEDCURVE));
-    if (pOut == NULL)
-            return NULL;
-
-    if((pOut->Values = (double *) _cmsMalloc(nItems * sizeof(double))) == NULL)
-    {
-         _cmsFree(pOut);
-        return NULL;
-    }
-
-    pOut->nItems = nItems;
-    ZeroMemory(pOut->Values, nItems * sizeof(double));
-
-    return pOut;
-}
-
-
-void cmsFreeSampledCurve(LPSAMPLEDCURVE p)
-{
-     _cmsFree((LPVOID) p -> Values);
-     _cmsFree((LPVOID) p);
-}
-
-
-
-// Does duplicate a sampled curve
-
-LPSAMPLEDCURVE cmsDupSampledCurve(LPSAMPLEDCURVE p)
-{
-    LPSAMPLEDCURVE out;
-
-    out = cmsAllocSampledCurve(p -> nItems);
-    if (!out) return NULL;
-
-    CopyMemory(out ->Values, p ->Values, p->nItems * sizeof(double));
-
-    return out;
-}
-
-
-// Take min, max of curve
-
-void cmsEndpointsOfSampledCurve(LPSAMPLEDCURVE p, double* Min, double* Max)
-{
-        int i;
-
-        *Min = 65536.;
-        *Max = 0.;
-
-        for (i=0; i < p -> nItems; i++) {
-
-                double v = p -> Values[i];
-
-                if (v < *Min)
-                        *Min = v;
-
-                if (v > *Max)
-                        *Max = v;
-        }
-
-        if (*Min < 0) *Min = 0;
-        if (*Max > 65535.0) *Max = 65535.0;
-}
-
-// Clamps to Min, Max
-
-void cmsClampSampledCurve(LPSAMPLEDCURVE p, double Min, double Max)
-{
-
-        int i;
-
-        for (i=0; i < p -> nItems; i++) {
-
-                double v = p -> Values[i];
-
-                if (v < Min)
-                        v = Min;
-
-                if (v > Max)
-                        v = Max;
-
-                p -> Values[i] = v;
-
-        }
-
-}
-
-
-
-// Smooths a curve sampled at regular intervals
-
-LCMSBOOL cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double lambda)
-{
-    vec w, y, z;
-    int i, nItems;
-
-    nItems = Tab -> nItems;
-
-    if (nItems > MAX_KNOTS) {
-                cmsSignalError(LCMS_ERRC_ABORTED, "cmsSmoothSampledCurve: too many points.");
-                return FALSE;
-                }
-
-    ZeroMemory(w, nItems * sizeof(float));
-    ZeroMemory(y, nItems * sizeof(float));
-    ZeroMemory(z, nItems * sizeof(float));
-
-    for (i=0; i < nItems; i++)
-    {
-        float value = (float) Tab -> Values[i];
-
-        y[i+1] = value;
-        w[i+1] = (float) ((value < 0.0) ?  0 : 1);
-    }
-
-
-    smooth2(w, y, z, (float) lambda, nItems);
-
-    for (i=0; i < nItems; i++) {
-
-        Tab -> Values[i] = z[i+1];;
-     }
-
-    return TRUE;
-
-}
-
-
-// Scale a value v, within domain Min .. Max
-// to a domain 0..(nPoints-1)
-
-static
-double ScaleVal(double v, double Min, double Max, int nPoints)
-{
-
-        double a, b;
-
-        if (v <= Min) return 0;
-        if (v >= Max) return (nPoints-1);
-
-        a = (double) (nPoints - 1) / (Max - Min);
-        b = a * Min;
-
-        return (a * v) - b;
-
-}
-
-
-// Does rescale a sampled curve to fit in a 0..(nPoints-1) domain
-
-void cmsRescaleSampledCurve(LPSAMPLEDCURVE p, double Min, double Max, int nPoints)
-{
-
-        int i;
-
-        for (i=0; i < p -> nItems; i++) {
-
-                double v = p -> Values[i];
-
-                p -> Values[i] = ScaleVal(v, Min, Max, nPoints);
-        }
-
-}
-
-
-// Joins two sampled curves for X and Y. Curves should be sorted.
-
-LPSAMPLEDCURVE cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints)
-{
-    int i, j;
-    LPSAMPLEDCURVE out;
-    double MinX, MinY, MaxX, MaxY;
-    double x, y, x1, y1, x2, y2, a, b;
-
-    out = cmsAllocSampledCurve(nResultingPoints);
-    if (out == NULL)
-        return NULL;
-
-    if (X -> nItems != Y -> nItems) {
-
-        cmsSignalError(LCMS_ERRC_ABORTED, "cmsJoinSampledCurves: invalid curve.");
-        cmsFreeSampledCurve(out);
-        return NULL;
-    }
-
-    // Get endpoints of sampled curves
-    cmsEndpointsOfSampledCurve(X, &MinX, &MaxX);
-    cmsEndpointsOfSampledCurve(Y, &MinY, &MaxY);
-
-
-    // Set our points
-    out ->Values[0] = MinY;
-    for (i=1; i < nResultingPoints; i++) {
-
-        // Scale t to x domain
-        x = (i * (MaxX - MinX) / (nResultingPoints-1)) + MinX;
-
-        // Find interval in which j is within (always up,
-        // since fn should be monotonic at all)
-
-        j = 1;
-        while ((j < X ->nItems - 1) && X ->Values[j] < x)
-            j++;
-
-        // Now x is within X[j-1], X[j]
-        x1 = X ->Values[j-1]; x2 = X ->Values[j];
-        y1 = Y ->Values[j-1]; y2 = Y ->Values[j];
-
-        // Interpolate  the value
-        a = (y1 - y2) / (x1 - x2);
-        b = y1 - a * x1;
-        y = a* x + b;
-
-        out ->Values[i] = y;
-    }
-
-
-    cmsClampSampledCurve(out, MinY, MaxY);
-    return out;
-}
-
-
-
-// Convert between curve types
-
-LPGAMMATABLE cmsConvertSampledCurveToGamma(LPSAMPLEDCURVE Sampled, double Max)
-{
-    LPGAMMATABLE Gamma;
-    int i, nPoints;
-
-
-    nPoints = Sampled ->nItems;
-
-    Gamma = cmsAllocGamma(nPoints);
-    for (i=0; i < nPoints; i++) {
-
-        Gamma->GammaTable[i] = (WORD) floor(ScaleVal(Sampled ->Values[i], 0, Max, 65536) + .5);
-    }
-
-    return Gamma;
-
-}
-
-// Inverse of anterior
-
-LPSAMPLEDCURVE cmsConvertGammaToSampledCurve(LPGAMMATABLE Gamma, int nPoints)
-{
-    LPSAMPLEDCURVE Sampled;
-    L16PARAMS L16;
-    int i;
-    WORD wQuant, wValIn;
-
-    if (nPoints > 4096) {
-
-        cmsSignalError(LCMS_ERRC_ABORTED, "cmsConvertGammaToSampledCurve: too many points (max=4096)");
-        return NULL;
-    }
-
-    cmsCalcL16Params(Gamma -> nEntries, &L16);
-
-    Sampled = cmsAllocSampledCurve(nPoints);
-    for (i=0; i < nPoints; i++) {
-            wQuant  = _cmsQuantizeVal(i, nPoints);
-            wValIn  = cmsLinearInterpLUT16(wQuant, Gamma ->GammaTable, &L16);
-            Sampled ->Values[i] = (float) wValIn;
-    }
-
-    return Sampled;
-}
-
-
-
-
-// Smooth endpoints (used in Black/White compensation)
-
-LCMSBOOL _cmsSmoothEndpoints(LPWORD Table, int nEntries)
-{
-    vec w, y, z;
-    int i, Zeros, Poles;
-
-
-
-    if (cmsIsLinear(Table, nEntries)) return FALSE; // Nothing to do
-
-
-    if (nEntries > MAX_KNOTS) {
-                cmsSignalError(LCMS_ERRC_ABORTED, "_cmsSmoothEndpoints: too many points.");
-                return FALSE;
-                }
-
-    ZeroMemory(w, nEntries * sizeof(float));
-    ZeroMemory(y, nEntries * sizeof(float));
-    ZeroMemory(z, nEntries * sizeof(float));
-
-    for (i=0; i < nEntries; i++)
-    {
-        y[i+1] = (float) Table[i];
-        w[i+1] = 1.0;
-    }
-
-    w[1]        = 65535.0;
-    w[nEntries] = 65535.0;
-
-    smooth2(w, y, z, (float) nEntries, nEntries);
-
-    // Do some reality - checking...
-    Zeros = Poles = 0;
-    for (i=nEntries; i > 1; --i) {
-
-            if (z[i] == 0.) Zeros++;
-            if (z[i] >= 65535.) Poles++;
-            if (z[i] < z[i-1]) return FALSE; // Non-Monotonic
-    }
-
-    if (Zeros > (nEntries / 3)) return FALSE;  // Degenerated, mostly zeros
-    if (Poles > (nEntries / 3)) return FALSE;    // Degenerated, mostly poles
-
-    // Seems ok
-
-    for (i=0; i < nEntries; i++) {
-
-        // Clamp to WORD
-
-        float v = z[i+1];
-
-        if (v < 0) v = 0;
-        if (v > 65535.) v = 65535.;
-
-        Table[i] = (WORD) floor(v + .5);
-        }
-
-    return TRUE;
-}
--- a/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,871 +49,383 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-#include "lcms.h"
-
-/*
-Gamut check by default is a catching of 0xFFFF/0xFFFF/0xFFFF PCS values, used
-internally by lcms to hold invalid values. Matrix LUT's, operates in a way that
-unencodeable values are marked as this combination, if PCS is XYZ, this is a very
-high value since encoding is a 1.15 fixed point, something like 1.9997, 1.9997, 1.9997
-not a very common color after all. Lab PCS is not to be a problem, since L>100 are truely
-undefined. There is a posibility than ICC comitee defines L>100 as a valid means
-to use highlights, then it will be lost.
-
-(1.10 - Actually ICC did it, so this should be checked for full ICC 4.0 support)
-
-*/
-
-
-LCMSBOOL _cmsEndPointsBySpace(icColorSpaceSignature Space, WORD **White, WORD **Black,
-                            int *nOutputs)
-{
-       // Only most common spaces
-
-       static WORD RGBblack[4]  = { 0, 0, 0 };
-       static WORD RGBwhite[4]  = { 0xffff, 0xffff, 0xffff };
-       static WORD CMYKblack[4] = { 0xffff, 0xffff, 0xffff, 0xffff };   // 400% of ink
-       static WORD CMYKwhite[4] = { 0, 0, 0, 0 };
-       static WORD LABblack[4]  = { 0, 0x8000, 0x8000 };
-       static WORD LABwhite[4]  = { 0xFF00, 0x8000, 0x8000 };
-       static WORD CMYblack[4]  = { 0xffff, 0xffff, 0xffff };
-       static WORD CMYwhite[4]  = { 0, 0, 0 };
-       static WORD Grayblack[4] = { 0 };
-       static WORD GrayWhite[4] = { 0xffff };
-
-       switch (Space) {
-
-       case icSigGrayData: if (White)    *White = GrayWhite;
-                           if (Black)    *Black = Grayblack;
-                           if (nOutputs) *nOutputs = 1;
-                           return TRUE;
-
-       case icSigRgbData:  if (White)    *White = RGBwhite;
-                           if (Black)    *Black = RGBblack;
-                           if (nOutputs) *nOutputs = 3;
-                           return TRUE;
-
-       case icSigLabData:  if (White)    *White = LABwhite;
-                           if (Black)    *Black = LABblack;
-                           if (nOutputs) *nOutputs = 3;
-                           return TRUE;
-
-       case icSigCmykData: if (White)    *White = CMYKwhite;
-                           if (Black)    *Black = CMYKblack;
-                           if (nOutputs) *nOutputs = 4;
-                           return TRUE;
-
-       case icSigCmyData:  if (White)    *White = CMYwhite;
-                           if (Black)    *Black = CMYblack;
-                           if (nOutputs) *nOutputs = 3;
-                           return TRUE;
-
-       default:;
-       }
+//
+//---------------------------------------------------------------------------------
+//
 
-  return FALSE;
-}
-
-
-WORD *_cmsWhiteBySpace(icColorSpaceSignature Space)
-{
-       WORD *White= NULL, *Black = NULL;
-       int Dummy;
-       static WORD Default[MAXCHANNELS];
-
-       if (_cmsEndPointsBySpace(Space, &White, &Black, &Dummy))
-              return White;
-
-       return Default;
-
-}
-
-
-
-
-WORD Clamp_L(Fixed32 in)
-{
-       if (in == 0xFFFF) return 0xFFFFU;  // Marker
-
-       if (in > 0xFF00) return 0xFF00U;  // L* = 100.0
-       return (WORD) in;
-}
-
-
-#define ENCODE_AB(x) (WORD) (((x) + 128.0) * 256.0 + 0.5)
-
-WORD Clamp_ab(Fixed32 in)
-{
-       if (in == 0xFFFF) return 0xFFFFU;             // Marker
-
-       if (in < 0) return ENCODE_AB(-128.0);         // Max negative number
-       if (in > 0xFFFF) return ENCODE_AB(+127.9961); // Max positive number
-       return (WORD) in;
-}
-
-
-
-// Returns dE on two Lab values
-
-double LCMSEXPORT cmsDeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
-{
-        double dL, da, db;
-
-        if (Lab1 -> L < 0 ||
-            Lab2 -> L < 0) return 65536.;
-
-        if (Lab1 -> a < -200 || Lab1 -> a > 200) return 65536.;
-        if (Lab1 -> b < -200 || Lab1 -> b > 200) return 65536.;
-
-        if (Lab2 -> a < -200 || Lab2 -> a > 200) return 65536.;
-        if (Lab2 -> b < -200 || Lab2 -> b > 200) return 65536.;
-
-        if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;
-
-        dL = fabs(Lab1 -> L - Lab2 -> L);
-        da = fabs(Lab1 -> a - Lab2 -> a);
-        db = fabs(Lab1 -> b - Lab2 -> b);
-
-        return pow(dL*dL + da * da + db * db, 0.5);
-
-}
+#include "lcms2_internal.h"
 
 
-// Square
-static
-double Sqr(double v)
-{
-    return v *  v;
-}
-
-// Return the CIE94 Delta E
-double LCMSEXPORT cmsCIE94DeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
+// Auxiliar: append a Lab identity after the given sequence of profiles
+// and return the transform. Lab profile is closed, rest of profiles are kept open.
+cmsHTRANSFORM _cmsChain2Lab(cmsContext            ContextID,
+                            cmsUInt32Number        nProfiles,
+                            cmsUInt32Number        InputFormat,
+                            cmsUInt32Number        OutputFormat,
+                            const cmsUInt32Number  Intents[],
+                            const cmsHPROFILE      hProfiles[],
+                            const cmsBool          BPC[],
+                            const cmsFloat64Number AdaptationStates[],
+                            cmsUInt32Number        dwFlags)
 {
-    cmsCIELCh LCh1, LCh2;
-    double dE, dL, dC, dh, dhsq;
-    double c12, sc, sh;
-
-    if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;
-
-    dL = fabs(Lab1 ->L - Lab2 ->L);
-
-    cmsLab2LCh(&LCh1, Lab1);
-    cmsLab2LCh(&LCh2, Lab2);
-
-    dC  = fabs(LCh1.C - LCh2.C);
-    dE  = cmsDeltaE(Lab1, Lab2);
-
-    dhsq = Sqr(dE) - Sqr(dL) - Sqr(dC);
-    if (dhsq < 0)
-        dh = 0;
-    else
-        dh = pow(dhsq, 0.5);
-
-    c12 = sqrt(LCh1.C * LCh2.C);
-
-    sc = 1.0 + (0.048 * c12);
-    sh = 1.0 + (0.014 * c12);
-
-    return sqrt(Sqr(dL)  + Sqr(dC) / Sqr(sc) + Sqr(dh) / Sqr(sh));
-}
-
-
-// Auxiliary
+    cmsHTRANSFORM xform;
+    cmsHPROFILE   hLab;
+    cmsHPROFILE   ProfileList[256];
+    cmsBool       BPCList[256];
+    cmsFloat64Number AdaptationList[256];
+    cmsUInt32Number IntentList[256];
+    cmsUInt32Number i;
 
-static
-double ComputeLBFD(LPcmsCIELab Lab)
-{
-  double yt;
-
-  if (Lab->L > 7.996969)
-        yt = (Sqr((Lab->L+16)/116)*((Lab->L+16)/116))*100;
-  else
-        yt = 100 * (Lab->L / 903.3);
-
-  return (54.6 * (LOGE * (log(yt + 1.5))) - 9.6);
-}
-
-
-
-// bfd - gets BFD(1:1) difference between Lab1, Lab2
-double LCMSEXPORT cmsBFDdeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
-{
-    double lbfd1,lbfd2,AveC,Aveh,dE,deltaL,
-        deltaC,deltah,dc,t,g,dh,rh,rc,rt,bfd;
-    cmsCIELCh LCh1, LCh2;
+    // This is a rather big number and there is no need of dynamic memory
+    // since we are adding a profile, 254 + 1 = 255 and this is the limit
+    if (nProfiles > 254) return NULL;
 
-
-    if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;
-
-    lbfd1 = ComputeLBFD(Lab1);
-    lbfd2 = ComputeLBFD(Lab2);
-    deltaL = lbfd2 - lbfd1;
-
-    cmsLab2LCh(&LCh1, Lab1);
-    cmsLab2LCh(&LCh2, Lab2);
-
-    deltaC = LCh2.C - LCh1.C;
-    AveC = (LCh1.C+LCh2.C)/2;
-    Aveh = (LCh1.h+LCh2.h)/2;
-
-    dE = cmsDeltaE(Lab1, Lab2);
-
-    if (Sqr(dE)>(Sqr(Lab2->L-Lab1->L)+Sqr(deltaC)))
-        deltah = sqrt(Sqr(dE)-Sqr(Lab2->L-Lab1->L)-Sqr(deltaC));
-    else
-        deltah =0;
-
+    // The output space
+    hLab = cmsCreateLab4ProfileTHR(ContextID, NULL);
+    if (hLab == NULL) return NULL;
 
-    dc   = 0.035 * AveC / (1 + 0.00365 * AveC)+0.521;
-    g    = sqrt(Sqr(Sqr(AveC))/(Sqr(Sqr(AveC))+14000));
-    t    = 0.627+(0.055*cos((Aveh-254)/(180/M_PI))-
-        0.040*cos((2*Aveh-136)/(180/M_PI))+
-        0.070*cos((3*Aveh-31)/(180/M_PI))+
-        0.049*cos((4*Aveh+114)/(180/M_PI))-
-        0.015*cos((5*Aveh-103)/(180/M_PI)));
-
-    dh    = dc*(g*t+1-g);
-    rh    = -0.260*cos((Aveh-308)/(180/M_PI))-
-        0.379*cos((2*Aveh-160)/(180/M_PI))-
-        0.636*cos((3*Aveh+254)/(180/M_PI))+
-        0.226*cos((4*Aveh+140)/(180/M_PI))-
-        0.194*cos((5*Aveh+280)/(180/M_PI));
-
-    rc = sqrt((AveC*AveC*AveC*AveC*AveC*AveC)/((AveC*AveC*AveC*AveC*AveC*AveC)+70000000));
-    rt = rh*rc;
-
-    bfd = sqrt(Sqr(deltaL)+Sqr(deltaC/dc)+Sqr(deltah/dh)+(rt*(deltaC/dc)*(deltah/dh)));
+    // Create a copy of parameters
+    for (i=0; i < nProfiles; i++) {
 
-    return bfd;
-}
-
-
-//  cmc - CMC(1:1) difference between Lab1, Lab2
-double LCMSEXPORT cmsCMCdeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
-{
-  double dE,dL,dC,dh,sl,sc,sh,t,f,cmc;
-  cmsCIELCh LCh1, LCh2;
-
-  if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;
-
-  cmsLab2LCh(&LCh1, Lab1);
-  cmsLab2LCh(&LCh2, Lab2);
-
-
-  dL = Lab2->L-Lab1->L;
-  dC = LCh2.C-LCh1.C;
-
-  dE = cmsDeltaE(Lab1, Lab2);
-  if (Sqr(dE)>(Sqr(dL)+Sqr(dC)))
-            dh = sqrt(Sqr(dE)-Sqr(dL)-Sqr(dC));
-  else
-            dh =0;
+        ProfileList[i]    = hProfiles[i];
+        BPCList[i]        = BPC[i];
+        AdaptationList[i] = AdaptationStates[i];
+        IntentList[i]     = Intents[i];
+    }
 
-  if ((LCh1.h > 164) && (LCh1.h<345))
-      t = 0.56 + fabs(0.2 * cos(((LCh1.h + 168)/(180/M_PI))));
-  else
-      t = 0.36 + fabs(0.4 * cos(((LCh1.h + 35 )/(180/M_PI))));
-
-   sc  = 0.0638   * LCh1.C / (1 + 0.0131  * LCh1.C) + 0.638;
-   sl  = 0.040975 * Lab1->L /(1 + 0.01765 * Lab1->L);
-
-   if (Lab1->L<16)
-         sl = 0.511;
-
-   f   = sqrt((LCh1.C * LCh1.C * LCh1.C * LCh1.C)/((LCh1.C * LCh1.C * LCh1.C * LCh1.C)+1900));
-   sh  = sc*(t*f+1-f);
-   cmc = sqrt(Sqr(dL/sl)+Sqr(dC/sc)+Sqr(dh/sh));
-
-   return cmc;
-}
-
-
+    // Place Lab identity at chain's end.
+    ProfileList[nProfiles]    = hLab;
+    BPCList[nProfiles]        = 0;
+    AdaptationList[nProfiles] = 1.0;
+    IntentList[nProfiles]     = INTENT_RELATIVE_COLORIMETRIC;
 
-static
-double atan2deg(double b, double a)
-{
-   double h;
-
-   if (a == 0 && b == 0)
-            h   = 0;
-    else
-            h = atan2(a, b);
-
-    h *= (180. / M_PI);
+    // Create the transform
+    xform = cmsCreateExtendedTransform(ContextID, nProfiles + 1, ProfileList,
+                                       BPCList,
+                                       IntentList,
+                                       AdaptationList,
+                                       NULL, 0,
+                                       InputFormat,
+                                       OutputFormat,
+                                       dwFlags);
 
-    while (h > 360.)
-        h -= 360.;
-
-    while ( h < 0)
-        h += 360.;
-
-    return h;
+    cmsCloseProfile(hLab);
 
-}
-
-
-static
-double RADIANES(double deg)
-{
-    return (deg * M_PI) / 180.;
+    return xform;
 }
 
 
-// dE2000 The weightings KL, KC and KH can be modified to reflect the relative
-// importance of lightness, chroma and hue in different industrial applications
-
-double LCMSEXPORT cmsCIE2000DeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2,
-                                  double Kl, double Kc, double Kh)
+// Compute K -> L* relationship. Flags may include black point compensation. In this case,
+// the relationship is assumed from the profile with BPC to a black point zero.
+static
+cmsToneCurve* ComputeKToLstar(cmsContext            ContextID,
+                               cmsUInt32Number       nPoints,
+                               cmsUInt32Number       nProfiles,
+                               const cmsUInt32Number Intents[],
+                               const cmsHPROFILE     hProfiles[],
+                               const cmsBool         BPC[],
+                               const cmsFloat64Number AdaptationStates[],
+                               cmsUInt32Number dwFlags)
 {
-    double L1  = Lab1->L;
-    double a1  = Lab1->a;
-    double b1  = Lab1->b;
-    double C   = sqrt( Sqr(a1) + Sqr(b1) );
-
-    double Ls = Lab2 ->L;
-    double as = Lab2 ->a;
-    double bs = Lab2 ->b;
-    double Cs = sqrt( Sqr(as) + Sqr(bs) );
+    cmsToneCurve* out = NULL;
+    cmsUInt32Number i;
+    cmsHTRANSFORM xform;
+    cmsCIELab Lab;
+    cmsFloat32Number cmyk[4];
+    cmsFloat32Number* SampledPoints;
 
-    double G = 0.5 * ( 1 - sqrt(pow((C + Cs) / 2 , 7.0) / (pow((C + Cs) / 2, 7.0) + pow(25.0, 7.0) ) ));
-
-    double a_p = (1 + G ) * a1;
-    double b_p = b1;
-    double C_p = sqrt( Sqr(a_p) + Sqr(b_p));
-    double h_p = atan2deg(a_p, b_p);
-
-
-    double a_ps = (1 + G) * as;
-    double b_ps = bs;
-    double C_ps = sqrt(Sqr(a_ps) + Sqr(b_ps));
-    double h_ps = atan2deg(a_ps, b_ps);
-
-    double meanC_p =(C_p + C_ps) / 2;
-
-    double hps_plus_hp  = h_ps + h_p;
-    double hps_minus_hp = h_ps - h_p;
+    xform = _cmsChain2Lab(ContextID, nProfiles, TYPE_CMYK_FLT, TYPE_Lab_DBL, Intents, hProfiles, BPC, AdaptationStates, dwFlags);
+    if (xform == NULL) return NULL;
 
-    double meanh_p = fabs(hps_minus_hp) <= 180.000001 ? (hps_plus_hp)/2 :
-                            (hps_plus_hp) < 360 ? (hps_plus_hp + 360)/2 :
-                                                 (hps_plus_hp - 360)/2;
+    SampledPoints = (cmsFloat32Number*) _cmsCalloc(ContextID, nPoints, sizeof(cmsFloat32Number));
+    if (SampledPoints  == NULL) goto Error;
+
+    for (i=0; i < nPoints; i++) {
 
-    double delta_h = (hps_minus_hp) <= -180.000001 ?  (hps_minus_hp + 360) :
-                            (hps_minus_hp) > 180 ? (hps_minus_hp - 360) :
-                                                    (hps_minus_hp);
-    double delta_L = (Ls - L1);
-    double delta_C = (C_ps - C_p );
-
-
-    double delta_H =2 * sqrt(C_ps*C_p) * sin(RADIANES(delta_h) / 2);
-
-    double T = 1 - 0.17 * cos(RADIANES(meanh_p-30))
-                 + 0.24 * cos(RADIANES(2*meanh_p))
-                 + 0.32 * cos(RADIANES(3*meanh_p + 6))
-                 - 0.2  * cos(RADIANES(4*meanh_p - 63));
+        cmyk[0] = 0;
+        cmyk[1] = 0;
+        cmyk[2] = 0;
+        cmyk[3] = (cmsFloat32Number) ((i * 100.0) / (nPoints-1));
 
-    double Sl = 1 + (0.015 * Sqr((Ls + L1) /2- 50) )/ sqrt(20 + Sqr( (Ls+L1)/2 - 50) );
+        cmsDoTransform(xform, cmyk, &Lab, 1);
+        SampledPoints[i]= (cmsFloat32Number) (1.0 - Lab.L / 100.0); // Negate K for easier operation
+    }
 
-    double Sc = 1 + 0.045 * (C_p + C_ps)/2;
-    double Sh = 1 + 0.015 * ((C_ps + C_p)/2) * T;
-
-    double delta_ro = 30 * exp( -Sqr(((meanh_p - 275 ) / 25)));
-
-    double Rc = 2 * sqrt(( pow(meanC_p, 7.0) )/( pow(meanC_p, 7.0) + pow(25.0, 7.0)));
+    out = cmsBuildTabulatedToneCurveFloat(ContextID, nPoints, SampledPoints);
 
-    double Rt = -sin(2 * RADIANES(delta_ro)) * Rc;
+Error:
 
-    double deltaE00 = sqrt( Sqr(delta_L /(Sl * Kl)) +
-                            Sqr(delta_C/(Sc * Kc))  +
-                            Sqr(delta_H/(Sh * Kh))  +
-                            Rt*(delta_C/(Sc * Kc)) * (delta_H / (Sh * Kh)));
+    cmsDeleteTransform(xform);
+    if (SampledPoints) _cmsFree(ContextID, SampledPoints);
 
-    return deltaE00;
+    return out;
 }
 
 
-
-// Carefully,  clamp on CIELab space.
-
-void LCMSEXPORT cmsClampLab(LPcmsCIELab Lab, double amax, double amin,
-                                   double bmax, double bmin)
+// Compute Black tone curve on a CMYK -> CMYK transform. This is done by
+// using the proof direction on both profiles to find K->L* relationship
+// then joining both curves. dwFlags may include black point compensation.
+cmsToneCurve* _cmsBuildKToneCurve(cmsContext        ContextID,
+                                   cmsUInt32Number   nPoints,
+                                   cmsUInt32Number   nProfiles,
+                                   const cmsUInt32Number Intents[],
+                                   const cmsHPROFILE hProfiles[],
+                                   const cmsBool     BPC[],
+                                   const cmsFloat64Number AdaptationStates[],
+                                   cmsUInt32Number   dwFlags)
 {
-
-            // Whole Luma surface to zero
-
-        if (Lab -> L < 0) {
-
-                Lab-> L = Lab->a = Lab-> b = 0.0;
-                return;
-            }
+    cmsToneCurve *in, *out, *KTone;
 
-            // Clamp white, DISCARD HIGHLIGHTS. This is done
-            // in such way because icc spec doesn't allow the
-            // use of L>100 as a highlight means.
-
-            if (Lab->L > 100)
-                        Lab -> L = 100;
-
-            // Check out gamut prism, on a, b faces
-
-            if (Lab -> a < amin || Lab->a > amax||
-                Lab -> b < bmin || Lab->b > bmax) {
-
-                 cmsCIELCh LCh;
-                 double h, slope;
-
-                 // Falls outside a, b limits. Transports to LCh space,
-                 // and then do the clipping
+    // Make sure CMYK -> CMYK
+    if (cmsGetColorSpace(hProfiles[0]) != cmsSigCmykData ||
+        cmsGetColorSpace(hProfiles[nProfiles-1])!= cmsSigCmykData) return NULL;
 
 
-                 if (Lab -> a == 0.0) { // Is hue exactly 90?
-
-                        // atan will not work, so clamp here
-                        Lab -> b = Lab->b < 0 ? bmin : bmax;
-                        return;
-                 }
+    // Make sure last is an output profile
+    if (cmsGetDeviceClass(hProfiles[nProfiles - 1]) != cmsSigOutputClass) return NULL;
 
-                 cmsLab2LCh(&LCh, Lab);
-
-                 slope = Lab -> b / Lab -> a;
-                 h = LCh.h;
-
-                 // There are 4 zones
-
-                 if ((h >= 0. && h < 45.) ||
-                     (h >= 315 && h <= 360.)) {
+    // Create individual curves. BPC works also as each K to L* is
+    // computed as a BPC to zero black point in case of L*
+    in  = ComputeKToLstar(ContextID, nPoints, nProfiles - 1, Intents, hProfiles, BPC, AdaptationStates, dwFlags);
+    if (in == NULL) return NULL;
 
-                     // clip by amax
-                     Lab -> a = amax;
-                     Lab -> b = amax * slope;
-                 }
-                 else
-                 if (h >= 45. && h < 135)
-                 {
-                        // clip by bmax
-                        Lab -> b = bmax;
-                        Lab -> a = bmax / slope;
-                 }
-                 else
-                 if (h >= 135 && h < 225) {
-                        // clip by amin
-                        Lab -> a = amin;
-                        Lab -> b = amin * slope;
+    out = ComputeKToLstar(ContextID, nPoints, 1,
+                            Intents + (nProfiles - 1),
+                            hProfiles + (nProfiles - 1),
+                            BPC + (nProfiles - 1),
+                            AdaptationStates + (nProfiles - 1),
+                            dwFlags);
+    if (out == NULL) {
+        cmsFreeToneCurve(in);
+        return NULL;
+    }
 
-                 }
-                 else
-                 if (h >= 225 && h < 315) {
-                        // clip by bmin
-                        Lab -> b = bmin;
-                        Lab -> a = bmin / slope;
-                 }
-                 else
-                        cmsSignalError(LCMS_ERRC_ABORTED, "Invalid angle");
+    // Build the relationship. This effectively limits the maximum accuracy to 16 bits, but
+    // since this is used on black-preserving LUTs, we are not loosing  accuracy in any case
+    KTone = cmsJoinToneCurve(ContextID, in, out, nPoints);
 
-        }
-}
-
-// Several utilities -------------------------------------------------------
-
-// Translate from our colorspace to ICC representation
-
-icColorSpaceSignature LCMSEXPORT _cmsICCcolorSpace(int OurNotation)
-{
-       switch (OurNotation) {
-
-       case 1:
-       case PT_GRAY: return  icSigGrayData;
+    // Get rid of components
+    cmsFreeToneCurve(in); cmsFreeToneCurve(out);
 
-       case 2:
-       case PT_RGB:  return  icSigRgbData;
+    // Something went wrong...
+    if (KTone == NULL) return NULL;
+
+    // Make sure it is monotonic
+    if (!cmsIsToneCurveMonotonic(KTone)) {
 
-       case PT_CMY:  return  icSigCmyData;
-       case PT_CMYK: return  icSigCmykData;
-       case PT_YCbCr:return  icSigYCbCrData;
-       case PT_YUV:  return  icSigLuvData;
-       case PT_XYZ:  return  icSigXYZData;
-       case PT_Lab:  return  icSigLabData;
-       case PT_YUVK: return  icSigLuvKData;
-       case PT_HSV:  return  icSigHsvData;
-       case PT_HLS:  return  icSigHlsData;
-       case PT_Yxy:  return  icSigYxyData;
-       case PT_HiFi: return  icSigHexachromeData;
-       case PT_HiFi7: return icSigHeptachromeData;
-       case PT_HiFi8: return icSigOctachromeData;
+        cmsFreeToneCurve(KTone);
+        return NULL;
+    }
 
-       case PT_HiFi9:  return icSigMCH9Data;
-       case PT_HiFi10: return icSigMCHAData;
-       case PT_HiFi11: return icSigMCHBData;
-       case PT_HiFi12: return icSigMCHCData;
-       case PT_HiFi13: return icSigMCHDData;
-       case PT_HiFi14: return icSigMCHEData;
-       case PT_HiFi15: return icSigMCHFData;
-
-       default:  return icMaxEnumData;
-       }
+    return KTone;
 }
 
 
-int LCMSEXPORT _cmsLCMScolorSpace(icColorSpaceSignature ProfileSpace)
-{
-    switch (ProfileSpace) {
-
-    case icSigGrayData: return  PT_GRAY;
-    case icSigRgbData:  return  PT_RGB;
-    case icSigCmyData:  return  PT_CMY;
-    case icSigCmykData: return  PT_CMYK;
-    case icSigYCbCrData:return  PT_YCbCr;
-    case icSigLuvData:  return  PT_YUV;
-    case icSigXYZData:  return  PT_XYZ;
-    case icSigLabData:  return  PT_Lab;
-    case icSigLuvKData: return  PT_YUVK;
-    case icSigHsvData:  return  PT_HSV;
-    case icSigHlsData:  return  PT_HLS;
-    case icSigYxyData:  return  PT_Yxy;
-
-    case icSig6colorData:
-    case icSigHexachromeData: return PT_HiFi;
-
-    case icSigHeptachromeData:
-    case icSig7colorData:     return PT_HiFi7;
-
-    case icSigOctachromeData:
-    case icSig8colorData:     return PT_HiFi8;
-
-    case icSigMCH9Data:
-    case icSig9colorData:     return PT_HiFi9;
-
-    case icSigMCHAData:
-    case icSig10colorData:     return PT_HiFi10;
-
-    case icSigMCHBData:
-    case icSig11colorData:     return PT_HiFi11;
-
-    case icSigMCHCData:
-    case icSig12colorData:     return PT_HiFi12;
-
-    case icSigMCHDData:
-    case icSig13colorData:     return PT_HiFi13;
-
-    case icSigMCHEData:
-    case icSig14colorData:     return PT_HiFi14;
-
-    case icSigMCHFData:
-    case icSig15colorData:     return PT_HiFi15;
-
-    default:  return icMaxEnumData;
-    }
-}
-
-
-int LCMSEXPORT _cmsChannelsOf(icColorSpaceSignature ColorSpace)
-{
-
-    switch (ColorSpace) {
-
-    case icSigGrayData: return 1;
-
-    case icSig2colorData:  return 2;
-
-    case icSigXYZData:
-    case icSigLabData:
-    case icSigLuvData:
-    case icSigYCbCrData:
-    case icSigYxyData:
-    case icSigRgbData:
-    case icSigHsvData:
-    case icSigHlsData:
-    case icSigCmyData:
-    case icSig3colorData:  return 3;
-
-    case icSigLuvKData:
-    case icSigCmykData:
-    case icSig4colorData:  return 4;
-
-    case icSigMCH5Data:
-    case icSig5colorData:  return 5;
-
-    case icSigHexachromeData:
-    case icSig6colorData:  return 6;
-
-    case icSigHeptachromeData:
-    case icSig7colorData:  return  7;
-
-    case icSigOctachromeData:
-    case icSig8colorData:  return  8;
-
-    case icSigMCH9Data:
-    case icSig9colorData:  return  9;
-
-    case icSigMCHAData:
-    case icSig10colorData: return 10;
-
-    case icSigMCHBData:
-    case icSig11colorData: return 11;
-
-    case icSigMCHCData:
-    case icSig12colorData: return 12;
-
-    case icSigMCHDData:
-    case icSig13colorData: return 13;
-
-    case icSigMCHEData:
-    case icSig14colorData: return 14;
-
-    case icSigMCHFData:
-    case icSig15colorData: return 15;
-
-    default: return 3;
-    }
-
-}
-
-
-// v2 L=100 is supposed to be placed on 0xFF00. There is no reasonable
-// number of gridpoints that would make exact match. However, a
-// prelinearization of 258 entries, would map 0xFF00 on entry 257.
-// This is almost what we need, unfortunately, the rest of entries
-// should be scaled by (255*257/256) and this is not exact.
-//
-// An intermediate solution would be to use 257 entries. This does not
-// map 0xFF00 exactly on a node, but so close that the dE induced is
-// negligible. AND the rest of curve is exact.
-
-static
-void CreateLabPrelinearization(LPGAMMATABLE LabTable[])
-{
-    int i;
-
-    LabTable[0] = cmsAllocGamma(257);
-    LabTable[1] = cmsBuildGamma(257, 1.0);
-    LabTable[2] = cmsBuildGamma(257, 1.0);
-
-    // L* uses 257 entries. Entry 256 holds 0xFFFF, so, the effective range
-    // is 0..0xFF00. Last entry (257) is also collapsed to 0xFFFF
-
-    // From 0 to 0xFF00
-    for (i=0; i < 256; i++)
-        LabTable[0]->GammaTable[i] = RGB_8_TO_16(i);
-
-    // Repeat last for 0xFFFF
-    LabTable[0] ->GammaTable[256] = 0xFFFF;
-}
-
+// Gamut LUT Creation -----------------------------------------------------------------------------------------
 
 // Used by gamut & softproofing
 
 typedef struct {
 
-    cmsHTRANSFORM hInput;               // From whatever input color space. NULL for Lab
+    cmsHTRANSFORM hInput;               // From whatever input color space. 16 bits to DBL
     cmsHTRANSFORM hForward, hReverse;   // Transforms going from Lab to colorant and back
-    double Thereshold;                  // The thereshold after which is considered out of gamut
+    cmsFloat64Number Thereshold;        // The thereshold after which is considered out of gamut
 
-    } GAMUTCHAIN,FAR* LPGAMUTCHAIN;
+    } GAMUTCHAIN;
 
 // This sampler does compute gamut boundaries by comparing original
 // values with a transform going back and forth. Values above ERR_THERESHOLD
 // of maximum are considered out of gamut.
 
-
 #define ERR_THERESHOLD      5
 
 
 static
-int GamutSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
+int GamutSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
 {
-    LPGAMUTCHAIN t = (LPGAMUTCHAIN) Cargo;
-    WORD Proof[MAXCHANNELS], Check[MAXCHANNELS];
-    WORD Proof2[MAXCHANNELS], Check2[MAXCHANNELS];
+    GAMUTCHAIN*  t = (GAMUTCHAIN* ) Cargo;
     cmsCIELab LabIn1, LabOut1;
     cmsCIELab LabIn2, LabOut2;
-    double dE1, dE2, ErrorRatio;
+    cmsFloat32Number Proof[cmsMAXCHANNELS], Proof2[cmsMAXCHANNELS];
+    cmsFloat64Number dE1, dE2, ErrorRatio;
 
     // Assume in-gamut by default.
     dE1 = 0.;
     dE2 = 0;
     ErrorRatio = 1.0;
 
-
-    // Any input space? I can use In[] no matter channels
-    // because is just one pixel
-
-    if (t -> hInput != NULL) cmsDoTransform(t -> hInput, In, In, 1);
+    // Convert input to Lab
+    if (t -> hInput != NULL)
+        cmsDoTransform(t -> hInput, In, &LabIn1, 1);
 
     // converts from PCS to colorant. This always
     // does return in-gamut values,
-    cmsDoTransform(t -> hForward, In, Proof, 1);
+    cmsDoTransform(t -> hForward, &LabIn1, Proof, 1);
 
     // Now, do the inverse, from colorant to PCS.
-    cmsDoTransform(t -> hReverse, Proof, Check, 1);
+    cmsDoTransform(t -> hReverse, Proof, &LabOut1, 1);
 
+    memmove(&LabIn2, &LabOut1, sizeof(cmsCIELab));
 
     // Try again, but this time taking Check as input
-    cmsDoTransform(t -> hForward, Check, Proof2,  1);
-    cmsDoTransform(t -> hReverse, Proof2, Check2, 1);
+    cmsDoTransform(t -> hForward, &LabOut1, Proof2,  1);
+    cmsDoTransform(t -> hReverse, Proof2, &LabOut2, 1);
 
+    // Take difference of direct value
+    dE1 = cmsDeltaE(&LabIn1, &LabOut1);
+
+    // Take difference of converted value
+    dE2 = cmsDeltaE(&LabIn2, &LabOut2);
 
 
-    // Does the transform returns out-of-gamut?
-    if (Check[0] == 0xFFFF &&
-        Check[1] == 0xFFFF &&
-        Check[2] == 0xFFFF)
-
-        Out[0] = 0xFF00;            // Out of gamut!
+    // if dE1 is small and dE2 is small, value is likely to be in gamut
+    if (dE1 < t->Thereshold && dE2 < t->Thereshold)
+        Out[0] = 0;
     else {
 
-        // Transport encoded values
-        cmsLabEncoded2Float(&LabIn1,  In);
-        cmsLabEncoded2Float(&LabOut1, Check);
-
-        // Take difference of direct value
-        dE1 = cmsDeltaE(&LabIn1, &LabOut1);
-
-        cmsLabEncoded2Float(&LabIn2,  Check);
-        cmsLabEncoded2Float(&LabOut2, Check2);
-
-        // Take difference of converted value
-        dE2 = cmsDeltaE(&LabIn2, &LabOut2);
-
-
-        // if dE1 is small and dE2 is small, value is likely to be in gamut
-        if (dE1 < t->Thereshold && dE2 < t->Thereshold)
+        // if dE1 is small and dE2 is big, undefined. Assume in gamut
+        if (dE1 < t->Thereshold && dE2 > t->Thereshold)
             Out[0] = 0;
         else
-            // if dE1 is small and dE2 is big, undefined. Assume in gamut
-            if (dE1 < t->Thereshold && dE2 > t->Thereshold)
-                Out[0] = 0;
-            else
-                // dE1 is big and dE2 is small, clearly out of gamut
-                if (dE1 > t->Thereshold && dE2 < t->Thereshold)
-                    Out[0] = (WORD) _cmsQuickFloor((dE1 - t->Thereshold) + .5);
-                else  {
+            // dE1 is big and dE2 is small, clearly out of gamut
+            if (dE1 > t->Thereshold && dE2 < t->Thereshold)
+                Out[0] = (cmsUInt16Number) _cmsQuickFloor((dE1 - t->Thereshold) + .5);
+            else  {
 
-                    // dE1 is big and dE2 is also big, could be due to perceptual mapping
-                    // so take error ratio
-                    if (dE2 == 0.0)
-                        ErrorRatio = dE1;
-                    else
-                        ErrorRatio = dE1 / dE2;
+                // dE1 is big and dE2 is also big, could be due to perceptual mapping
+                // so take error ratio
+                if (dE2 == 0.0)
+                    ErrorRatio = dE1;
+                else
+                    ErrorRatio = dE1 / dE2;
 
-                    if (ErrorRatio > t->Thereshold)
-                        Out[0] = (WORD)  _cmsQuickFloor((ErrorRatio - t->Thereshold) + .5);
-                    else
-                        Out[0] = 0;
-                }
+                if (ErrorRatio > t->Thereshold)
+                    Out[0] = (cmsUInt16Number)  _cmsQuickFloor((ErrorRatio - t->Thereshold) + .5);
+                else
+                    Out[0] = 0;
+            }
+    }
 
-    }
 
     return TRUE;
 }
 
-
-// Does compute a gamut LUT going back and forth across
-// pcs -> relativ. colorimetric intent -> pcs
-// the dE obtained is then annotated on the LUT.
-// values truely out of gamut, are clipped to dE = 0xFFFE
-// and values changed are supposed to be handled by
-// any gamut remapping, so, are out of gamut as well.
+// Does compute a gamut LUT going back and forth across pcs -> relativ. colorimetric intent -> pcs
+// the dE obtained is then annotated on the LUT. Values truely out of gamut are clipped to dE = 0xFFFE
+// and values changed are supposed to be handled by any gamut remapping, so, are out of gamut as well.
 //
-// **WARNING: This algorithm does assume that gamut
-// remapping algorithms does NOT move in-gamut colors,
-// of course, many perceptual and saturation intents does
-// not work in such way, but relativ. ones should.
+// **WARNING: This algorithm does assume that gamut remapping algorithms does NOT move in-gamut colors,
+// of course, many perceptual and saturation intents does not work in such way, but relativ. ones should.
 
-static
-LPLUT ComputeGamutWithInput(cmsHPROFILE hInput, cmsHPROFILE hProfile, int Intent)
+cmsPipeline* _cmsCreateGamutCheckPipeline(cmsContext ContextID,
+                                          cmsHPROFILE hProfiles[],
+                                          cmsBool  BPC[],
+                                          cmsUInt32Number Intents[],
+                                          cmsFloat64Number AdaptationStates[],
+                                          cmsUInt32Number nGamutPCSposition,
+                                          cmsHPROFILE hGamut)
 {
     cmsHPROFILE hLab;
-    LPLUT Gamut;
-    DWORD dwFormat;
+    cmsPipeline* Gamut;
+    cmsStage* CLUT;
+    cmsUInt32Number dwFormat;
     GAMUTCHAIN Chain;
-    int nErrState, nChannels, nGridpoints;
-    LPGAMMATABLE Trans[3];
-    icColorSpaceSignature ColorSpace;
+    int nChannels, nGridpoints;
+    cmsColorSpaceSignature ColorSpace;
+    cmsUInt32Number i;
+    cmsHPROFILE ProfileList[256];
+    cmsBool     BPCList[256];
+    cmsFloat64Number AdaptationList[256];
+    cmsUInt32Number IntentList[256];
+
+    memset(&Chain, 0, sizeof(GAMUTCHAIN));
 
 
-    ZeroMemory(&Chain, sizeof(GAMUTCHAIN));
+    if (nGamutPCSposition <= 0 || nGamutPCSposition > 255) {
+        cmsSignalError(ContextID, cmsERROR_RANGE, "Wrong position of PCS. 1..255 expected, %d found.", nGamutPCSposition);
+        return NULL;
+    }
 
-    hLab = cmsCreateLabProfile(NULL);
+    hLab = cmsCreateLab4ProfileTHR(ContextID, NULL);
+    if (hLab == NULL) return NULL;
 
-    // Safeguard against early abortion
-    nErrState = cmsErrorAction(LCMS_ERROR_IGNORE);
 
     // The figure of merit. On matrix-shaper profiles, should be almost zero as
     // the conversion is pretty exact. On LUT based profiles, different resolutions
     // of input and output CLUT may result in differences.
 
-    if (!cmsIsIntentSupported(hProfile, Intent, LCMS_USED_AS_INPUT) &&
-        !cmsIsIntentSupported(hProfile, Intent, LCMS_USED_AS_OUTPUT))
+    if (cmsIsMatrixShaper(hGamut)) {
 
         Chain.Thereshold = 1.0;
-    else
+    }
+    else {
         Chain.Thereshold = ERR_THERESHOLD;
-
-    ColorSpace  = cmsGetColorSpace(hProfile);
-
-    // If input profile specified, create a transform from such profile to Lab
-    if (hInput != NULL) {
-
-        nChannels   = _cmsChannelsOf(ColorSpace);
-        nGridpoints = _cmsReasonableGridpointsByColorspace(ColorSpace, cmsFLAGS_HIGHRESPRECALC);
-        dwFormat    = (CHANNELS_SH(nChannels)|BYTES_SH(2));
-
-        Chain.hInput = cmsCreateTransform(hInput, dwFormat,
-                                          hLab,   TYPE_Lab_16,
-                                          Intent,
-                                          cmsFLAGS_NOTPRECALC);
-    }
-    else  {
-        // Input transform=NULL (Lab) Used to compute the gamut tag
-        // This table will take 53 points to give some accurancy,
-        // 53 * 53 * 53 * 2 = 291K
-
-        nChannels    = 3;      // For Lab
-        nGridpoints  = 53;
-        Chain.hInput = NULL;
-        dwFormat = (CHANNELS_SH(_cmsChannelsOf(ColorSpace))|BYTES_SH(2));
     }
 
 
-    // Does create the forward step
-    Chain.hForward = cmsCreateTransform(hLab, TYPE_Lab_16,
-                                        hProfile, dwFormat,
-                                        INTENT_RELATIVE_COLORIMETRIC,
-                                        cmsFLAGS_NOTPRECALC);
+    // Create a copy of parameters
+    for (i=0; i < nGamutPCSposition; i++) {
+        ProfileList[i]    = hProfiles[i];
+        BPCList[i]        = BPC[i];
+        AdaptationList[i] = AdaptationStates[i];
+        IntentList[i]     = Intents[i];
+    }
+
+    // Fill Lab identity
+    ProfileList[nGamutPCSposition] = hLab;
+    BPCList[nGamutPCSposition] = 0;
+    AdaptationList[nGamutPCSposition] = 1.0;
+    Intents[nGamutPCSposition] = INTENT_RELATIVE_COLORIMETRIC;
+
+
+    ColorSpace  = cmsGetColorSpace(hGamut);
+
+    nChannels   = cmsChannelsOf(ColorSpace);
+    nGridpoints = _cmsReasonableGridpointsByColorspace(ColorSpace, cmsFLAGS_HIGHRESPRECALC);
+    dwFormat    = (CHANNELS_SH(nChannels)|BYTES_SH(2));
+
+    // 16 bits to Lab double
+    Chain.hInput = cmsCreateExtendedTransform(ContextID,
+                                              nGamutPCSposition + 1,
+                                              ProfileList,
+                                              BPCList,
+                                              Intents,
+                                              AdaptationList,
+                                              NULL, 0,
+                                              dwFormat, TYPE_Lab_DBL,
+                                              cmsFLAGS_NOCACHE);
+
+
+    // Does create the forward step. Lab double to cmsFloat32Number
+    dwFormat    = (FLOAT_SH(1)|CHANNELS_SH(nChannels)|BYTES_SH(4));
+    Chain.hForward = cmsCreateTransformTHR(ContextID,
+                                           hLab, TYPE_Lab_DBL,
+                                           hGamut, dwFormat,
+                                           INTENT_RELATIVE_COLORIMETRIC,
+                                           cmsFLAGS_NOCACHE);
 
     // Does create the backwards step
-    Chain.hReverse = cmsCreateTransform(hProfile, dwFormat,
-                                        hLab, TYPE_Lab_16,
-                                        INTENT_RELATIVE_COLORIMETRIC,
-                                        cmsFLAGS_NOTPRECALC);
-
-    // Restores error handler previous state
-    cmsErrorAction(nErrState);
+    Chain.hReverse = cmsCreateTransformTHR(ContextID, hGamut, dwFormat,
+                                           hLab, TYPE_Lab_DBL,
+                                           INTENT_RELATIVE_COLORIMETRIC,
+                                           cmsFLAGS_NOCACHE);
 
 
     // All ok?
     if (Chain.hForward && Chain.hReverse) {
 
-    // Go on, try to compute gamut LUT from PCS.
-    // This consist on a single channel containing
-    // dE when doing a transform back and forth on
-    // the colorimetric intent.
+        // Go on, try to compute gamut LUT from PCS. This consist on a single channel containing
+        // dE when doing a transform back and forth on the colorimetric intent.
 
-    Gamut = cmsAllocLUT();
-    Gamut = cmsAlloc3DGrid(Gamut, nGridpoints, nChannels, 1);
+        Gamut = cmsPipelineAlloc(ContextID, 3, 1);
 
-    // If no input, then this is a gamut tag operated by Lab,
-    // so include pertinent prelinearization
-    if (hInput == NULL) {
+        if (Gamut != NULL) {
 
-        CreateLabPrelinearization(Trans);
-        cmsAllocLinearTable(Gamut, Trans, 1);
-        cmsFreeGammaTriple(Trans);
-    }
+            CLUT = cmsStageAllocCLut16bit(ContextID, nGridpoints, nChannels, 1, NULL);
+            cmsPipelineInsertStage(Gamut, cmsAT_BEGIN, CLUT);
 
-
-    cmsSample3DGrid(Gamut, GamutSampler, (LPVOID) &Chain, Gamut ->wFlags);
+            cmsStageSampleCLut16bit(CLUT, GamutSampler, (void*) &Chain, 0);
+        }
     }
     else
         Gamut = NULL;   // Didn't work...
@@ -921,352 +434,187 @@
     if (Chain.hInput)   cmsDeleteTransform(Chain.hInput);
     if (Chain.hForward) cmsDeleteTransform(Chain.hForward);
     if (Chain.hReverse) cmsDeleteTransform(Chain.hReverse);
-
-    cmsCloseProfile(hLab);
+    if (hLab) cmsCloseProfile(hLab);
 
     // And return computed hull
     return Gamut;
 }
 
-
-// Wrapper
+// Total Area Coverage estimation ----------------------------------------------------------------
 
-LPLUT _cmsComputeGamutLUT(cmsHPROFILE hProfile, int Intent)
-{
-    return ComputeGamutWithInput(NULL, hProfile, Intent);
-}
+typedef struct {
+    cmsUInt32Number  nOutputChans;
+    cmsHTRANSFORM    hRoundTrip;
+    cmsFloat32Number MaxTAC;
+    cmsFloat32Number MaxInput[cmsMAXCHANNELS];
+
+} cmsTACestimator;
 
 
-// This routine does compute the gamut check CLUT. This CLUT goes from whatever
-// input space to the 0 or != 0 gamut check.
+// This callback just accounts the maximum ink dropped in the given node. It does not populate any
+// memory, as the destination table is NULL. Its only purpose it to know the global maximum.
+static
+int EstimateTAC(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void * Cargo)
+{
+    cmsTACestimator* bp = (cmsTACestimator*) Cargo;
+    cmsFloat32Number RoundTrip[cmsMAXCHANNELS];
+    cmsUInt32Number i;
+    cmsFloat32Number Sum;
+
+
+    // Evaluate the xform
+    cmsDoTransform(bp->hRoundTrip, In, RoundTrip, 1);
 
-LPLUT _cmsPrecalculateGamutCheck(cmsHTRANSFORM h)
-{
-       _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) h;
+    // All all amounts of ink
+    for (Sum=0, i=0; i < bp ->nOutputChans; i++)
+            Sum += RoundTrip[i];
+
+    // If above maximum, keep track of input values
+    if (Sum > bp ->MaxTAC) {
+
+            bp ->MaxTAC = Sum;
 
-       return ComputeGamutWithInput(p->InputProfile, p ->PreviewProfile, p->Intent);
+            for (i=0; i < bp ->nOutputChans; i++) {
+                bp ->MaxInput[i] = In[i];
+            }
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(Out);
 }
 
 
-// SoftProofing. Convert from Lab to device, then back to Lab,
-// any gamut remapping is applied
-
-static
-int SoftProofSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
+// Detect Total area coverage of the profile
+cmsFloat64Number CMSEXPORT cmsDetectTAC(cmsHPROFILE hProfile)
 {
-        LPGAMUTCHAIN t = (LPGAMUTCHAIN) Cargo;
-        WORD Colorant[MAXCHANNELS];
+    cmsTACestimator bp;
+    cmsUInt32Number dwFormatter;
+    cmsUInt32Number GridPoints[MAX_INPUT_DIMENSIONS];
+    cmsHPROFILE hLab;
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
-        // From pcs to colorant
-        cmsDoTransform(t -> hForward, In, Colorant, 1);
+    // TAC only works on output profiles
+    if (cmsGetDeviceClass(hProfile) != cmsSigOutputClass) {
+        return 0;
+    }
+
+    // Create a fake formatter for result
+    dwFormatter = cmsFormatterForColorspaceOfProfile(hProfile, 4, TRUE);
 
-        // Now, do the inverse, from colorant to pcs.
-        cmsDoTransform(t -> hReverse, Colorant, Out, 1);
+    bp.nOutputChans = T_CHANNELS(dwFormatter);
+    bp.MaxTAC = 0;    // Initial TAC is 0
 
-        return TRUE;
-}
-
-// Does return Softproofing LUT on desired intent
+    //  for safety
+    if (bp.nOutputChans >= cmsMAXCHANNELS) return 0;
 
-LPLUT _cmsComputeSoftProofLUT(cmsHPROFILE hProfile, int nIntent)
-{
-    cmsHPROFILE hLab;
-    LPLUT SoftProof;
-    DWORD dwFormat;
-    GAMUTCHAIN Chain;
-    int nErrState;
-    LPGAMMATABLE Trans[3];
+    hLab = cmsCreateLab4ProfileTHR(ContextID, NULL);
+    if (hLab == NULL) return 0;
+    // Setup a roundtrip on perceptual intent in output profile for TAC estimation
+    bp.hRoundTrip = cmsCreateTransformTHR(ContextID, hLab, TYPE_Lab_16,
+                                          hProfile, dwFormatter, INTENT_PERCEPTUAL, cmsFLAGS_NOOPTIMIZE|cmsFLAGS_NOCACHE);
+
+    cmsCloseProfile(hLab);
+    if (bp.hRoundTrip == NULL) return 0;
+
+    // For L* we only need black and white. For C* we need many points
+    GridPoints[0] = 6;
+    GridPoints[1] = 74;
+    GridPoints[2] = 74;
 
 
-    // LUTs are never abs. colorimetric, is the transform who
-    // is responsible of generating white point displacement
-    if (nIntent == INTENT_ABSOLUTE_COLORIMETRIC)
-        nIntent = INTENT_RELATIVE_COLORIMETRIC;
-
-    ZeroMemory(&Chain, sizeof(GAMUTCHAIN));
-
-    hLab = cmsCreateLabProfile(NULL);
-
-    // ONLY 4 channels
-    dwFormat = (CHANNELS_SH(4)|BYTES_SH(2));
-
-    // Safeguard against early abortion
-    nErrState = cmsErrorAction(LCMS_ERROR_IGNORE);
-
-    // Does create the first step
-    Chain.hForward = cmsCreateTransform(hLab, TYPE_Lab_16,
-                                        hProfile, dwFormat,
-                                        nIntent,
-                                        cmsFLAGS_NOTPRECALC);
-
-    // Does create the last step
-    Chain.hReverse = cmsCreateTransform(hProfile, dwFormat,
-                                        hLab, TYPE_Lab_16,
-                                        INTENT_RELATIVE_COLORIMETRIC,
-                                        cmsFLAGS_NOTPRECALC);
+    if (!cmsSliceSpace16(3, GridPoints, EstimateTAC, &bp)) {
+        bp.MaxTAC = 0;
+    }
 
-    // Restores error handler previous state
-    cmsErrorAction(nErrState);
-
-    // All ok?
-    if (Chain.hForward && Chain.hReverse) {
-
-    // This is Lab -> Lab, so 33 point should hold anything
-    SoftProof = cmsAllocLUT();
-    SoftProof = cmsAlloc3DGrid(SoftProof, 33, 3, 3);
+    cmsDeleteTransform(bp.hRoundTrip);
 
-    CreateLabPrelinearization(Trans);
-    cmsAllocLinearTable(SoftProof, Trans, 1);
-    cmsFreeGammaTriple(Trans);
-
-    cmsSample3DGrid(SoftProof, SoftProofSampler, (LPVOID) &Chain, SoftProof->wFlags);
-    }
-    else
-        SoftProof = NULL;   // Didn't work...
-
-    // Free all needed stuff.
-    if (Chain.hForward) cmsDeleteTransform(Chain.hForward);
-    if (Chain.hReverse) cmsDeleteTransform(Chain.hReverse);
-
-    cmsCloseProfile(hLab);
-
-    return SoftProof;
+    // Results in %
+    return bp.MaxTAC;
 }
 
 
-static
-int MostlyLinear(WORD Table[], int nEntries)
+// Carefully,  clamp on CIELab space.
+
+cmsBool CMSEXPORT cmsDesaturateLab(cmsCIELab* Lab,
+                                   double amax, double amin,
+                                   double bmax, double bmin)
 {
-       register int i;
-       int diff;
+
+    // Whole Luma surface to zero
 
-       for (i=5; i < nEntries; i++) {
+    if (Lab -> L < 0) {
+
+        Lab-> L = Lab->a = Lab-> b = 0.0;
+        return FALSE;
+    }
 
-           diff = abs((int) Table[i] - (int) _cmsQuantizeVal(i, nEntries));
-           if (diff > 0x0300)
-                     return 0;
-       }
+    // Clamp white, DISCARD HIGHLIGHTS. This is done
+    // in such way because icc spec doesn't allow the
+    // use of L>100 as a highlight means.
+
+    if (Lab->L > 100)
+        Lab -> L = 100;
+
+    // Check out gamut prism, on a, b faces
 
-       return 1;
-}
+    if (Lab -> a < amin || Lab->a > amax||
+        Lab -> b < bmin || Lab->b > bmax) {
+
+            cmsCIELCh LCh;
+            double h, slope;
+
+            // Falls outside a, b limits. Transports to LCh space,
+            // and then do the clipping
 
 
-static
-void SlopeLimiting(WORD Table[], int nEntries)
-{
-    int At = (int) floor((double) nEntries * 0.02 + 0.5);   // Cutoff at 2%
-    double Val, Slope;
-    int i;
+            if (Lab -> a == 0.0) { // Is hue exactly 90?
+
+                // atan will not work, so clamp here
+                Lab -> b = Lab->b < 0 ? bmin : bmax;
+                return TRUE;
+            }
 
-    Val   = Table[At];
-    Slope = Val / At;
+            cmsLab2LCh(&LCh, Lab);
+
+            slope = Lab -> b / Lab -> a;
+            h = LCh.h;
 
-    for (i=0; i < At; i++)
-        Table[i] = (WORD) floor(i * Slope + 0.5);
+            // There are 4 zones
 
-}
-
+            if ((h >= 0. && h < 45.) ||
+                (h >= 315 && h <= 360.)) {
 
-// Check for monotonicity.
-
-static
-LCMSBOOL IsMonotonic(LPGAMMATABLE t)
-{
-    int n = t -> nEntries;
-    int i, last;
+                    // clip by amax
+                    Lab -> a = amax;
+                    Lab -> b = amax * slope;
+            }
+            else
+                if (h >= 45. && h < 135.)
+                {
+                    // clip by bmax
+                    Lab -> b = bmax;
+                    Lab -> a = bmax / slope;
+                }
+                else
+                    if (h >= 135. && h < 225.) {
+                        // clip by amin
+                        Lab -> a = amin;
+                        Lab -> b = amin * slope;
 
-    last = t ->GammaTable[n-1];
-
-    for (i = n-2; i >= 0; --i) {
-
-        if (t ->GammaTable[i] > last)
-
-               return FALSE;
-        else
-                last = t ->GammaTable[i];
+                    }
+                    else
+                        if (h >= 225. && h < 315.) {
+                            // clip by bmin
+                            Lab -> b = bmin;
+                            Lab -> a = bmin / slope;
+                        }
+                        else  {
+                            cmsSignalError(0, cmsERROR_RANGE, "Invalid angle");
+                            return FALSE;
+                        }
 
     }
 
     return TRUE;
 }
-
-// Check for endpoints
-
-static
-LCMSBOOL HasProperEndpoints(LPGAMMATABLE t)
-{
-    if (t ->GammaTable[0] != 0) return FALSE;
-    if (t ->GammaTable[t ->nEntries-1] != 0xFFFF) return FALSE;
-
-    return TRUE;
-}
-
-
-
-#define PRELINEARIZATION_POINTS 4096
-
-// Fixes the gamma balancing of transform. Thanks to Mike Chaney
-// for pointing this subtle bug.
-
-void _cmsComputePrelinearizationTablesFromXFORM(cmsHTRANSFORM h[], int nTransforms, LPLUT Grid)
-{
-    LPGAMMATABLE Trans[MAXCHANNELS];
-    unsigned int t, i, v;
-    int j;
-    WORD In[MAXCHANNELS], Out[MAXCHANNELS];
-    LCMSBOOL lIsSuitable;
-    _LPcmsTRANSFORM InputXForm   = (_LPcmsTRANSFORM) h[0];
-    _LPcmsTRANSFORM OutputXForm  = (_LPcmsTRANSFORM) h[nTransforms-1];
-
-
-    // First space is *Lab, use our specialized curves for v2 Lab
-
-    if (InputXForm ->EntryColorSpace == icSigLabData &&
-        OutputXForm->ExitColorSpace != icSigLabData) {
-
-                CreateLabPrelinearization(Trans);
-                cmsAllocLinearTable(Grid, Trans, 1);
-                cmsFreeGammaTriple(Trans);
-                return;
-    }
-
-
-    // Do nothing on all but Gray/RGB to Gray/RGB transforms
-
-    if (((InputXForm ->EntryColorSpace != icSigRgbData) && (InputXForm ->EntryColorSpace != icSigGrayData)) ||
-        ((OutputXForm->ExitColorSpace  != icSigRgbData) && (OutputXForm->ExitColorSpace  != icSigGrayData))) return;
-
-
-    for (t = 0; t < Grid -> InputChan; t++)
-            Trans[t] = cmsAllocGamma(PRELINEARIZATION_POINTS);
-
-    for (i=0; i < PRELINEARIZATION_POINTS; i++) {
-
-                v = _cmsQuantizeVal(i, PRELINEARIZATION_POINTS);
-
-                for (t=0; t < Grid -> InputChan; t++)
-                        In[t] = (WORD) v;
-
-                cmsDoTransform(h[0], In, Out, 1);
-                for (j=1; j < nTransforms; j++)
-                        cmsDoTransform(h[j], Out, Out, 1);
-
-                for (t=0; t < Grid -> InputChan; t++)
-                        Trans[t] ->GammaTable[i] = Out[t];
-
-    }
-
-
-    // Check transfer curves
-    lIsSuitable = TRUE;
-    for (t=0; (lIsSuitable && (t < Grid->InputChan)); t++) {
-
-
-        // Exclude if already linear
-        if (MostlyLinear(Trans[t]->GammaTable, PRELINEARIZATION_POINTS))
-                    lIsSuitable = FALSE;
-
-        // Exclude if non-monotonic
-        if (!IsMonotonic(Trans[t]))
-                    lIsSuitable = FALSE;
-
-        // Exclude if weird endpoints
-        if (!HasProperEndpoints(Trans[t]))
-                    lIsSuitable = FALSE;
-
-        /*
-        // Exclude if transfer function is not smooth enough
-        // to be modelled as a gamma function, or the gamma is reversed
-
-        if (cmsEstimateGamma(Trans[t]) < 1.0)
-                    lIsSuitable = FALSE;
-        */
-
-    }
-
-    if (lIsSuitable) {
-
-            for (t = 0; t < Grid ->InputChan; t++)
-                SlopeLimiting(Trans[t]->GammaTable, Trans[t]->nEntries);
-    }
-
-    if (lIsSuitable) cmsAllocLinearTable(Grid, Trans, 1);
-
-
-    for (t = 0; t < Grid ->InputChan; t++)
-                        cmsFreeGamma(Trans[t]);
-
-
-}
-
-
-// Compute K -> L* relationship. Flags may include black point compensation. In this case,
-// the relationship is assumed from the profile with BPC to a black point zero.
-static
-LPGAMMATABLE ComputeKToLstar(cmsHPROFILE hProfile, int nPoints, int Intent, DWORD dwFlags)
-{
-    LPGAMMATABLE out;
-    int i;
-    WORD cmyk[4], wLab[3];
-    cmsHPROFILE   hLab  = cmsCreateLabProfile(NULL);
-    cmsHTRANSFORM xform = cmsCreateTransform(hProfile, TYPE_CMYK_16,
-                                             hLab, TYPE_Lab_16,
-                                             Intent, (dwFlags|cmsFLAGS_NOTPRECALC));
-
-
-    out = cmsAllocGamma(nPoints);
-    for (i=0; i < nPoints; i++) {
-
-        cmyk[0] = 0;
-        cmyk[1] = 0;
-        cmyk[2] = 0;
-        cmyk[3] = _cmsQuantizeVal(i, nPoints);
-
-        cmsDoTransform(xform, cmyk, wLab, 1);
-        out->GammaTable[i] = (WORD) (0xFFFF - wLab[0]);
-    }
-
-    cmsDeleteTransform(xform);
-    cmsCloseProfile(hLab);
-
-    return out;
-}
-
-
-
-// Compute Black tone curve on a CMYK -> CMYK transform. This is done by
-// using the proof direction on both profiles to find K->L* relationship
-// then joining both curves. dwFlags may include black point compensation.
-
-LPGAMMATABLE _cmsBuildKToneCurve(cmsHTRANSFORM hCMYK2CMYK, int nPoints)
-{
-    LPGAMMATABLE in, out;
-    LPGAMMATABLE KTone;
-    _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) hCMYK2CMYK;
-
-
-    // Make sure CMYK -> CMYK
-    if (p -> EntryColorSpace != icSigCmykData ||
-        p -> ExitColorSpace  != icSigCmykData) return NULL;
-
-    // Create individual curves. BPC works also as each K to L* is
-    // computed as a BPC to zero black point in case of L*
-    in  = ComputeKToLstar(p ->InputProfile,  nPoints, p->Intent, p -> dwOriginalFlags);
-    out = ComputeKToLstar(p ->OutputProfile, nPoints, p->Intent, p -> dwOriginalFlags);
-
-    // Build the relationship
-    KTone = cmsJoinGamma(in, out);
-
-    cmsFreeGamma(in); cmsFreeGamma(out);
-
-    // Make sure it is monotonic
-
-    if (!IsMonotonic(KTone)) {
-
-        cmsFreeGamma(KTone);
-        return NULL;
-    }
-
-
-    return KTone;
-}
--- a/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,667 +49,341 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
 
-// Interpolation
-
-#include "lcms.h"
+#include "lcms2_internal.h"
 
-void cmsCalcL16Params(int nSamples, LPL16PARAMS p)
-{
-       p -> nSamples = nSamples;
-       p -> Domain   = (WORD) (nSamples - 1);
-       p -> nInputs = p -> nOutputs = 1;
+// This module incorporates several interpolation routines, for 1, 3, 4, 5, 6, 7 and 8 channels on input and
+// up to 65535 channels on output. The user may change those by using the interpolation plug-in
 
-}
+// Interpolation routines by default
+static cmsInterpFunction DefaultInterpolatorsFactory(cmsUInt32Number nInputChannels, cmsUInt32Number nOutputChannels, cmsUInt32Number dwFlags);
 
+// This is the default factory
+static cmsInterpFnFactory Interpolators = DefaultInterpolatorsFactory;
 
 
-// Eval gray LUT having only one input channel
+// Main plug-in entry
+cmsBool  _cmsRegisterInterpPlugin(cmsPluginBase* Data)
+{
+    cmsPluginInterpolation* Plugin = (cmsPluginInterpolation*) Data;
 
-static
-void Eval1Input(WORD StageABC[], WORD StageLMN[], WORD LutTable[], LPL16PARAMS p16)
-{
-       Fixed32 fk;
-       Fixed32 k0, k1, rk, K0, K1;
-       int OutChan;
+    if (Data == NULL) {
 
-       fk = ToFixedDomain((Fixed32) StageABC[0] * p16 -> Domain);
-       k0 = FIXED_TO_INT(fk);
-       rk = (WORD) FIXED_REST_TO_INT(fk);
-
-       k1 = k0 + (StageABC[0] != 0xFFFFU ? 1 : 0);
+        Interpolators = DefaultInterpolatorsFactory;
+        return TRUE;
+    }
 
-       K0 = p16 -> opta1 * k0;
-       K1 = p16 -> opta1 * k1;
-
-       for (OutChan=0; OutChan < p16->nOutputs; OutChan++) {
-
-           StageLMN[OutChan] = (WORD) FixedLERP(rk, LutTable[K0+OutChan],
-                                                    LutTable[K1+OutChan]);
-       }
+    // Set replacement functions
+    Interpolators = Plugin ->InterpolatorsFactory;
+    return TRUE;
 }
 
 
-
-// For more that 3 inputs (i.e., CMYK)
-// evaluate two 3-dimensional interpolations and then linearly interpolate between them.
+// Set the interpolation method
 static
-void Eval4Inputs(WORD StageABC[], WORD StageLMN[], WORD LutTable[], LPL16PARAMS p16)
+cmsBool _cmsSetInterpolationRoutine(cmsInterpParams* p)
 {
-       Fixed32 fk;
-       Fixed32 k0, rk;
-       int K0, K1;
-       LPWORD T;
-       int i;
-       WORD Tmp1[MAXCHANNELS], Tmp2[MAXCHANNELS];
-
-
-       fk = ToFixedDomain((Fixed32) StageABC[0] * p16 -> Domain);
-       k0 = FIXED_TO_INT(fk);
-       rk = FIXED_REST_TO_INT(fk);
-
-       K0 = p16 -> opta4 * k0;
-       K1 = p16 -> opta4 * (k0 + (StageABC[0] != 0xFFFFU ? 1 : 0));
-
-       p16 -> nInputs = 3;
-
-       T = LutTable + K0;
-
-       cmsTetrahedralInterp16(StageABC + 1,  Tmp1, T, p16);
-
-
-       T = LutTable + K1;
-
-       cmsTetrahedralInterp16(StageABC + 1,  Tmp2, T, p16);
-
-
-       p16 -> nInputs = 4;
-       for (i=0; i < p16 -> nOutputs; i++)
-       {
-              StageLMN[i] = (WORD) FixedLERP(rk, Tmp1[i], Tmp2[i]);
+    // Invoke factory, possibly in the Plug-in
+    p ->Interpolation = Interpolators(p -> nInputs, p ->nOutputs, p ->dwFlags);
 
-       }
-
-}
-
-
-static
-void Eval5Inputs(WORD StageABC[], WORD StageLMN[], WORD LutTable[], LPL16PARAMS p16)
-{
-       Fixed32 fk;
-       Fixed32 k0, rk;
-       int K0, K1;
-       LPWORD T;
-       int i;
-       WORD Tmp1[MAXCHANNELS], Tmp2[MAXCHANNELS];
-
-
-       fk = ToFixedDomain((Fixed32) StageABC[0] * p16 -> Domain);
-       k0 = FIXED_TO_INT(fk);
-       rk = FIXED_REST_TO_INT(fk);
+    // If unsupported by the plug-in, go for the LittleCMS default.
+    // If happens only if an extern plug-in is being used
+    if (p ->Interpolation.Lerp16 == NULL)
+        p ->Interpolation = DefaultInterpolatorsFactory(p ->nInputs, p ->nOutputs, p ->dwFlags);
 
-       K0 = p16 -> opta5 * k0;
-       K1 = p16 -> opta5 * (k0 + (StageABC[0] != 0xFFFFU ? 1 : 0));
-
-       p16 -> nInputs = 4;
-
-       T = LutTable + K0;
-
-       Eval4Inputs(StageABC + 1, Tmp1, T, p16);
-
-       T = LutTable + K1;
-
-       Eval4Inputs(StageABC + 1, Tmp2, T, p16);
-
-       p16 -> nInputs = 5;
-       for (i=0; i < p16 -> nOutputs; i++)
-       {
-              StageLMN[i] = (WORD) FixedLERP(rk, Tmp1[i], Tmp2[i]);
-
-       }
-
+    // Check for valid interpolator (we just check one member of the union)
+    if (p ->Interpolation.Lerp16 == NULL) {
+            return FALSE;
+    }
+    return TRUE;
 }
 
 
-static
-void Eval6Inputs(WORD StageABC[], WORD StageLMN[], WORD LutTable[], LPL16PARAMS p16)
+// This function precalculates as many parameters as possible to speed up the interpolation.
+cmsInterpParams* _cmsComputeInterpParamsEx(cmsContext ContextID,
+                                           const cmsUInt32Number nSamples[],
+                                           int InputChan, int OutputChan,
+                                           const void *Table,
+                                           cmsUInt32Number dwFlags)
 {
-       Fixed32 fk;
-       Fixed32 k0, rk;
-       int K0, K1;
-       LPWORD T;
-       int i;
-       WORD Tmp1[MAXCHANNELS], Tmp2[MAXCHANNELS];
-
+    cmsInterpParams* p;
+    int i;
 
-       fk = ToFixedDomain((Fixed32) StageABC[0] * p16 -> Domain);
-       k0 = FIXED_TO_INT(fk);
-       rk = FIXED_REST_TO_INT(fk);
-
-       K0 = p16 -> opta6 * k0;
-       K1 = p16 -> opta6 * (k0 + (StageABC[0] != 0xFFFFU ? 1 : 0));
-
-       p16 -> nInputs = 5;
-
-       T = LutTable + K0;
+    // Check for maximum inputs
+    if (InputChan > MAX_INPUT_DIMENSIONS) {
+             cmsSignalError(ContextID, cmsERROR_RANGE, "Too many input channels (%d channels, max=%d)", InputChan, MAX_INPUT_DIMENSIONS);
+            return NULL;
+    }
 
-       Eval5Inputs(StageABC + 1, Tmp1, T, p16);
-
-       T = LutTable + K1;
-
-       Eval5Inputs(StageABC + 1, Tmp2, T, p16);
+    // Creates an empty object
+    p = (cmsInterpParams*) _cmsMallocZero(ContextID, sizeof(cmsInterpParams));
+    if (p == NULL) return NULL;
 
-       p16 -> nInputs = 6;
-       for (i=0; i < p16 -> nOutputs; i++)
-       {
-              StageLMN[i] = (WORD) FixedLERP(rk, Tmp1[i], Tmp2[i]);
-       }
+    // Keep original parameters
+    p -> dwFlags  = dwFlags;
+    p -> nInputs  = InputChan;
+    p -> nOutputs = OutputChan;
+    p ->Table     = Table;
+    p ->ContextID  = ContextID;
 
-}
+    // Fill samples per input direction and domain (which is number of nodes minus one)
+    for (i=0; i < InputChan; i++) {
 
-static
-void Eval7Inputs(WORD StageABC[], WORD StageLMN[], WORD LutTable[], LPL16PARAMS p16)
-{
-       Fixed32 fk;
-       Fixed32 k0, rk;
-       int K0, K1;
-       LPWORD T;
-       int i;
-       WORD Tmp1[MAXCHANNELS], Tmp2[MAXCHANNELS];
+        p -> nSamples[i] = nSamples[i];
+        p -> Domain[i]   = nSamples[i] - 1;
+    }
+
+    // Compute factors to apply to each component to index the grid array
+    p -> opta[0] = p -> nOutputs;
+    for (i=1; i < InputChan; i++)
+        p ->opta[i] = p ->opta[i-1] * nSamples[InputChan-i];
 
 
-       fk = ToFixedDomain((Fixed32) StageABC[0] * p16 -> Domain);
-       k0 = FIXED_TO_INT(fk);
-       rk = FIXED_REST_TO_INT(fk);
-
-       K0 = p16 -> opta7 * k0;
-       K1 = p16 -> opta7 * (k0 + (StageABC[0] != 0xFFFFU ? 1 : 0));
-
-       p16 -> nInputs = 6;
-
-       T = LutTable + K0;
+    if (!_cmsSetInterpolationRoutine(p)) {
+         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported interpolation (%d->%d channels)", InputChan, OutputChan);
+        _cmsFree(ContextID, p);
+        return NULL;
+    }
 
-       Eval6Inputs(StageABC + 1, Tmp1, T, p16);
-
-       T = LutTable + K1;
-
-       Eval6Inputs(StageABC + 1, Tmp2, T, p16);
-
-       p16 -> nInputs = 7;
-       for (i=0; i < p16 -> nOutputs; i++)
-       {
-              StageLMN[i] = (WORD) FixedLERP(rk, Tmp1[i], Tmp2[i]);
-       }
-
+    // All seems ok
+    return p;
 }
 
-static
-void Eval8Inputs(WORD StageABC[], WORD StageLMN[], WORD LutTable[], LPL16PARAMS p16)
+
+// This one is a wrapper on the anterior, but assuming all directions have same number of nodes
+cmsInterpParams* _cmsComputeInterpParams(cmsContext ContextID, int nSamples, int InputChan, int OutputChan, const void* Table, cmsUInt32Number dwFlags)
 {
-       Fixed32 fk;
-       Fixed32 k0, rk;
-       int K0, K1;
-       LPWORD T;
-       int i;
-       WORD Tmp1[MAXCHANNELS], Tmp2[MAXCHANNELS];
-
-
-       fk = ToFixedDomain((Fixed32) StageABC[0] * p16 -> Domain);
-       k0 = FIXED_TO_INT(fk);
-       rk = FIXED_REST_TO_INT(fk);
+    int i;
+    cmsUInt32Number Samples[MAX_INPUT_DIMENSIONS];
 
-       K0 = p16 -> opta8 * k0;
-       K1 = p16 -> opta8 * (k0 + (StageABC[0] != 0xFFFFU ? 1 : 0));
-
-       p16 -> nInputs = 7;
-
-       T = LutTable + K0;
-
-       Eval7Inputs(StageABC + 1, Tmp1, T, p16);
+    // Fill the auxiliar array
+    for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
+        Samples[i] = nSamples;
 
-       T = LutTable + K1;
-
-       Eval7Inputs(StageABC + 1, Tmp2, T, p16);
-
-       p16 -> nInputs = 8;
-       for (i=0; i < p16 -> nOutputs; i++)
-       {
-              StageLMN[i] = (WORD) FixedLERP(rk, Tmp1[i], Tmp2[i]);
-       }
-
+    // Call the extended function
+    return _cmsComputeInterpParamsEx(ContextID, Samples, InputChan, OutputChan, Table, dwFlags);
 }
 
 
-// Fills optimization parameters
-
-void cmsCalcCLUT16ParamsEx(int nSamples, int InputChan, int OutputChan,
-                                            LCMSBOOL lUseTetrahedral, LPL16PARAMS p)
+// Free all associated memory
+void _cmsFreeInterpParams(cmsInterpParams* p)
 {
-       int clutPoints;
-
-       cmsCalcL16Params(nSamples, p);
-
-       p -> nInputs  = InputChan;
-       p -> nOutputs = OutputChan;
-
-       clutPoints = p -> Domain + 1;
-
-       p -> opta1 = p -> nOutputs;              // Z
-       p -> opta2 = p -> opta1 * clutPoints;    // Y
-       p -> opta3 = p -> opta2 * clutPoints;    // X
-       p -> opta4 = p -> opta3 * clutPoints;    // Used only in 4 inputs LUT
-       p -> opta5 = p -> opta4 * clutPoints;    // Used only in 5 inputs LUT
-       p -> opta6 = p -> opta5 * clutPoints;    // Used only on 6 inputs LUT
-       p -> opta7 = p -> opta6 * clutPoints;    // Used only on 7 inputs LUT
-       p -> opta8 = p -> opta7 * clutPoints;    // Used only on 8 inputs LUT
-
-
-       switch (InputChan) {
+    if (p != NULL) _cmsFree(p ->ContextID, p);
+}
 
 
-           case 1: // Gray LUT
-
-               p ->Interp3D = Eval1Input;
-               break;
-
-           case 3:  // RGB et al
-               if (lUseTetrahedral) {
-                   p ->Interp3D = cmsTetrahedralInterp16;
-               }
-               else
-                   p ->Interp3D = cmsTrilinearInterp16;
-               break;
-
-           case 4:  // CMYK LUT
-                p ->Interp3D = Eval4Inputs;
-                break;
-
-           case 5: // 5 Inks
-                p ->Interp3D = Eval5Inputs;
-                break;
-
-           case 6: // 6 Inks
-                p -> Interp3D = Eval6Inputs;
-                break;
-
-            case 7: // 7 inks
-                p ->Interp3D = Eval7Inputs;
-                break;
-
-           case 8: // 8 inks
-                p ->Interp3D = Eval8Inputs;
-                break;
-
-           default:
-                cmsSignalError(LCMS_ERRC_ABORTED, "Unsupported restoration (%d channels)", InputChan);
-           }
-
+// Inline fixed point interpolation
+cmsINLINE cmsUInt16Number LinearInterp(cmsS15Fixed16Number a, cmsS15Fixed16Number l, cmsS15Fixed16Number h)
+{
+    cmsUInt32Number dif = (cmsUInt32Number) (h - l) * a + 0x8000;
+    dif = (dif >> 16) + l;
+    return (cmsUInt16Number) (dif);
 }
 
 
-void cmsCalcCLUT16Params(int nSamples, int InputChan, int OutputChan, LPL16PARAMS p)
+//  Linear interpolation (Fixed-point optimized)
+static
+void LinLerp1D(register const cmsUInt16Number Value[],
+               register cmsUInt16Number Output[],
+               register const cmsInterpParams* p)
 {
-    cmsCalcCLUT16ParamsEx(nSamples, InputChan, OutputChan, FALSE, p);
+    cmsUInt16Number y1, y0;
+    int cell0, rest;
+    int val3;
+    const cmsUInt16Number* LutTable = (cmsUInt16Number*) p ->Table;
+
+    // if last value...
+    if (Value[0] == 0xffff) {
+
+        Output[0] = LutTable[p -> Domain[0]];
+        return;
+    }
+
+    val3 = p -> Domain[0] * Value[0];
+    val3 = _cmsToFixedDomain(val3);    // To fixed 15.16
+
+    cell0 = FIXED_TO_INT(val3);             // Cell is 16 MSB bits
+    rest  = FIXED_REST_TO_INT(val3);        // Rest is 16 LSB bits
+
+    y0 = LutTable[cell0];
+    y1 = LutTable[cell0+1];
+
+
+    Output[0] = LinearInterp(rest, y0, y1);
 }
 
 
-
-#ifdef USE_FLOAT
-
-
-// Floating-point version
-
-WORD cmsLinearInterpLUT16(WORD Value, WORD LutTable[], LPL16PARAMS p)
+// Floating-point version of 1D interpolation
+static
+void LinLerp1Dfloat(const cmsFloat32Number Value[],
+                    cmsFloat32Number Output[],
+                    const cmsInterpParams* p)
 {
-       double y1, y0;
-       double y;
-       double val2, rest;
+       cmsFloat32Number y1, y0;
+       cmsFloat32Number val2, rest;
        int cell0, cell1;
+       const cmsFloat32Number* LutTable = (cmsFloat32Number*) p ->Table;
 
        // if last value...
+       if (Value[0] == 1.0) {
+           Output[0] = LutTable[p -> Domain[0]];
+           return;
+       }
 
-       if (Value == 0xffff) return LutTable[p -> Domain];
-
-       val2 = p -> Domain * ((double) Value / 65535.0);
+       val2 = p -> Domain[0] * Value[0];
 
        cell0 = (int) floor(val2);
        cell1 = (int) ceil(val2);
 
        // Rest is 16 LSB bits
-
        rest = val2 - cell0;
 
        y0 = LutTable[cell0] ;
        y1 = LutTable[cell1] ;
 
-       y = y0 + (y1 - y0) * rest;
-
-
-       return (WORD) floor(y+.5);
-}
-
-#endif
-
-
-//
-//  Linear interpolation (Fixed-point optimized, but C source)
-//
-
-
-#ifdef USE_C
-
-WORD cmsLinearInterpLUT16(WORD Value1, WORD LutTable[], LPL16PARAMS p)
-{
-       WORD y1, y0;
-       WORD y;
-       int dif, a1;
-       int cell0, rest;
-       int val3, Value;
-
-       // if last value...
-
-
-       Value = Value1;
-       if (Value == 0xffff) return LutTable[p -> Domain];
-
-       val3 = p -> Domain * Value;
-       val3 = ToFixedDomain(val3);              // To fixed 15.16
-
-       cell0 = FIXED_TO_INT(val3);             // Cell is 16 MSB bits
-       rest  = FIXED_REST_TO_INT(val3);        // Rest is 16 LSB bits
-
-       y0 = LutTable[cell0] ;
-       y1 = LutTable[cell0+1] ;
-
-       dif = (int) y1 - y0;        // dif is in domain -ffff ... ffff
-
-       if (dif >= 0)
-       {
-       a1 = ToFixedDomain(dif * rest);
-       a1 += 0x8000;
-       }
-       else
-       {
-              a1 = ToFixedDomain((- dif) * rest);
-              a1 -= 0x8000;
-              a1 = -a1;
-       }
-
-       y = (WORD) (y0 + FIXED_TO_INT(a1));
-
-       return y;
-}
-
-#endif
-
-// Linear interpolation (asm by hand optimized)
-
-#ifdef USE_ASSEMBLER
-
-#ifdef _MSC_VER
-#pragma warning(disable : 4033)
-#pragma warning(disable : 4035)
-#endif
-
-WORD cmsLinearInterpLUT16(WORD Value, WORD LutTable[], LPL16PARAMS p)
-{
-       int xDomain = p -> Domain;
-
-
-       if (Value == 0xffff) return LutTable[p -> Domain];
-       else
-       ASM {
-              xor       eax, eax
-              mov       ax, word ptr ss:Value
-              mov       edx, ss:xDomain
-              mul       edx                         //  val3 = p -> Domain * Value;
-              shld      edx, eax, 16                // Convert it to fixed 15.16
-              shl       eax, 16                     // * 65536 / 65535
-              mov       ebx, 0x0000ffff
-              div       ebx
-              mov       ecx, eax
-              sar       ecx, 16                        // ecx = cell0
-              mov       edx, eax                       // rest = (val2 & 0xFFFFU)
-              and       edx, 0x0000ffff                // edx = rest
-              mov       ebx, ss:LutTable
-              lea       eax, dword ptr [ebx+2*ecx]     // Ptr to LUT
-              xor       ebx, ebx
-              mov        bx, word  ptr [eax]           // EBX = y0
-              movzx     eax, word  ptr [eax+2]         // EAX = y1
-              sub       eax, ebx                       // EAX = y1-y0
-              js        IsNegative
-              mul       edx                            // EAX = EAX * rest
-              shld      edx, eax, 16                   // Pass it to fixed
-              sal       eax, 16                        // * 65536 / 65535
-              mov       ecx, 0x0000ffff
-              div       ecx
-              add       eax, 0x8000                    // Rounding
-              sar       eax, 16
-              add       eax, ebx                       // Done!
-              }
-
-              RET((WORD) _EAX);
-
-       IsNegative:
-
-              ASM {
-              neg       eax
-              mul       edx                            // EAX = EAX * rest
-              shld      edx, eax, 16                   // Pass it to fixed
-              sal       eax, 16                        // * 65536 / 65535
-              mov       ecx, 0x0000ffff
-              div       ecx
-              sub       eax, 0x8000
-              neg       eax
-              sar       eax, 16
-              add       eax, ebx                       // Done!
-              }
-
-              RET((WORD) _EAX);
-}
-
-#ifdef _MSC_VER
-#pragma warning(default : 4033)
-#pragma warning(default : 4035)
-#endif
-
-#endif
-
-Fixed32 cmsLinearInterpFixed(WORD Value1, WORD LutTable[], LPL16PARAMS p)
-{
-       Fixed32 y1, y0;
-       int cell0;
-       int val3, Value;
-
-       // if last value...
-
-
-       Value = Value1;
-       if (Value == 0xffffU) return LutTable[p -> Domain];
-
-       val3 = p -> Domain * Value;
-       val3 = ToFixedDomain(val3);              // To fixed 15.16
-
-       cell0 = FIXED_TO_INT(val3);             // Cell is 16 MSB bits
-
-       y0 = LutTable[cell0] ;
-       y1 = LutTable[cell0+1] ;
-
-
-       return y0 + FixedMul((y1 - y0), (val3 & 0xFFFFL));
+       Output[0] = y0 + (y1 - y0) * rest;
 }
 
 
-// Reverse Lineal interpolation (16 bits)
-// Im using a sort of binary search here, this is not a time-critical function
 
-WORD cmsReverseLinearInterpLUT16(WORD Value, WORD LutTable[], LPL16PARAMS p)
+// Eval gray LUT having only one input channel
+static
+void Eval1Input(register const cmsUInt16Number Input[],
+                register cmsUInt16Number Output[],
+                register const cmsInterpParams* p16)
 {
-        register int l = 1;
-        register int r = 0x10000;
-        register int x = 0, res;       // 'int' Give spacing for negative values
-        int NumZeroes, NumPoles;
-        int cell0, cell1;
-        double val2;
-        double y0, y1, x0, x1;
-        double a, b, f;
-
-        // July/27 2001 - Expanded to handle degenerated curves with an arbitrary
-        // number of elements containing 0 at the begining of the table (Zeroes)
-        // and another arbitrary number of poles (FFFFh) at the end.
-        // First the zero and pole extents are computed, then value is compared.
-
-        NumZeroes = 0;
-        while (LutTable[NumZeroes] == 0 && NumZeroes < p -> Domain)
-                        NumZeroes++;
-
-        // There are no zeros at the beginning and we are trying to find a zero, so
-        // return anything. It seems zero would be the less destructive choice
-
-        if (NumZeroes == 0 && Value == 0)
-            return 0;
-
-        NumPoles = 0;
-        while (LutTable[p -> Domain - NumPoles] == 0xFFFF && NumPoles < p -> Domain)
-                        NumPoles++;
-
-        // Does the curve belong to this case?
-        if (NumZeroes > 1 || NumPoles > 1)
-        {
-                int a, b;
-
-                // Identify if value fall downto 0 or FFFF zone
-                if (Value == 0) return 0;
-               // if (Value == 0xFFFF) return 0xFFFF;
-
-                // else restrict to valid zone
-
-                a = ((NumZeroes-1) * 0xFFFF) / p->Domain;
-                b = ((p -> Domain - NumPoles) * 0xFFFF) / p ->Domain;
-
-                l = a - 1;
-                r = b + 1;
-        }
+       cmsS15Fixed16Number fk;
+       cmsS15Fixed16Number k0, k1, rk, K0, K1;
+       int v;
+       cmsUInt32Number OutChan;
+       const cmsUInt16Number* LutTable = (cmsUInt16Number*) p16 -> Table;
 
-
-        // Seems not a degenerated case... apply binary search
-
-        while (r > l) {
-
-                x = (l + r) / 2;
-
-                res = (int) cmsLinearInterpLUT16((WORD) (x - 1), LutTable, p);
-
-                if (res == Value) {
+       v = Input[0] * p16 -> Domain[0];
+       fk = _cmsToFixedDomain(v);
 
-                    // Found exact match.
-
-                    return (WORD) (x - 1);
-                }
+       k0 = FIXED_TO_INT(fk);
+       rk = (cmsUInt16Number) FIXED_REST_TO_INT(fk);
 
-                if (res > Value) r = x - 1;
-                else l = x + 1;
-        }
-
-        // Not found, should we interpolate?
-
-
-        // Get surrounding nodes
+       k1 = k0 + (Input[0] != 0xFFFFU ? 1 : 0);
 
-        val2 = p -> Domain * ((double) (x - 1) / 65535.0);
-
-        cell0 = (int) floor(val2);
-        cell1 = (int) ceil(val2);
-
-        if (cell0 == cell1) return (WORD) x;
-
-        y0 = LutTable[cell0] ;
-        x0 = (65535.0 * cell0) / p ->Domain;
-
-        y1 = LutTable[cell1] ;
-        x1 = (65535.0 * cell1) / p ->Domain;
+       K0 = p16 -> opta[0] * k0;
+       K1 = p16 -> opta[0] * k1;
 
-        a = (y1 - y0) / (x1 - x0);
-        b = y0 - a * x0;
-
-        if (fabs(a) < 0.01) return (WORD) x;
+       for (OutChan=0; OutChan < p16->nOutputs; OutChan++) {
 
-        f = ((Value - b) / a);
-
-        if (f < 0.0) return (WORD) 0;
-        if (f >= 65535.0) return (WORD) 0xFFFF;
-
-        return (WORD) floor(f + 0.5);
-
+           Output[OutChan] = LinearInterp(rk, LutTable[K0+OutChan], LutTable[K1+OutChan]);
+       }
 }
 
 
 
+// Eval gray LUT having only one input channel
+static
+void Eval1InputFloat(const cmsFloat32Number Value[],
+                     cmsFloat32Number Output[],
+                     const cmsInterpParams* p)
+{
+    cmsFloat32Number y1, y0;
+    cmsFloat32Number val2, rest;
+    int cell0, cell1;
+    cmsUInt32Number OutChan;
+    const cmsFloat32Number* LutTable = (cmsFloat32Number*) p ->Table;
 
-// Trilinear interpolation (16 bits) - float version
+        // if last value...
+       if (Value[0] == 1.0) {
+           Output[0] = LutTable[p -> Domain[0]];
+           return;
+       }
 
-#ifdef USE_FLOAT
-void cmsTrilinearInterp16(WORD Input[], WORD Output[],
-                            WORD LutTable[], LPL16PARAMS p)
+       val2 = p -> Domain[0] * Value[0];
+
+       cell0 = (int) floor(val2);
+       cell1 = (int) ceil(val2);
+
+       // Rest is 16 LSB bits
+       rest = val2 - cell0;
 
-{
-#   define LERP(a,l,h)  (double) ((l)+(((h)-(l))*(a)))
-#   define DENS(X, Y, Z)    (double) (LutTable[TotalOut*((Z)+clutPoints*((Y)+clutPoints*(X)))+OutChan])
+       cell0 *= p -> opta[0];
+       cell1 *= p -> opta[0];
+
+       for (OutChan=0; OutChan < p->nOutputs; OutChan++) {
+
+            y0 = LutTable[cell0 + OutChan] ;
+            y1 = LutTable[cell1 + OutChan] ;
+
+            Output[OutChan] = y0 + (y1 - y0) * rest;
+       }
+}
 
 
 
-    double     px, py, pz;
+// Trilinear interpolation (16 bits) - cmsFloat32Number version
+static
+void TrilinearInterpFloat(const cmsFloat32Number Input[],
+                          cmsFloat32Number Output[],
+                          const cmsInterpParams* p)
+
+{
+#   define LERP(a,l,h)      (cmsFloat32Number) ((l)+(((h)-(l))*(a)))
+#   define DENS(i,j,k)      (LutTable[(i)+(j)+(k)+OutChan])
+
+    const cmsFloat32Number* LutTable = (cmsFloat32Number*) p ->Table;
+    cmsFloat32Number      px, py, pz;
     int        x0, y0, z0,
-               x1, y1, z1;
-               int clutPoints, TotalOut, OutChan;
-    double     fx, fy, fz,
-               d000, d001, d010, d011,
-               d100, d101, d110, d111,
-               dx00, dx01, dx10, dx11,
-               dxy0, dxy1, dxyz;
+               X0, Y0, Z0, X1, Y1, Z1;
+    int        TotalOut, OutChan;
+    cmsFloat32Number      fx, fy, fz,
+        d000, d001, d010, d011,
+        d100, d101, d110, d111,
+        dx00, dx01, dx10, dx11,
+        dxy0, dxy1, dxyz;
 
-
-    clutPoints = p -> Domain + 1;
     TotalOut   = p -> nOutputs;
 
-    px = ((double) Input[0] * (p->Domain)) / 65535.0;
-    py = ((double) Input[1] * (p->Domain)) / 65535.0;
-    pz = ((double) Input[2] * (p->Domain)) / 65535.0;
+    px = Input[0] * p->Domain[0];
+    py = Input[1] * p->Domain[1];
+    pz = Input[2] * p->Domain[2];
+
+    x0 = (int) _cmsQuickFloor(px); fx = px - (cmsFloat32Number) x0;
+    y0 = (int) _cmsQuickFloor(py); fy = py - (cmsFloat32Number) y0;
+    z0 = (int) _cmsQuickFloor(pz); fz = pz - (cmsFloat32Number) z0;
+
+    X0 = p -> opta[2] * x0;
+    X1 = X0 + (Input[0] >= 1.0 ? 0 : p->opta[2]);
+
+    Y0 = p -> opta[1] * y0;
+    Y1 = Y0 + (Input[1] >= 1.0 ? 0 : p->opta[1]);
 
-    x0 = (int) _cmsQuickFloor(px); fx = px - (double) x0;
-    y0 = (int) _cmsQuickFloor(py); fy = py - (double) y0;
-    z0 = (int) _cmsQuickFloor(pz); fz = pz - (double) z0;
+    Z0 = p -> opta[0] * z0;
+    Z1 = Z0 + (Input[2] >= 1.0 ? 0 : p->opta[0]);
+
+    for (OutChan = 0; OutChan < TotalOut; OutChan++) {
 
-    x1 = x0 + (Input[0] != 0xFFFFU ? 1 : 0);
-    y1 = y0 + (Input[1] != 0xFFFFU ? 1 : 0);
-    z1 = z0 + (Input[2] != 0xFFFFU ? 1 : 0);
+        d000 = DENS(X0, Y0, Z0);
+        d001 = DENS(X0, Y0, Z1);
+        d010 = DENS(X0, Y1, Z0);
+        d011 = DENS(X0, Y1, Z1);
+
+        d100 = DENS(X1, Y0, Z0);
+        d101 = DENS(X1, Y0, Z1);
+        d110 = DENS(X1, Y1, Z0);
+        d111 = DENS(X1, Y1, Z1);
 
 
-    for (OutChan = 0; OutChan < TotalOut; OutChan++)
-    {
-
-        d000 = DENS(x0, y0, z0);
-        d001 = DENS(x0, y0, z1);
-        d010 = DENS(x0, y1, z0);
-        d011 = DENS(x0, y1, z1);
-
-        d100 = DENS(x1, y0, z0);
-        d101 = DENS(x1, y0, z1);
-        d110 = DENS(x1, y1, z0);
-        d111 = DENS(x1, y1, z1);
+        dx00 = LERP(fx, d000, d100);
+        dx01 = LERP(fx, d001, d101);
+        dx10 = LERP(fx, d010, d110);
+        dx11 = LERP(fx, d011, d111);
 
-
-    dx00 = LERP(fx, d000, d100);
-    dx01 = LERP(fx, d001, d101);
-    dx10 = LERP(fx, d010, d110);
-    dx11 = LERP(fx, d011, d111);
+        dxy0 = LERP(fy, dx00, dx10);
+        dxy1 = LERP(fy, dx01, dx11);
 
-    dxy0 = LERP(fy, dx00, dx10);
-    dxy1 = LERP(fy, dx01, dx11);
+        dxyz = LERP(fz, dxy0, dxy1);
 
-    dxyz = LERP(fz, dxy0, dxy1);
-
-    Output[OutChan] = (WORD) floor(dxyz + .5);
+        Output[OutChan] = dxyz;
     }
 
 
@@ -716,24 +391,19 @@
 #   undef DENS
 }
 
-
-#endif
-
-
-#ifndef USE_FLOAT
-
 // Trilinear interpolation (16 bits) - optimized version
-
-void cmsTrilinearInterp16(WORD Input[], WORD Output[],
-                            WORD LutTable[], LPL16PARAMS p)
+static
+void TrilinearInterp16(register const cmsUInt16Number Input[],
+                       register cmsUInt16Number Output[],
+                       register const cmsInterpParams* p)
 
 {
 #define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
-#define LERP(a,l,h)     (WORD) (l+ ROUND_FIXED_TO_INT(((h-l)*a)))
-
+#define LERP(a,l,h)     (cmsUInt16Number) (l + ROUND_FIXED_TO_INT(((h-l)*a)))
 
+           const cmsUInt16Number* LutTable = (cmsUInt16Number*) p ->Table;
            int        OutChan, TotalOut;
-           Fixed32    fx, fy, fz;
+           cmsS15Fixed16Number    fx, fy, fz;
   register int        rx, ry, rz;
            int        x0, y0, z0;
   register int        X0, X1, Y0, Y1, Z0, Z1;
@@ -742,37 +412,32 @@
                       dx00, dx01, dx10, dx11,
                       dxy0, dxy1, dxyz;
 
-
     TotalOut   = p -> nOutputs;
 
-    fx = ToFixedDomain((int) Input[0] * p -> Domain);
+    fx = _cmsToFixedDomain((int) Input[0] * p -> Domain[0]);
     x0  = FIXED_TO_INT(fx);
     rx  = FIXED_REST_TO_INT(fx);    // Rest in 0..1.0 domain
 
 
-    fy = ToFixedDomain((int) Input[1] * p -> Domain);
+    fy = _cmsToFixedDomain((int) Input[1] * p -> Domain[1]);
     y0  = FIXED_TO_INT(fy);
     ry  = FIXED_REST_TO_INT(fy);
 
-    fz = ToFixedDomain((int) Input[2] * p -> Domain);
+    fz = _cmsToFixedDomain((int) Input[2] * p -> Domain[2]);
     z0 = FIXED_TO_INT(fz);
     rz = FIXED_REST_TO_INT(fz);
 
 
-
-    X0 = p -> opta3 * x0;
-    X1 = X0 + (Input[0] == 0xFFFFU ? 0 : p->opta3);
-
-    Y0 = p -> opta2 * y0;
-    Y1 = Y0 + (Input[1] == 0xFFFFU ? 0 : p->opta2);
+    X0 = p -> opta[2] * x0;
+    X1 = X0 + (Input[0] == 0xFFFFU ? 0 : p->opta[2]);
 
-    Z0 = p -> opta1 * z0;
-    Z1 = Z0 + (Input[2] == 0xFFFFU ? 0 : p->opta1);
-
+    Y0 = p -> opta[1] * y0;
+    Y1 = Y0 + (Input[1] == 0xFFFFU ? 0 : p->opta[1]);
 
+    Z0 = p -> opta[0] * z0;
+    Z1 = Z0 + (Input[2] == 0xFFFFU ? 0 : p->opta[0]);
 
-    for (OutChan = 0; OutChan < TotalOut; OutChan++)
-    {
+    for (OutChan = 0; OutChan < TotalOut; OutChan++) {
 
         d000 = DENS(X0, Y0, Z0);
         d001 = DENS(X0, Y0, Z1);
@@ -795,7 +460,7 @@
 
         dxyz = LERP(rz, dxy0, dxy1);
 
-        Output[OutChan] = (WORD) dxyz;
+        Output[OutChan] = (cmsUInt16Number) dxyz;
     }
 
 
@@ -803,133 +468,128 @@
 #   undef DENS
 }
 
-#endif
-
-
-#ifdef USE_FLOAT
-
-#define DENS(X, Y, Z)    (double) (LutTable[TotalOut*((Z)+clutPoints*((Y)+clutPoints*(X)))+OutChan])
-
 
 // Tetrahedral interpolation, using Sakamoto algorithm.
-
-void cmsTetrahedralInterp16(WORD Input[],
-                            WORD Output[],
-                            WORD LutTable[],
-                            LPL16PARAMS p)
+#define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
+static
+void TetrahedralInterpFloat(const cmsFloat32Number Input[],
+                            cmsFloat32Number Output[],
+                            const cmsInterpParams* p)
 {
-    double     px, py, pz;
+    const cmsFloat32Number* LutTable = (cmsFloat32Number*) p -> Table;
+    cmsFloat32Number     px, py, pz;
     int        x0, y0, z0,
-               x1, y1, z1;
-    double     fx, fy, fz;
-    double     c1=0, c2=0, c3=0;
-    int        clutPoints, OutChan, TotalOut;
+               X0, Y0, Z0, X1, Y1, Z1;
+    cmsFloat32Number     rx, ry, rz;
+    cmsFloat32Number     c0, c1=0, c2=0, c3=0;
+    int                  OutChan, TotalOut;
 
-
-    clutPoints = p -> Domain + 1;
     TotalOut   = p -> nOutputs;
 
+    px = Input[0] * p->Domain[0];
+    py = Input[1] * p->Domain[1];
+    pz = Input[2] * p->Domain[2];
 
-    px = ((double) Input[0] * p->Domain) / 65535.0;
-    py = ((double) Input[1] * p->Domain) / 65535.0;
-    pz = ((double) Input[2] * p->Domain) / 65535.0;
-
-    x0 = (int) _cmsQuickFloor(px); fx = (px - (double) x0);
-    y0 = (int) _cmsQuickFloor(py); fy = (py - (double) y0);
-    z0 = (int) _cmsQuickFloor(pz); fz = (pz - (double) z0);
+    x0 = (int) _cmsQuickFloor(px); rx = (px - (cmsFloat32Number) x0);
+    y0 = (int) _cmsQuickFloor(py); ry = (py - (cmsFloat32Number) y0);
+    z0 = (int) _cmsQuickFloor(pz); rz = (pz - (cmsFloat32Number) z0);
 
 
-    x1 = x0 + (Input[0] != 0xFFFFU ? 1 : 0);
-    y1 = y0 + (Input[1] != 0xFFFFU ? 1 : 0);
-    z1 = z0 + (Input[2] != 0xFFFFU ? 1 : 0);
+    X0 = p -> opta[2] * x0;
+    X1 = X0 + (Input[0] >= 1.0 ? 0 : p->opta[2]);
 
+    Y0 = p -> opta[1] * y0;
+    Y1 = Y0 + (Input[1] >= 1.0 ? 0 : p->opta[1]);
 
-    for (OutChan=0; OutChan < TotalOut; OutChan++)
-    {
+    Z0 = p -> opta[0] * z0;
+    Z1 = Z0 + (Input[2] >= 1.0 ? 0 : p->opta[0]);
+
+    for (OutChan=0; OutChan < TotalOut; OutChan++) {
 
        // These are the 6 Tetrahedral
 
-       if (fx >= fy && fy >= fz)
-       {
-              c1 = DENS(x1, y0, z0) - DENS(x0, y0, z0);
-              c2 = DENS(x1, y1, z0) - DENS(x1, y0, z0);
-              c3 = DENS(x1, y1, z1) - DENS(x1, y1, z0);
-       }
-       else
-       if (fx >= fz && fz >= fy)
-       {
-              c1 = DENS(x1, y0, z0) - DENS(x0, y0, z0);
-              c2 = DENS(x1, y1, z1) - DENS(x1, y0, z1);
-              c3 = DENS(x1, y0, z1) - DENS(x1, y0, z0);
-       }
-       else
-       if (fz >= fx && fx >= fy)
-       {
-              c1 = DENS(x1, y0, z1) - DENS(x0, y0, z1);
-              c2 = DENS(x1, y1, z1) - DENS(x1, y0, z1);
-              c3 = DENS(x0, y0, z1) - DENS(x0, y0, z0);
-       }
-       else
-       if (fy >= fx && fx >= fz)
-       {
-              c1 = DENS(x1, y1, z0) - DENS(x0, y1, z0);
-              c2 = DENS(x0, y1, z0) - DENS(x0, y0, z0);
-              c3 = DENS(x1, y1, z1) - DENS(x1, y1, z0);
+        c0 = DENS(X0, Y0, Z0);
+
+        if (rx >= ry && ry >= rz) {
+
+            c1 = DENS(X1, Y0, Z0) - c0;
+            c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
+            c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+
+        }
+        else
+            if (rx >= rz && rz >= ry) {
+
+                c1 = DENS(X1, Y0, Z0) - c0;
+                c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
+
+            }
+            else
+                if (rz >= rx && rx >= ry) {
+
+                    c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
+                    c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                    c3 = DENS(X0, Y0, Z1) - c0;
 
-       }
-       else
-       if (fy >= fz && fz >= fx)
-       {
-              c1 = DENS(x1, y1, z1) - DENS(x0, y1, z1);
-              c2 = DENS(x0, y1, z0) - DENS(x0, y0, z0);
-              c3 = DENS(x0, y1, z1) - DENS(x0, y1, z0);
-       }
-       else
-       if (fz >= fy && fy >= fx)
-       {
-              c1 = DENS(x1, y1, z1) - DENS(x0, y1, z1);
-              c2 = DENS(x0, y1, z1) - DENS(x0, y0, z1);
-              c3 = DENS(x0, y0, z1) - DENS(x0, y0, z0);
-       }
-       else
-       {
-         c1 = c2 = c3 = 0;
-       //  assert(FALSE);
-       }
+                }
+                else
+                    if (ry >= rx && rx >= rz) {
+
+                        c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
+                        c2 = DENS(X0, Y1, Z0) - c0;
+                        c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+
+                    }
+                    else
+                        if (ry >= rz && rz >= rx) {
 
+                            c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                            c2 = DENS(X0, Y1, Z0) - c0;
+                            c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
 
-       Output[OutChan] = (WORD) floor((double) DENS(x0,y0,z0) + c1 * fx + c2 * fy + c3 * fz + .5);
+                        }
+                        else
+                            if (rz >= ry && ry >= rx) {
+
+                                c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                                c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
+                                c3 = DENS(X0, Y0, Z1) - c0;
+
+                            }
+                            else  {
+                                c1 = c2 = c3 = 0;
+                            }
+
+       Output[OutChan] = c0 + c1 * rx + c2 * ry + c3 * rz;
        }
 
 }
 
 #undef DENS
 
-#else
+
 
 #define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
 
-
-void cmsTetrahedralInterp16(WORD Input[],
-                            WORD Output[],
-                            WORD LutTable1[],
-                            LPL16PARAMS p)
+static
+void TetrahedralInterp16(register const cmsUInt16Number Input[],
+                         register cmsUInt16Number Output[],
+                         register const cmsInterpParams* p)
 {
-
-       Fixed32    fx, fy, fz;
-       Fixed32    rx, ry, rz;
-       int        x0, y0, z0;
-       Fixed32    c0, c1, c2, c3, Rest;
-       int        OutChan;
-       Fixed32    X0, X1, Y0, Y1, Z0, Z1;
-       int        TotalOut = p -> nOutputs;
-       register   LPWORD LutTable = LutTable1;
+    const cmsUInt16Number* LutTable = (cmsUInt16Number*) p -> Table;
+    cmsS15Fixed16Number    fx, fy, fz;
+    cmsS15Fixed16Number    rx, ry, rz;
+    int                    x0, y0, z0;
+    cmsS15Fixed16Number    c0, c1, c2, c3, Rest;
+    cmsUInt32Number        OutChan;
+    cmsS15Fixed16Number    X0, X1, Y0, Y1, Z0, Z1;
+    cmsUInt32Number        TotalOut = p -> nOutputs;
 
 
-
-    fx  = ToFixedDomain((int) Input[0] * p -> Domain);
-    fy  = ToFixedDomain((int) Input[1] * p -> Domain);
-    fz  = ToFixedDomain((int) Input[2] * p -> Domain);
+    fx  = _cmsToFixedDomain((int) Input[0] * p -> Domain[0]);
+    fy  = _cmsToFixedDomain((int) Input[1] * p -> Domain[1]);
+    fz  = _cmsToFixedDomain((int) Input[2] * p -> Domain[2]);
 
     x0  = FIXED_TO_INT(fx);
     y0  = FIXED_TO_INT(fy);
@@ -939,196 +599,754 @@
     ry  = FIXED_REST_TO_INT(fy);
     rz  = FIXED_REST_TO_INT(fz);
 
-    X0 = p -> opta3 * x0;
-    X1 = X0 + (Input[0] == 0xFFFFU ? 0 : p->opta3);
+    X0 = p -> opta[2] * x0;
+    X1 = X0 + (Input[0] == 0xFFFFU ? 0 : p->opta[2]);
 
-    Y0 = p -> opta2 * y0;
-    Y1 = Y0 + (Input[1] == 0xFFFFU ? 0 : p->opta2);
+    Y0 = p -> opta[1] * y0;
+    Y1 = Y0 + (Input[1] == 0xFFFFU ? 0 : p->opta[1]);
 
-    Z0 = p -> opta1 * z0;
-    Z1 = Z0 + (Input[2] == 0xFFFFU ? 0 : p->opta1);
-
-
+    Z0 = p -> opta[0] * z0;
+    Z1 = Z0 + (Input[2] == 0xFFFFU ? 0 : p->opta[0]);
 
     // These are the 6 Tetrahedral
     for (OutChan=0; OutChan < TotalOut; OutChan++) {
 
-       c0 = DENS(X0, Y0, Z0);
+        c0 = DENS(X0, Y0, Z0);
+
+        if (rx >= ry && ry >= rz) {
+
+            c1 = DENS(X1, Y0, Z0) - c0;
+            c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
+            c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+
+        }
+        else
+            if (rx >= rz && rz >= ry) {
+
+                c1 = DENS(X1, Y0, Z0) - c0;
+                c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
+
+            }
+            else
+                if (rz >= rx && rx >= ry) {
+
+                    c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
+                    c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                    c3 = DENS(X0, Y0, Z1) - c0;
+
+                }
+                else
+                    if (ry >= rx && rx >= rz) {
 
-       if (rx >= ry && ry >= rz) {
+                        c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
+                        c2 = DENS(X0, Y1, Z0) - c0;
+                        c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+
+                    }
+                    else
+                        if (ry >= rz && rz >= rx) {
+
+                            c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                            c2 = DENS(X0, Y1, Z0) - c0;
+                            c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
+
+                        }
+                        else
+                            if (rz >= ry && ry >= rx) {
+
+                                c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                                c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
+                                c3 = DENS(X0, Y0, Z1) - c0;
+
+                            }
+                            else  {
+                                c1 = c2 = c3 = 0;
+                            }
+
+                            Rest = c1 * rx + c2 * ry + c3 * rz;
+
+                            Output[OutChan] = (cmsUInt16Number) c0 + ROUND_FIXED_TO_INT(_cmsToFixedDomain(Rest));
+    }
+
+}
+#undef DENS
+
 
-              c1 = DENS(X1, Y0, Z0) - c0;
-              c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
-              c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+#define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
+static
+void Eval4Inputs(register const cmsUInt16Number Input[],
+                     register cmsUInt16Number Output[],
+                     register const cmsInterpParams* p16)
+{
+    const cmsUInt16Number* LutTable = (cmsUInt16Number*) p16 -> Table;
+    cmsS15Fixed16Number fk;
+    cmsS15Fixed16Number k0, rk;
+    int K0, K1;
+    cmsS15Fixed16Number    fx, fy, fz;
+    cmsS15Fixed16Number    rx, ry, rz;
+    int                    x0, y0, z0;
+    cmsS15Fixed16Number    X0, X1, Y0, Y1, Z0, Z1;
+    cmsUInt32Number i;
+    cmsS15Fixed16Number    c0, c1, c2, c3, Rest;
+    cmsUInt32Number        OutChan;
+    cmsUInt16Number        Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+
+
+    fk  = _cmsToFixedDomain((int) Input[0] * p16 -> Domain[0]);
+    fx  = _cmsToFixedDomain((int) Input[1] * p16 -> Domain[1]);
+    fy  = _cmsToFixedDomain((int) Input[2] * p16 -> Domain[2]);
+    fz  = _cmsToFixedDomain((int) Input[3] * p16 -> Domain[3]);
+
+    k0  = FIXED_TO_INT(fk);
+    x0  = FIXED_TO_INT(fx);
+    y0  = FIXED_TO_INT(fy);
+    z0  = FIXED_TO_INT(fz);
+
+    rk  = FIXED_REST_TO_INT(fk);
+    rx  = FIXED_REST_TO_INT(fx);
+    ry  = FIXED_REST_TO_INT(fy);
+    rz  = FIXED_REST_TO_INT(fz);
+
+    K0 = p16 -> opta[3] * k0;
+    K1 = K0 + (Input[0] == 0xFFFFU ? 0 : p16->opta[3]);
 
-       }
-       else
-       if (rx >= rz && rz >= ry) {
+    X0 = p16 -> opta[2] * x0;
+    X1 = X0 + (Input[1] == 0xFFFFU ? 0 : p16->opta[2]);
+
+    Y0 = p16 -> opta[1] * y0;
+    Y1 = Y0 + (Input[2] == 0xFFFFU ? 0 : p16->opta[1]);
+
+    Z0 = p16 -> opta[0] * z0;
+    Z1 = Z0 + (Input[3] == 0xFFFFU ? 0 : p16->opta[0]);
+
+    LutTable = (cmsUInt16Number*) p16 -> Table;
+    LutTable += K0;
+
+    for (OutChan=0; OutChan < p16 -> nOutputs; OutChan++) {
+
+        c0 = DENS(X0, Y0, Z0);
+
+        if (rx >= ry && ry >= rz) {
+
+            c1 = DENS(X1, Y0, Z0) - c0;
+            c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
+            c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+
+        }
+        else
+            if (rx >= rz && rz >= ry) {
+
+                c1 = DENS(X1, Y0, Z0) - c0;
+                c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
+
+            }
+            else
+                if (rz >= rx && rx >= ry) {
+
+                    c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
+                    c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                    c3 = DENS(X0, Y0, Z1) - c0;
+
+                }
+                else
+                    if (ry >= rx && rx >= rz) {
 
-              c1 = DENS(X1, Y0, Z0) - c0;
-              c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
-              c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
+                        c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
+                        c2 = DENS(X0, Y1, Z0) - c0;
+                        c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+
+                    }
+                    else
+                        if (ry >= rz && rz >= rx) {
+
+                            c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                            c2 = DENS(X0, Y1, Z0) - c0;
+                            c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
+
+                        }
+                        else
+                            if (rz >= ry && ry >= rx) {
+
+                                c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                                c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
+                                c3 = DENS(X0, Y0, Z1) - c0;
+
+                            }
+                            else  {
+                                c1 = c2 = c3 = 0;
+                            }
+
+                            Rest = c1 * rx + c2 * ry + c3 * rz;
+
+                            Tmp1[OutChan] = (cmsUInt16Number) c0 + ROUND_FIXED_TO_INT(_cmsToFixedDomain(Rest));
+    }
+
+
+    LutTable = (cmsUInt16Number*) p16 -> Table;
+    LutTable += K1;
+
+    for (OutChan=0; OutChan < p16 -> nOutputs; OutChan++) {
+
+        c0 = DENS(X0, Y0, Z0);
+
+        if (rx >= ry && ry >= rz) {
+
+            c1 = DENS(X1, Y0, Z0) - c0;
+            c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
+            c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+
+        }
+        else
+            if (rx >= rz && rz >= ry) {
+
+                c1 = DENS(X1, Y0, Z0) - c0;
+                c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
+
+            }
+            else
+                if (rz >= rx && rx >= ry) {
+
+                    c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
+                    c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                    c3 = DENS(X0, Y0, Z1) - c0;
+
+                }
+                else
+                    if (ry >= rx && rx >= rz) {
+
+                        c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
+                        c2 = DENS(X0, Y1, Z0) - c0;
+                        c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+
+                    }
+                    else
+                        if (ry >= rz && rz >= rx) {
 
-       }
-       else
-       if (rz >= rx && rx >= ry) {
+                            c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                            c2 = DENS(X0, Y1, Z0) - c0;
+                            c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
+
+                        }
+                        else
+                            if (rz >= ry && ry >= rx) {
+
+                                c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                                c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
+                                c3 = DENS(X0, Y0, Z1) - c0;
+
+                            }
+                            else  {
+                                c1 = c2 = c3 = 0;
+                            }
+
+                            Rest = c1 * rx + c2 * ry + c3 * rz;
+
+                            Tmp2[OutChan] = (cmsUInt16Number) c0 + ROUND_FIXED_TO_INT(_cmsToFixedDomain(Rest));
+    }
+
+
+
+    for (i=0; i < p16 -> nOutputs; i++) {
+        Output[i] = LinearInterp(rk, Tmp1[i], Tmp2[i]);
+    }
+}
+#undef DENS
+
+
+// For more that 3 inputs (i.e., CMYK)
+// evaluate two 3-dimensional interpolations and then linearly interpolate between them.
+
 
-              c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
-              c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
-              c3 = DENS(X0, Y0, Z1) - c0;
+static
+void Eval4InputsFloat(const cmsFloat32Number Input[],
+                      cmsFloat32Number Output[],
+                      const cmsInterpParams* p)
+{
+       const cmsFloat32Number* LutTable = (cmsFloat32Number*) p -> Table;
+       cmsFloat32Number rest;
+       cmsFloat32Number pk;
+       int k0, K0, K1;
+       const cmsFloat32Number* T;
+       cmsUInt32Number i;
+       cmsFloat32Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
+
+
+       pk = Input[0] * p->Domain[0];
+       k0 = _cmsQuickFloor(pk);
+       rest = pk - (cmsFloat32Number) k0;
 
+       K0 = p -> opta[3] * k0;
+       K1 = K0 + (Input[0] >= 1.0 ? 0 : p->opta[3]);
+
+       p1 = *p;
+       memmove(&p1.Domain[0], &p ->Domain[1], 3*sizeof(cmsUInt32Number));
+
+       T = LutTable + K0;
+       p1.Table = T;
+
+       TetrahedralInterpFloat(Input + 1,  Tmp1, &p1);
+
+       T = LutTable + K1;
+       p1.Table = T;
+       TetrahedralInterpFloat(Input + 1,  Tmp2, &p1);
+
+       for (i=0; i < p -> nOutputs; i++)
+       {
+              cmsFloat32Number y0 = Tmp1[i];
+              cmsFloat32Number y1 = Tmp2[i];
+
+              Output[i] = y0 + (y1 - y0) * rest;
        }
-       else
-       if (ry >= rx && rx >= rz) {
+}
+
+
+static
+void Eval5Inputs(register const cmsUInt16Number Input[],
+                 register cmsUInt16Number Output[],
 
-              c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
-              c2 = DENS(X0, Y1, Z0) - c0;
-              c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+                 register const cmsInterpParams* p16)
+{
+       const cmsUInt16Number* LutTable = (cmsUInt16Number*) p16 -> Table;
+       cmsS15Fixed16Number fk;
+       cmsS15Fixed16Number k0, rk;
+       int K0, K1;
+       const cmsUInt16Number* T;
+       cmsUInt32Number i;
+       cmsUInt16Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
 
-       }
-       else
-       if (ry >= rz && rz >= rx) {
 
-              c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
-              c2 = DENS(X0, Y1, Z0) - c0;
-              c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
+       fk = _cmsToFixedDomain((cmsS15Fixed16Number) Input[0] * p16 -> Domain[0]);
+       k0 = FIXED_TO_INT(fk);
+       rk = FIXED_REST_TO_INT(fk);
 
-       }
-       else
-       if (rz >= ry && ry >= rx) {
+       K0 = p16 -> opta[4] * k0;
+       K1 = p16 -> opta[4] * (k0 + (Input[0] != 0xFFFFU ? 1 : 0));
+
+       p1 = *p16;
+       memmove(&p1.Domain[0], &p16 ->Domain[1], 4*sizeof(cmsUInt32Number));
 
-              c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
-              c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
-              c3 = DENS(X0, Y0, Z1) - c0;
+       T = LutTable + K0;
+       p1.Table = T;
+
+       Eval4Inputs(Input + 1, Tmp1, &p1);
 
-       }
-       else  {
-              c1 = c2 = c3 = 0;
-              // assert(FALSE);
+       T = LutTable + K1;
+       p1.Table = T;
+
+       Eval4Inputs(Input + 1, Tmp2, &p1);
+
+       for (i=0; i < p16 -> nOutputs; i++) {
+
+              Output[i] = LinearInterp(rk, Tmp1[i], Tmp2[i]);
        }
 
-        Rest = c1 * rx + c2 * ry + c3 * rz;
+}
+
+
+static
+void Eval5InputsFloat(const cmsFloat32Number Input[],
+                      cmsFloat32Number Output[],
+                      const cmsInterpParams* p)
+{
+       const cmsFloat32Number* LutTable = (cmsFloat32Number*) p -> Table;
+       cmsFloat32Number rest;
+       cmsFloat32Number pk;
+       int k0, K0, K1;
+       const cmsFloat32Number* T;
+       cmsUInt32Number i;
+       cmsFloat32Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
+
+       pk = Input[0] * p->Domain[0];
+       k0 = _cmsQuickFloor(pk);
+       rest = pk - (cmsFloat32Number) k0;
 
-        // There is a lot of math hidden in this expression. The rest is in fixed domain
-        // and the result in 0..ffff domain. So the complete expression should be
-        // ROUND_FIXED_TO_INT(ToFixedDomain(Rest)) But that can be optimized as (Rest + 0x7FFF) / 0xFFFF
+       K0 = p -> opta[4] * k0;
+       K1 = K0 + (Input[0] >= 1.0 ? 0 : p->opta[4]);
+
+       p1 = *p;
+       memmove(&p1.Domain[0], &p ->Domain[1], 4*sizeof(cmsUInt32Number));
+
+       T = LutTable + K0;
+       p1.Table = T;
+
+       Eval4InputsFloat(Input + 1,  Tmp1, &p1);
 
-        Output[OutChan] = (WORD) (c0 + ((Rest + 0x7FFF) / 0xFFFF));
+       T = LutTable + K1;
+       p1.Table = T;
+
+       Eval4InputsFloat(Input + 1,  Tmp2, &p1);
 
-    }
+       for (i=0; i < p -> nOutputs; i++) {
 
+              cmsFloat32Number y0 = Tmp1[i];
+              cmsFloat32Number y1 = Tmp2[i];
+
+              Output[i] = y0 + (y1 - y0) * rest;
+       }
 }
 
 
 
-#undef DENS
+static
+void Eval6Inputs(register const cmsUInt16Number Input[],
+                 register cmsUInt16Number Output[],
+                 register const cmsInterpParams* p16)
+{
+       const cmsUInt16Number* LutTable = (cmsUInt16Number*) p16 -> Table;
+       cmsS15Fixed16Number fk;
+       cmsS15Fixed16Number k0, rk;
+       int K0, K1;
+       const cmsUInt16Number* T;
+       cmsUInt32Number i;
+       cmsUInt16Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
+
+       fk = _cmsToFixedDomain((cmsS15Fixed16Number) Input[0] * p16 -> Domain[0]);
+       k0 = FIXED_TO_INT(fk);
+       rk = FIXED_REST_TO_INT(fk);
+
+       K0 = p16 -> opta[5] * k0;
+       K1 = p16 -> opta[5] * (k0 + (Input[0] != 0xFFFFU ? 1 : 0));
+
+       p1 = *p16;
+       memmove(&p1.Domain[0], &p16 ->Domain[1], 5*sizeof(cmsUInt32Number));
+
+       T = LutTable + K0;
+       p1.Table = T;
+
+       Eval5Inputs(Input + 1, Tmp1, &p1);
+
+       T = LutTable + K1;
+       p1.Table = T;
+
+       Eval5Inputs(Input + 1, Tmp2, &p1);
+
+       for (i=0; i < p16 -> nOutputs; i++) {
+
+              Output[i] = LinearInterp(rk, Tmp1[i], Tmp2[i]);
+       }
+
+}
+
 
-#endif
+static
+void Eval6InputsFloat(const cmsFloat32Number Input[],
+                      cmsFloat32Number Output[],
+                      const cmsInterpParams* p)
+{
+       const cmsFloat32Number* LutTable = (cmsFloat32Number*) p -> Table;
+       cmsFloat32Number rest;
+       cmsFloat32Number pk;
+       int k0, K0, K1;
+       const cmsFloat32Number* T;
+       cmsUInt32Number i;
+       cmsFloat32Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
+
+       pk = Input[0] * p->Domain[0];
+       k0 = _cmsQuickFloor(pk);
+       rest = pk - (cmsFloat32Number) k0;
+
+       K0 = p -> opta[5] * k0;
+       K1 = K0 + (Input[0] >= 1.0 ? 0 : p->opta[5]);
+
+       p1 = *p;
+       memmove(&p1.Domain[0], &p ->Domain[1], 5*sizeof(cmsUInt32Number));
+
+       T = LutTable + K0;
+       p1.Table = T;
+
+       Eval5InputsFloat(Input + 1,  Tmp1, &p1);
+
+       T = LutTable + K1;
+       p1.Table = T;
+
+       Eval5InputsFloat(Input + 1,  Tmp2, &p1);
+
+       for (i=0; i < p -> nOutputs; i++) {
+
+              cmsFloat32Number y0 = Tmp1[i];
+              cmsFloat32Number y1 = Tmp2[i];
+
+              Output[i] = y0 + (y1 - y0) * rest;
+       }
+}
+
+
+static
+void Eval7Inputs(register const cmsUInt16Number Input[],
+                 register cmsUInt16Number Output[],
+                 register const cmsInterpParams* p16)
+{
+       const cmsUInt16Number* LutTable = (cmsUInt16Number*) p16 -> Table;
+       cmsS15Fixed16Number fk;
+       cmsS15Fixed16Number k0, rk;
+       int K0, K1;
+       const cmsUInt16Number* T;
+       cmsUInt32Number i;
+       cmsUInt16Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
 
 
-// A optimized interpolation for 8-bit input.
+       fk = _cmsToFixedDomain((cmsS15Fixed16Number) Input[0] * p16 -> Domain[0]);
+       k0 = FIXED_TO_INT(fk);
+       rk = FIXED_REST_TO_INT(fk);
+
+       K0 = p16 -> opta[6] * k0;
+       K1 = p16 -> opta[6] * (k0 + (Input[0] != 0xFFFFU ? 1 : 0));
 
-#define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
+       p1 = *p16;
+       memmove(&p1.Domain[0], &p16 ->Domain[1], 5*sizeof(cmsUInt32Number));
+
+       T = LutTable + K0;
+       p1.Table = T;
+
+       Eval6Inputs(Input + 1, Tmp1, &p1);
 
-void cmsTetrahedralInterp8(WORD Input[],
-                           WORD Output[],
-                           WORD LutTable[],
-                           LPL16PARAMS p)
+       T = LutTable + K1;
+       p1.Table = T;
+
+       Eval6Inputs(Input + 1, Tmp2, &p1);
+
+       for (i=0; i < p16 -> nOutputs; i++) {
+              Output[i] = LinearInterp(rk, Tmp1[i], Tmp2[i]);
+       }
+}
+
+
+static
+void Eval7InputsFloat(const cmsFloat32Number Input[],
+                      cmsFloat32Number Output[],
+                      const cmsInterpParams* p)
 {
+       const cmsFloat32Number* LutTable = (cmsFloat32Number*) p -> Table;
+       cmsFloat32Number rest;
+       cmsFloat32Number pk;
+       int k0, K0, K1;
+       const cmsFloat32Number* T;
+       cmsUInt32Number i;
+       cmsFloat32Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
 
-       int        r, g, b;
-       Fixed32    rx, ry, rz;
-       Fixed32    c1, c2, c3, Rest;
-       int        OutChan;
-       register   Fixed32    X0, X1, Y0, Y1, Z0, Z1;
-       int        TotalOut = p -> nOutputs;
-       register   LPL8PARAMS p8 = p ->p8;
+       pk = Input[0] * p->Domain[0];
+       k0 = _cmsQuickFloor(pk);
+       rest = pk - (cmsFloat32Number) k0;
+
+       K0 = p -> opta[6] * k0;
+       K1 = K0 + (Input[0] >= 1.0 ? 0 : p->opta[6]);
+
+       p1 = *p;
+       memmove(&p1.Domain[0], &p ->Domain[1], 6*sizeof(cmsUInt32Number));
+
+       T = LutTable + K0;
+       p1.Table = T;
+
+       Eval6InputsFloat(Input + 1,  Tmp1, &p1);
+
+       T = LutTable + K1;
+       p1.Table = T;
+
+       Eval6InputsFloat(Input + 1,  Tmp2, &p1);
+
+
+       for (i=0; i < p -> nOutputs; i++) {
+
+              cmsFloat32Number y0 = Tmp1[i];
+              cmsFloat32Number y1 = Tmp2[i];
+
+              Output[i] = y0 + (y1 - y0) * rest;
+
+       }
+}
+
+static
+void Eval8Inputs(register const cmsUInt16Number Input[],
+                 register cmsUInt16Number Output[],
+                 register const cmsInterpParams* p16)
+{
+       const cmsUInt16Number* LutTable = (cmsUInt16Number*) p16 -> Table;
+       cmsS15Fixed16Number fk;
+       cmsS15Fixed16Number k0, rk;
+       int K0, K1;
+       const cmsUInt16Number* T;
+       cmsUInt32Number i;
+       cmsUInt16Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
+
+       fk = _cmsToFixedDomain((cmsS15Fixed16Number) Input[0] * p16 -> Domain[0]);
+       k0 = FIXED_TO_INT(fk);
+       rk = FIXED_REST_TO_INT(fk);
+
+       K0 = p16 -> opta[7] * k0;
+       K1 = p16 -> opta[7] * (k0 + (Input[0] != 0xFFFFU ? 1 : 0));
+
+       p1 = *p16;
+       memmove(&p1.Domain[0], &p16 ->Domain[1], 7*sizeof(cmsUInt32Number));
+
+       T = LutTable + K0;
+       p1.Table = T;
+
+       Eval7Inputs(Input + 1, Tmp1, &p1);
+
+       T = LutTable + K1;
+       p1.Table = T;
+       Eval7Inputs(Input + 1, Tmp2, &p1);
+
+       for (i=0; i < p16 -> nOutputs; i++) {
+              Output[i] = LinearInterp(rk, Tmp1[i], Tmp2[i]);
+       }
+}
 
 
 
-    r = Input[0] >> 8;
-    g = Input[1] >> 8;
-    b = Input[2] >> 8;
-
-    X0 = X1 = p8->X0[r];
-    Y0 = Y1 = p8->Y0[g];
-    Z0 = Z1 = p8->Z0[b];
+static
+void Eval8InputsFloat(const cmsFloat32Number Input[],
+                      cmsFloat32Number Output[],
+                      const cmsInterpParams* p)
+{
+       const cmsFloat32Number* LutTable = (cmsFloat32Number*) p -> Table;
+       cmsFloat32Number rest;
+       cmsFloat32Number pk;
+       int k0, K0, K1;
+       const cmsFloat32Number* T;
+       cmsUInt32Number i;
+       cmsFloat32Number Tmp1[MAX_STAGE_CHANNELS], Tmp2[MAX_STAGE_CHANNELS];
+       cmsInterpParams p1;
 
-    X1 += (r == 255) ? 0 : p ->opta3;
-    Y1 += (g == 255) ? 0 : p ->opta2;
-    Z1 += (b == 255) ? 0 : p ->opta1;
+       pk = Input[0] * p->Domain[0];
+       k0 = _cmsQuickFloor(pk);
+       rest = pk - (cmsFloat32Number) k0;
+
+       K0 = p -> opta[7] * k0;
+       K1 = K0 + (Input[0] >= 1.0 ? 0 : p->opta[7]);
+
+       p1 = *p;
+       memmove(&p1.Domain[0], &p ->Domain[1], 7*sizeof(cmsUInt32Number));
 
-    rx = p8 ->rx[r];
-    ry = p8 ->ry[g];
-    rz = p8 ->rz[b];
+       T = LutTable + K0;
+       p1.Table = T;
+
+       Eval7InputsFloat(Input + 1,  Tmp1, &p1);
+
+       T = LutTable + K1;
+       p1.Table = T;
+
+       Eval7InputsFloat(Input + 1,  Tmp2, &p1);
 
 
-    // These are the 6 Tetrahedral
-    for (OutChan=0; OutChan < TotalOut; OutChan++) {
-
-       if (rx >= ry && ry >= rz)
-       {
-
-              c1 = DENS(X1, Y0, Z0) - DENS(X0, Y0, Z0);
-              c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
-              c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+       for (i=0; i < p -> nOutputs; i++) {
 
-       }
-       else
-       if (rx >= rz && rz >= ry)
-       {
-              c1 = DENS(X1, Y0, Z0) - DENS(X0, Y0, Z0);
-              c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
-              c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
+              cmsFloat32Number y0 = Tmp1[i];
+              cmsFloat32Number y1 = Tmp2[i];
 
-       }
-       else
-       if (rz >= rx && rx >= ry)
-       {
-
-              c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
-              c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
-              c3 = DENS(X0, Y0, Z1) - DENS(X0, Y0, Z0);
-
+              Output[i] = y0 + (y1 - y0) * rest;
        }
-       else
-       if (ry >= rx && rx >= rz)
-       {
+}
+
+// The default factory
+static
+cmsInterpFunction DefaultInterpolatorsFactory(cmsUInt32Number nInputChannels, cmsUInt32Number nOutputChannels, cmsUInt32Number dwFlags)
+{
 
-              c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
-              c2 = DENS(X0, Y1, Z0) - DENS(X0, Y0, Z0);
-              c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+    cmsInterpFunction Interpolation;
+    cmsBool  IsFloat     = (dwFlags & CMS_LERP_FLAGS_FLOAT);
+    cmsBool  IsTrilinear = (dwFlags & CMS_LERP_FLAGS_TRILINEAR);
+
+    memset(&Interpolation, 0, sizeof(Interpolation));
 
-       }
-       else
-       if (ry >= rz && rz >= rx)
-       {
+    // Safety check
+    if (nInputChannels >= 4 && nOutputChannels >= MAX_STAGE_CHANNELS)
+        return Interpolation;
+
+    switch (nInputChannels) {
 
-              c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
-              c2 = DENS(X0, Y1, Z0) - DENS(X0, Y0, Z0);
-              c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
+           case 1: // Gray LUT / linear
+
+               if (nOutputChannels == 1) {
+
+                   if (IsFloat)
+                       Interpolation.LerpFloat = LinLerp1Dfloat;
+                   else
+                       Interpolation.Lerp16 = LinLerp1D;
 
-       }
-       else
-       if (rz >= ry && ry >= rx)
-       {
-              c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
-              c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
-              c3 = DENS(X0, Y0, Z1) - DENS(X0, Y0, Z0);
+               }
+               else {
 
-       }
-       else  {
-              c1 = c2 = c3 = 0;
-              // assert(FALSE);
-       }
+                   if (IsFloat)
+                       Interpolation.LerpFloat = Eval1InputFloat;
+                   else
+                       Interpolation.Lerp16 = Eval1Input;
+               }
+               break;
 
 
-        Rest = c1 * rx + c2 * ry + c3 * rz;
+           case 3:  // RGB et al
+
+               if (IsTrilinear) {
+
+                   if (IsFloat)
+                       Interpolation.LerpFloat = TrilinearInterpFloat;
+                   else
+                       Interpolation.Lerp16 = TrilinearInterp16;
+               }
+               else {
+
+                   if (IsFloat)
+                       Interpolation.LerpFloat = TetrahedralInterpFloat;
+                   else {
+
+                       Interpolation.Lerp16 = TetrahedralInterp16;
+                   }
+               }
+               break;
+
+           case 4:  // CMYK lut
+
+               if (IsFloat)
+                   Interpolation.LerpFloat =  Eval4InputsFloat;
+               else
+                   Interpolation.Lerp16    =  Eval4Inputs;
+               break;
 
-        Output[OutChan] = (WORD) (DENS(X0,Y0,Z0) + ((Rest + 0x7FFF) / 0xFFFF));
+           case 5: // 5 Inks
+               if (IsFloat)
+                   Interpolation.LerpFloat =  Eval5InputsFloat;
+               else
+                   Interpolation.Lerp16    =  Eval5Inputs;
+               break;
+
+           case 6: // 6 Inks
+               if (IsFloat)
+                   Interpolation.LerpFloat =  Eval6InputsFloat;
+               else
+                   Interpolation.Lerp16    =  Eval6Inputs;
+               break;
+
+           case 7: // 7 inks
+               if (IsFloat)
+                   Interpolation.LerpFloat =  Eval7InputsFloat;
+               else
+                   Interpolation.Lerp16    =  Eval7Inputs;
+               break;
+
+           case 8: // 8 inks
+               if (IsFloat)
+                   Interpolation.LerpFloat =  Eval8InputsFloat;
+               else
+                   Interpolation.Lerp16    =  Eval8Inputs;
+               break;
+
+               break;
+
+           default:
+               Interpolation.Lerp16 = NULL;
     }
 
+    return Interpolation;
 }
-
-#undef DENS
-
--- a/src/share/native/sun/java2d/cmm/lcms/cmsio0.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsio0.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -49,748 +50,1640 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
 
 // Generic I/O, tag dictionary management, profile struct
 
-
+// IOhandlers are abstractions used by littleCMS to read from whatever file, stream,
+// memory block or any storage. Each IOhandler provides implementations for read,
+// write, seek and tell functions. LittleCMS code deals with IO across those objects.
+// In this way, is easier to add support for new storage media.
 
-#include "lcms.h"
+// NULL stream, for taking care of used space -------------------------------------
 
-
-// Memory-based stream ---------------------------------------------------
+// NULL IOhandler basically does nothing but keep track on how many bytes have been
+// written. This is handy when creating profiles, where the file size is needed in the
+// header. Then, whole profile is serialized across NULL IOhandler and a second pass
+// writes the bytes to the pertinent IOhandler.
 
 typedef struct {
-                LPBYTE Block;           // Points to allocated memory
-                size_t Size;            // Size of allocated memory
-                size_t Pointer;         // Points to current location
-                int FreeBlockOnClose;   // As title
+    cmsUInt32Number Pointer;         // Points to current location
+} FILENULL;
+
+static
+cmsUInt32Number NULLRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
+{
+    FILENULL* ResData = (FILENULL*) iohandler ->stream;
+
+    cmsUInt32Number len = size * count;
+    ResData -> Pointer += len;
+    return count;
+
+    cmsUNUSED_PARAMETER(Buffer);
+}
 
-                } FILEMEM;
+static
+cmsBool  NULLSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
+{
+    FILENULL* ResData = (FILENULL*) iohandler ->stream;
+
+    ResData ->Pointer = offset;
+    return TRUE;
+}
+
+static
+cmsUInt32Number NULLTell(cmsIOHANDLER* iohandler)
+{
+    FILENULL* ResData = (FILENULL*) iohandler ->stream;
+    return ResData -> Pointer;
+}
 
 static
-LPVOID MemoryOpen(LPBYTE Block, size_t Size, char Mode)
+cmsBool  NULLWrite(cmsIOHANDLER* iohandler, cmsUInt32Number size, const void *Ptr)
 {
-    FILEMEM* fm = (FILEMEM*) _cmsMalloc(sizeof(FILEMEM));
-    if (fm == NULL) return NULL;
+    FILENULL* ResData = (FILENULL*) iohandler ->stream;
+
+    ResData ->Pointer += size;
+    if (ResData ->Pointer > iohandler->UsedSpace)
+        iohandler->UsedSpace = ResData ->Pointer;
+
+    return TRUE;
 
-    ZeroMemory(fm, sizeof(FILEMEM));
+    cmsUNUSED_PARAMETER(Ptr);
+}
 
-    if (Mode == 'r') {
+static
+cmsBool  NULLClose(cmsIOHANDLER* iohandler)
+{
+    FILENULL* ResData = (FILENULL*) iohandler ->stream;
 
-        fm ->Block   = (LPBYTE) _cmsMalloc(Size);
-        if (fm ->Block == NULL) {
-             _cmsFree(fm);
-            return NULL;
-        }
+    _cmsFree(iohandler ->ContextID, ResData);
+    _cmsFree(iohandler ->ContextID, iohandler);
+    return TRUE;
+}
 
-        CopyMemory(fm->Block, Block, Size);
-        fm ->FreeBlockOnClose = TRUE;
-    }
-    else {
-        fm ->Block = Block;
-        fm ->FreeBlockOnClose = FALSE;
-    }
+// The NULL IOhandler creator
+cmsIOHANDLER*  CMSEXPORT cmsOpenIOhandlerFromNULL(cmsContext ContextID)
+{
+    struct _cms_io_handler* iohandler = NULL;
+    FILENULL* fm = NULL;
 
-    fm ->Size    = Size;
+    iohandler = (struct _cms_io_handler*) _cmsMallocZero(ContextID, sizeof(struct _cms_io_handler));
+    if (iohandler == NULL) return NULL;
+
+    fm = (FILENULL*) _cmsMallocZero(ContextID, sizeof(FILENULL));
+    if (fm == NULL) goto Error;
+
     fm ->Pointer = 0;
 
-    return (LPVOID) fm;
+    iohandler ->ContextID = ContextID;
+    iohandler ->stream  = (void*) fm;
+    iohandler ->UsedSpace = 0;
+    iohandler ->PhysicalFile[0] = 0;
+
+    iohandler ->Read    = NULLRead;
+    iohandler ->Seek    = NULLSeek;
+    iohandler ->Close   = NULLClose;
+    iohandler ->Tell    = NULLTell;
+    iohandler ->Write   = NULLWrite;
+
+    return iohandler;
+
+Error:
+    if (fm) _cmsFree(ContextID, fm);
+    if (iohandler) _cmsFree(ContextID, iohandler);
+    return NULL;
+
 }
 
 
-static
-size_t MemoryRead(LPVOID buffer, size_t size, size_t count, struct _lcms_iccprofile_struct* Icc)
-{
-     FILEMEM* ResData = (FILEMEM*) Icc ->stream;
-     LPBYTE Ptr;
-     size_t len = size * count;
-     size_t extent = ResData -> Pointer + len;
+// Memory-based stream --------------------------------------------------------------
+
+// Those functions implements an iohandler which takes a block of memory as storage medium.
 
-        if (len == 0) {
-                return 0;
-        }
+typedef struct {
+    cmsUInt8Number* Block;    // Points to allocated memory
+    cmsUInt32Number Size;     // Size of allocated memory
+    cmsUInt32Number Pointer;  // Points to current location
+    int FreeBlockOnClose;     // As title
+
+} FILEMEM;
 
-        if (len / size != count) {
-          cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Integer overflow with count / size.");
-          return 0;
-      }
+static
+cmsUInt32Number MemoryRead(struct _cms_io_handler* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
+{
+    FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
+    cmsUInt8Number* Ptr;
+    cmsUInt32Number len = size * count;
 
-      if (extent < len || extent < ResData -> Pointer) {
-          cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Integer overflow with len.");
-          return 0;
-      }
+    if (ResData -> Pointer + len > ResData -> Size){
 
-      if (ResData -> Pointer + len > ResData -> Size) {
-
-         len = (ResData -> Size - ResData -> Pointer);
-         cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Got %d bytes, block should be of %d bytes", len * size, count * size);
-         return 0;
-     }
+        len = (ResData -> Size - ResData -> Pointer);
+        cmsSignalError(iohandler ->ContextID, cmsERROR_READ, "Read from memory error. Got %d bytes, block should be of %d bytes", len, count * size);
+        return 0;
+    }
 
     Ptr  = ResData -> Block;
     Ptr += ResData -> Pointer;
-    CopyMemory(buffer, Ptr, len);
-    ResData -> Pointer += (int) len;
+    memmove(Buffer, Ptr, len);
+    ResData -> Pointer += len;
 
     return count;
 }
 
 // SEEK_CUR is assumed
-
 static
-LCMSBOOL MemorySeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
+cmsBool  MemorySeek(struct _cms_io_handler* iohandler, cmsUInt32Number offset)
 {
-    FILEMEM* ResData = (FILEMEM*) Icc ->stream;
+    FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
 
     if (offset > ResData ->Size) {
-         cmsSignalError(LCMS_ERRC_ABORTED,  "Pointer error; probably corrupted file");
-         return TRUE;
+        cmsSignalError(iohandler ->ContextID, cmsERROR_SEEK,  "Too few data; probably corrupted profile");
+        return FALSE;
     }
 
-    ResData ->Pointer = (DWORD) offset;
-    return FALSE;
+    ResData ->Pointer = offset;
+    return TRUE;
 }
 
-// FTell
-
+// Tell for memory
 static
-size_t MemoryTell(struct _lcms_iccprofile_struct* Icc)
+cmsUInt32Number MemoryTell(struct _cms_io_handler* iohandler)
 {
-    FILEMEM* ResData = (FILEMEM*) Icc ->stream;
+    FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
 
+    if (ResData == NULL) return 0;
     return ResData -> Pointer;
 }
 
 
-// Writes data to memory, also keeps used space for further reference. NO CHECK IS PERFORMED
-
+// Writes data to memory, also keeps used space for further reference.
 static
-LCMSBOOL MemoryWrite(struct _lcms_iccprofile_struct* Icc, size_t size, void *Ptr)
+cmsBool  MemoryWrite(struct _cms_io_handler* iohandler, cmsUInt32Number size, const void *Ptr)
 {
-        FILEMEM* ResData = (FILEMEM*) Icc ->stream;
+    FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
 
-       if (size == 0) return TRUE;
+    if (ResData == NULL) return FALSE; // Housekeeping
 
-       if (ResData != NULL)
-           CopyMemory(ResData ->Block + ResData ->Pointer, Ptr, size);
+    if (size == 0) return TRUE;     // Write zero bytes is ok, but does nothing
 
-       ResData->Pointer += size;
-       Icc->UsedSpace += size;
+    memmove(ResData ->Block + ResData ->Pointer, Ptr, size);
+    ResData ->Pointer += size;
 
-       return TRUE;
-}
+    if (ResData ->Pointer > iohandler->UsedSpace)
+        iohandler->UsedSpace = ResData ->Pointer;
 
 
-static
-LCMSBOOL MemoryGrow(struct _lcms_iccprofile_struct* Icc, size_t size)
-{
-    FILEMEM* ResData = (FILEMEM*) Icc->stream;
-
-    void* newBlock = NULL;
+    iohandler->UsedSpace += size;
 
-    /* Follow same policies as functions in lcms.h  */
-    if (ResData->Size + size < 0) return NULL;
-    if (ResData->Size + size > ((size_t)1024*1024*500)) return NULL;
-
-    newBlock = realloc(ResData->Block, ResData->Size + size);
-
-    if (!newBlock) {
-        return FALSE;
-    }
-    ResData->Block = newBlock;
-    ResData->Size += size;
     return TRUE;
 }
 
 
 static
-LCMSBOOL MemoryClose(struct _lcms_iccprofile_struct* Icc)
+cmsBool  MemoryClose(struct _cms_io_handler* iohandler)
 {
-    FILEMEM* ResData = (FILEMEM*) Icc ->stream;
+    FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
 
     if (ResData ->FreeBlockOnClose) {
 
-        if (ResData ->Block)  _cmsFree(ResData ->Block);
+        if (ResData ->Block) _cmsFree(iohandler ->ContextID, ResData ->Block);
     }
-     _cmsFree(ResData);
-    return 0;
+
+    _cmsFree(iohandler ->ContextID, ResData);
+    _cmsFree(iohandler ->ContextID, iohandler);
+
+    return TRUE;
 }
 
+// Create a iohandler for memory block. AccessMode=='r' assumes the iohandler is going to read, and makes
+// a copy of the memory block for letting user to free the memory after invoking open profile. In write
+// mode ("w"), Buffere points to the begin of memory block to be written.
+cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromMem(cmsContext ContextID, void *Buffer, cmsUInt32Number size, const char* AccessMode)
+{
+    cmsIOHANDLER* iohandler = NULL;
+    FILEMEM* fm = NULL;
+
+    _cmsAssert(AccessMode != NULL);
+
+    iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
+    if (iohandler == NULL) return NULL;
+
+    switch (*AccessMode) {
+
+    case 'r':
+        fm = (FILEMEM*) _cmsMallocZero(ContextID, sizeof(FILEMEM));
+        if (fm == NULL) goto Error;
+
+        if (Buffer == NULL) {
+            cmsSignalError(ContextID, cmsERROR_READ, "Couldn't read profile from NULL pointer");
+            goto Error;
+        }
+
+        fm ->Block = (cmsUInt8Number*) _cmsMalloc(ContextID, size);
+        if (fm ->Block == NULL) {
+
+            _cmsFree(ContextID, fm);
+            _cmsFree(ContextID, iohandler);
+            cmsSignalError(ContextID, cmsERROR_READ, "Couldn't allocate %ld bytes for profile", size);
+            return NULL;
+        }
+
+
+        memmove(fm->Block, Buffer, size);
+        fm ->FreeBlockOnClose = TRUE;
+        fm ->Size    = size;
+        fm ->Pointer = 0;
+        break;
+
+    case 'w':
+        fm = (FILEMEM*) _cmsMallocZero(ContextID, sizeof(FILEMEM));
+        if (fm == NULL) goto Error;
+
+        fm ->Block = (cmsUInt8Number*) Buffer;
+        fm ->FreeBlockOnClose = FALSE;
+        fm ->Size    = size;
+        fm ->Pointer = 0;
+        break;
+
+    default:
+        cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknow access mode '%c'", *AccessMode);
+        return NULL;
+    }
+
+    iohandler ->ContextID = ContextID;
+    iohandler ->stream  = (void*) fm;
+    iohandler ->UsedSpace = 0;
+    iohandler ->PhysicalFile[0] = 0;
+
+    iohandler ->Read    = MemoryRead;
+    iohandler ->Seek    = MemorySeek;
+    iohandler ->Close   = MemoryClose;
+    iohandler ->Tell    = MemoryTell;
+    iohandler ->Write   = MemoryWrite;
+
+    return iohandler;
+
+Error:
+    if (fm) _cmsFree(ContextID, fm);
+    if (iohandler) _cmsFree(ContextID, iohandler);
+    return NULL;
+}
 
 // File-based stream -------------------------------------------------------
 
+// Read count elements of size bytes each. Return number of elements read
 static
-LPVOID FileOpen(const char* filename)
+cmsUInt32Number FileRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
 {
-    return (void*) fopen(filename, "rb");
-}
+    cmsUInt32Number nReaded = (cmsUInt32Number) fread(Buffer, size, count, (FILE*) iohandler->stream);
 
-static
-size_t FileRead(void *buffer, size_t size, size_t count, struct _lcms_iccprofile_struct* Icc)
-{
-    size_t nReaded = fread(buffer, size, count, (FILE*) Icc->stream);
     if (nReaded != count) {
-            cmsSignalError(LCMS_ERRC_ABORTED, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
+            cmsSignalError(iohandler ->ContextID, cmsERROR_FILE, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
             return 0;
     }
 
     return nReaded;
 }
 
+// Postion file pointer in the file
+static
+cmsBool  FileSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
+{
+    if (fseek((FILE*) iohandler ->stream, (long) offset, SEEK_SET) != 0) {
+
+       cmsSignalError(iohandler ->ContextID, cmsERROR_FILE, "Seek error; probably corrupted file");
+       return FALSE;
+    }
+
+    return TRUE;
+}
+
+// Returns file pointer position
+static
+cmsUInt32Number FileTell(cmsIOHANDLER* iohandler)
+{
+    return ftell((FILE*)iohandler ->stream);
+}
+
+// Writes data to stream, also keeps used space for further reference. Returns TRUE on success, FALSE on error
+static
+cmsBool  FileWrite(cmsIOHANDLER* iohandler, cmsUInt32Number size, const void* Buffer)
+{
+       if (size == 0) return TRUE;  // We allow to write 0 bytes, but nothing is written
+
+       iohandler->UsedSpace += size;
+       return (fwrite(Buffer, size, 1, (FILE*) iohandler->stream) == 1);
+}
+
+// Closes the file
+static
+cmsBool  FileClose(cmsIOHANDLER* iohandler)
+{
+    if (fclose((FILE*) iohandler ->stream) != 0) return FALSE;
+    _cmsFree(iohandler ->ContextID, iohandler);
+    return TRUE;
+}
+
+// Create a iohandler for disk based files. if FileName is NULL, then 'stream' member is also set
+// to NULL and no real writting is performed. This only happens in writting access mode
+cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromFile(cmsContext ContextID, const char* FileName, const char* AccessMode)
+{
+    cmsIOHANDLER* iohandler = NULL;
+    FILE* fm = NULL;
+
+    iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
+    if (iohandler == NULL) return NULL;
+
+    switch (*AccessMode) {
+
+    case 'r':
+        fm = fopen(FileName, "rb");
+        if (fm == NULL) {
+            _cmsFree(ContextID, iohandler);
+             cmsSignalError(ContextID, cmsERROR_FILE, "File '%s' not found", FileName);
+            return NULL;
+        }
+        break;
+
+    case 'w':
+        fm = fopen(FileName, "wb");
+        if (fm == NULL) {
+            _cmsFree(ContextID, iohandler);
+             cmsSignalError(ContextID, cmsERROR_FILE, "Couldn't create '%s'", FileName);
+            return NULL;
+        }
+        break;
+
+    default:
+        _cmsFree(ContextID, iohandler);
+         cmsSignalError(ContextID, cmsERROR_FILE, "Unknow access mode '%c'", *AccessMode);
+        return NULL;
+    }
+
+    iohandler ->ContextID = ContextID;
+    iohandler ->stream = (void*) fm;
+    iohandler ->UsedSpace = 0;
+
+    // Keep track of the original file
+    if (FileName != NULL)  {
+
+        strncpy(iohandler -> PhysicalFile, FileName, sizeof(iohandler -> PhysicalFile)-1);
+        iohandler -> PhysicalFile[sizeof(iohandler -> PhysicalFile)-1] = 0;
+    }
+
+    iohandler ->Read    = FileRead;
+    iohandler ->Seek    = FileSeek;
+    iohandler ->Close   = FileClose;
+    iohandler ->Tell    = FileTell;
+    iohandler ->Write   = FileWrite;
+
+    return iohandler;
+}
+
+// Create a iohandler for stream based files
+cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromStream(cmsContext ContextID, FILE* Stream)
+{
+    cmsIOHANDLER* iohandler = NULL;
+
+    iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
+    if (iohandler == NULL) return NULL;
+
+    iohandler -> ContextID = ContextID;
+    iohandler -> stream = (void*) Stream;
+    iohandler -> UsedSpace = 0;
+    iohandler -> PhysicalFile[0] = 0;
+
+    iohandler ->Read    = FileRead;
+    iohandler ->Seek    = FileSeek;
+    iohandler ->Close   = FileClose;
+    iohandler ->Tell    = FileTell;
+    iohandler ->Write   = FileWrite;
+
+    return iohandler;
+}
+
+
+
+// Close an open IO handler
+cmsBool CMSEXPORT cmsCloseIOhandler(cmsIOHANDLER* io)
+{
+    return io -> Close(io);
+}
+
+// -------------------------------------------------------------------------------------------------------
+
+// Creates an empty structure holding all required parameters
+cmsHPROFILE CMSEXPORT cmsCreateProfilePlaceholder(cmsContext ContextID)
+{
+    time_t now = time(NULL);
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) _cmsMallocZero(ContextID, sizeof(_cmsICCPROFILE));
+    if (Icc == NULL) return NULL;
+
+    Icc ->ContextID = ContextID;
+
+    // Set it to empty
+    Icc -> TagCount   = 0;
+
+    // Set default version
+    Icc ->Version =  0x02100000;
+
+    // Set creation date/time
+    memmove(&Icc ->Created, gmtime(&now), sizeof(Icc ->Created));
+
+    // Return the handle
+    return (cmsHPROFILE) Icc;
+}
+
+cmsContext CMSEXPORT cmsGetProfileContextID(cmsHPROFILE hProfile)
+{
+     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+
+    if (Icc == NULL) return NULL;
+    return Icc -> ContextID;
+}
+
+
+// Return the number of tags
+cmsInt32Number CMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    if (Icc == NULL) return -1;
+
+    return  Icc->TagCount;
+}
+
+// Return the tag signature of a given tag number
+cmsTagSignature CMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, cmsUInt32Number n)
+{
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+
+    if (n > Icc->TagCount) return (cmsTagSignature) 0;  // Mark as not available
+    if (n >= MAX_TABLE_TAG) return (cmsTagSignature) 0; // As double check
+
+    return Icc ->TagNames[n];
+}
+
+
+static
+int SearchOneTag(_cmsICCPROFILE* Profile, cmsTagSignature sig)
+{
+    cmsUInt32Number i;
+
+    for (i=0; i < Profile -> TagCount; i++) {
+
+        if (sig == Profile -> TagNames[i])
+            return i;
+    }
+
+    return -1;
+}
+
+// Search for a specific tag in tag dictionary. Returns position or -1 if tag not found.
+// If followlinks is turned on, then the position of the linked tag is returned
+int _cmsSearchTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, cmsBool lFollowLinks)
+{
+    int n;
+    cmsTagSignature LinkedSig;
+
+    do {
+
+        // Search for given tag in ICC profile directory
+        n = SearchOneTag(Icc, sig);
+        if (n < 0)
+            return -1;        // Not found
+
+        if (!lFollowLinks)
+            return n;         // Found, don't follow links
+
+        // Is this a linked tag?
+        LinkedSig = Icc ->TagLinked[n];
+
+        // Yes, follow link
+        if (LinkedSig != (cmsTagSignature) 0) {
+            sig = LinkedSig;
+        }
+
+    } while (LinkedSig != (cmsTagSignature) 0);
+
+    return n;
+}
+
+
+// Create a new tag entry
 
 static
-LCMSBOOL FileSeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
+cmsBool _cmsNewTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, int* NewPos)
+{
+    int i;
+
+    // Search for the tag
+    i = _cmsSearchTag(Icc, sig, FALSE);
+
+    // Now let's do it easy. If the tag has been already written, that's an error
+    if (i >= 0) {
+        cmsSignalError(Icc ->ContextID, cmsERROR_ALREADY_DEFINED, "Tag '%x' already exists", sig);
+        return FALSE;
+    }
+    else  {
+
+        // New one
+
+        if (Icc -> TagCount >= MAX_TABLE_TAG) {
+            cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
+            return FALSE;
+        }
+
+        *NewPos = Icc ->TagCount;
+        Icc -> TagCount++;
+    }
+
+    return TRUE;
+}
+
+
+// Check existance
+cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
+{
+       _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) (void*) hProfile;
+       return _cmsSearchTag(Icc, sig, FALSE) >= 0;
+}
+
+
+// Read profile header and validate it
+cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
+{
+    cmsTagEntry Tag;
+    cmsICCHeader Header;
+    cmsUInt32Number i, j;
+    cmsUInt32Number HeaderSize;
+    cmsIOHANDLER* io = Icc ->IOhandler;
+    cmsUInt32Number TagCount;
+
+
+    // Read the header
+    if (io -> Read(io, &Header, sizeof(cmsICCHeader), 1) != 1) {
+        return FALSE;
+    }
+
+    // Validate file as an ICC profile
+    if (_cmsAdjustEndianess32(Header.magic) != cmsMagicNumber) {
+        cmsSignalError(Icc ->ContextID, cmsERROR_BAD_SIGNATURE, "not an ICC profile, invalid signature");
+        return FALSE;
+    }
+
+    // Adjust endianess of the used parameters
+    Icc -> DeviceClass     = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
+    Icc -> ColorSpace      = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.colorSpace);
+    Icc -> PCS             = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.pcs);
+    Icc -> RenderingIntent = _cmsAdjustEndianess32(Header.renderingIntent);
+    Icc -> flags           = _cmsAdjustEndianess32(Header.flags);
+    Icc -> manufacturer    = _cmsAdjustEndianess32(Header.manufacturer);
+    Icc -> model           = _cmsAdjustEndianess32(Header.model);
+    _cmsAdjustEndianess64(&Icc -> attributes, Header.attributes);
+    Icc -> Version         = _cmsAdjustEndianess32(Header.version);
+
+    // Get size as reported in header
+    HeaderSize = _cmsAdjustEndianess32(Header.size);
+
+    // Get creation date/time
+    _cmsDecodeDateTimeNumber(&Header.date, &Icc ->Created);
+
+    // The profile ID are 32 raw bytes
+    memmove(Icc ->ProfileID.ID32, Header.profileID.ID32, 16);
+
+
+    // Read tag directory
+    if (!_cmsReadUInt32Number(io, &TagCount)) return FALSE;
+    if (TagCount > MAX_TABLE_TAG) {
+
+        cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", TagCount);
+        return FALSE;
+    }
+
+    // Read tag directory
+    Icc -> TagCount = 0;
+    for (i=0; i < TagCount; i++) {
+
+        if (!_cmsReadUInt32Number(io, (cmsUInt32Number *) &Tag.sig)) return FALSE;
+        if (!_cmsReadUInt32Number(io, &Tag.offset)) return FALSE;
+        if (!_cmsReadUInt32Number(io, &Tag.size)) return FALSE;
+
+        // Perform some sanity check. Offset + size should fall inside file.
+        if (Tag.offset + Tag.size > HeaderSize)
+                  continue;
+
+        Icc -> TagNames[Icc ->TagCount]   = Tag.sig;
+        Icc -> TagOffsets[Icc ->TagCount] = Tag.offset;
+        Icc -> TagSizes[Icc ->TagCount]   = Tag.size;
+
+       // Search for links
+        for (j=0; j < Icc ->TagCount; j++) {
+
+            if ((Icc ->TagOffsets[j] == Tag.offset) &&
+                (Icc ->TagSizes[j]   == Tag.size)) {
+
+                Icc ->TagLinked[Icc ->TagCount] = Icc ->TagNames[j];
+            }
+
+        }
+
+        Icc ->TagCount++;
+    }
+
+    return TRUE;
+}
+
+// Saves profile header
+cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace)
+{
+    cmsICCHeader Header;
+    cmsUInt32Number i;
+    cmsTagEntry Tag;
+    cmsInt32Number Count = 0;
+
+    Header.size        = _cmsAdjustEndianess32(UsedSpace);
+    Header.cmmId       = _cmsAdjustEndianess32(lcmsSignature);
+    Header.version     = _cmsAdjustEndianess32(Icc ->Version);
+
+    Header.deviceClass = (cmsProfileClassSignature) _cmsAdjustEndianess32(Icc -> DeviceClass);
+    Header.colorSpace  = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> ColorSpace);
+    Header.pcs         = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> PCS);
+
+    //   NOTE: in v4 Timestamp must be in UTC rather than in local time
+    _cmsEncodeDateTimeNumber(&Header.date, &Icc ->Created);
+
+    Header.magic       = _cmsAdjustEndianess32(cmsMagicNumber);
+
+#ifdef CMS_IS_WINDOWS_
+    Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMicrosoft);
+#else
+    Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMacintosh);
+#endif
+
+    Header.flags        = _cmsAdjustEndianess32(Icc -> flags);
+    Header.manufacturer = _cmsAdjustEndianess32(Icc -> manufacturer);
+    Header.model        = _cmsAdjustEndianess32(Icc -> model);
+
+    _cmsAdjustEndianess64(&Header.attributes, Icc -> attributes);
+
+    // Rendering intent in the header (for embedded profiles)
+    Header.renderingIntent = _cmsAdjustEndianess32(Icc -> RenderingIntent);
+
+    // Illuminant is always D50
+    Header.illuminant.X = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->X));
+    Header.illuminant.Y = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->Y));
+    Header.illuminant.Z = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(cmsD50_XYZ()->Z));
+
+    // Created by LittleCMS (that's me!)
+    Header.creator      = _cmsAdjustEndianess32(lcmsSignature);
+
+    memset(&Header.reserved, 0, sizeof(Header.reserved));
+
+    // Set profile ID. Endianess is always big endian
+    memmove(&Header.profileID, &Icc ->ProfileID, 16);
+
+    // Dump the header
+    if (!Icc -> IOhandler->Write(Icc->IOhandler, sizeof(cmsICCHeader), &Header)) return FALSE;
+
+    // Saves Tag directory
+
+    // Get true count
+    for (i=0;  i < Icc -> TagCount; i++) {
+        if (Icc ->TagNames[i] != 0)
+            Count++;
+    }
+
+    // Store number of tags
+    if (!_cmsWriteUInt32Number(Icc ->IOhandler, Count)) return FALSE;
+
+    for (i=0; i < Icc -> TagCount; i++) {
+
+        if (Icc ->TagNames[i] == 0) continue;   // It is just a placeholder
+
+        Tag.sig    = (cmsTagSignature) _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagNames[i]);
+        Tag.offset = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagOffsets[i]);
+        Tag.size   = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagSizes[i]);
+
+        if (!Icc ->IOhandler -> Write(Icc-> IOhandler, sizeof(cmsTagEntry), &Tag)) return FALSE;
+    }
+
+    return TRUE;
+}
+
+// ----------------------------------------------------------------------- Set/Get several struct members
+
+
+cmsUInt32Number CMSEXPORT cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    return Icc -> RenderingIntent;
+}
+
+void CMSEXPORT cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile, cmsUInt32Number RenderingIntent)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    Icc -> RenderingIntent = RenderingIntent;
+}
+
+cmsUInt32Number CMSEXPORT cmsGetHeaderFlags(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    return (cmsUInt32Number) Icc -> flags;
+}
+
+void CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    Icc -> flags = (cmsUInt32Number) Flags;
+}
+
+cmsUInt32Number CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    return (cmsUInt32Number) Icc ->manufacturer;
+}
+
+void CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    Icc -> manufacturer = (cmsUInt32Number) manufacturer;
+}
+
+cmsUInt32Number CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    return (cmsUInt32Number) Icc ->model;
+}
+
+void CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    Icc -> manufacturer = (cmsUInt32Number) model;
+}
+
+
+void CMSEXPORT cmsGetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number* Flags)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    memmove(Flags, &Icc -> attributes, sizeof(cmsUInt64Number));
+}
+
+void CMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number Flags)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    memmove(&Icc -> attributes, &Flags, sizeof(cmsUInt64Number));
+}
+
+void CMSEXPORT cmsGetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    memmove(ProfileID, Icc ->ProfileID.ID8, 16);
+}
+
+void CMSEXPORT cmsSetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    memmove(&Icc -> ProfileID, ProfileID, 16);
+}
+
+cmsBool  CMSEXPORT cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile, struct tm *Dest)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    memmove(Dest, &Icc ->Created, sizeof(struct tm));
+    return TRUE;
+}
+
+cmsColorSpaceSignature CMSEXPORT cmsGetPCS(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    return Icc -> PCS;
+}
+
+void CMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, cmsColorSpaceSignature pcs)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    Icc -> PCS = pcs;
+}
+
+cmsColorSpaceSignature CMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    return Icc -> ColorSpace;
+}
+
+void CMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, cmsColorSpaceSignature sig)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    Icc -> ColorSpace = sig;
+}
+
+cmsProfileClassSignature CMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    return Icc -> DeviceClass;
+}
+
+void CMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, cmsProfileClassSignature sig)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    Icc -> DeviceClass = sig;
+}
+
+cmsUInt32Number CMSEXPORT cmsGetEncodedICCversion(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    return Icc -> Version;
+}
+
+void CMSEXPORT cmsSetEncodedICCversion(cmsHPROFILE hProfile, cmsUInt32Number Version)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    Icc -> Version = Version;
+}
+
+// Get an hexadecimal number with same digits as v
+static
+cmsUInt32Number BaseToBase(cmsUInt32Number in, int BaseIn, int BaseOut)
+{
+    char Buff[100];
+    int i, len;
+    cmsUInt32Number out;
+
+    for (len=0; in > 0 && len < 100; len++) {
+
+        Buff[len] = (char) (in % BaseIn);
+        in /= BaseIn;
+    }
+
+    for (i=len-1, out=0; i >= 0; --i) {
+        out = out * BaseOut + Buff[i];
+    }
+
+    return out;
+}
+
+void  CMSEXPORT cmsSetProfileVersion(cmsHPROFILE hProfile, cmsFloat64Number Version)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+
+    // 4.2 -> 0x4200000
+
+    Icc -> Version = BaseToBase((cmsUInt32Number) floor(Version * 100.0), 10, 16) << 16;
+}
+
+cmsFloat64Number CMSEXPORT cmsGetProfileVersion(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
+    cmsUInt32Number n = Icc -> Version >> 16;
+
+    return BaseToBase(n, 16, 10) / 100.0;
+}
+// --------------------------------------------------------------------------------------------------------------
+
+
+// Create profile from IOhandler
+cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID, cmsIOHANDLER* io)
 {
-    if (fseek((FILE*) Icc ->stream, (long) offset, SEEK_SET) != 0) {
+    _cmsICCPROFILE* NewIcc;
+    cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
+
+    if (hEmpty == NULL) return NULL;
+
+    NewIcc = (_cmsICCPROFILE*) hEmpty;
+
+    NewIcc ->IOhandler = io;
+    if (!_cmsReadHeader(NewIcc)) goto Error;
+    return hEmpty;
+
+Error:
+    cmsCloseProfile(hEmpty);
+    return NULL;
+}
+
+// Create profile from disk file
+cmsHPROFILE CMSEXPORT cmsOpenProfileFromFileTHR(cmsContext ContextID, const char *lpFileName, const char *sAccess)
+{
+    _cmsICCPROFILE* NewIcc;
+    cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
+
+    if (hEmpty == NULL) return NULL;
+
+    NewIcc = (_cmsICCPROFILE*) hEmpty;
+
+    NewIcc ->IOhandler = cmsOpenIOhandlerFromFile(ContextID, lpFileName, sAccess);
+    if (NewIcc ->IOhandler == NULL) goto Error;
+
+    if (*sAccess == 'W' || *sAccess == 'w') {
+
+        NewIcc -> IsWrite = TRUE;
+
+        return hEmpty;
+    }
+
+    if (!_cmsReadHeader(NewIcc)) goto Error;
+    return hEmpty;
+
+Error:
+    cmsCloseProfile(hEmpty);
+    return NULL;
+}
+
+
+cmsHPROFILE CMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess)
+{
+    return cmsOpenProfileFromFileTHR(NULL, ICCProfile, sAccess);
+}
+
+
+cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStreamTHR(cmsContext ContextID, FILE* ICCProfile, const char *sAccess)
+{
+    _cmsICCPROFILE* NewIcc;
+    cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
+
+    if (hEmpty == NULL) return NULL;
+
+    NewIcc = (_cmsICCPROFILE*) hEmpty;
+
+    NewIcc ->IOhandler = cmsOpenIOhandlerFromStream(ContextID, ICCProfile);
+    if (NewIcc ->IOhandler == NULL) goto Error;
+
+    if (*sAccess == 'w') {
+
+        NewIcc -> IsWrite = TRUE;
+        return hEmpty;
+    }
+
+    if (!_cmsReadHeader(NewIcc)) goto Error;
+    return hEmpty;
+
+Error:
+    cmsCloseProfile(hEmpty);
+    return NULL;
+
+}
+
+cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStream(FILE* ICCProfile, const char *sAccess)
+{
+    return cmsOpenProfileFromStreamTHR(NULL, ICCProfile, sAccess);
+}
+
+
+// Open from memory block
+cmsHPROFILE CMSEXPORT cmsOpenProfileFromMemTHR(cmsContext ContextID, const void* MemPtr, cmsUInt32Number dwSize)
+{
+    _cmsICCPROFILE* NewIcc;
+    cmsHPROFILE hEmpty;
+
+    hEmpty = cmsCreateProfilePlaceholder(ContextID);
+    if (hEmpty == NULL) return NULL;
+
+    NewIcc = (_cmsICCPROFILE*) hEmpty;
+
+    // Ok, in this case const void* is casted to void* just because open IO handler
+    // shares read and writting modes. Don't abuse this feature!
+    NewIcc ->IOhandler = cmsOpenIOhandlerFromMem(ContextID, (void*) MemPtr, dwSize, "r");
+    if (NewIcc ->IOhandler == NULL) goto Error;
+
+    if (!_cmsReadHeader(NewIcc)) goto Error;
+
+    return hEmpty;
+
+Error:
+    cmsCloseProfile(hEmpty);
+    return NULL;
+}
+
+cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number dwSize)
+{
+    return cmsOpenProfileFromMemTHR(NULL, MemPtr, dwSize);
+}
+
+
+
+// Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
+static
+cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
+{
+    cmsUInt8Number* Data;
+    cmsUInt32Number i;
+    cmsUInt32Number Begin;
+    cmsIOHANDLER* io = Icc ->IOhandler;
+    cmsTagDescriptor* TagDescriptor;
+    cmsTagTypeSignature TypeBase;
+    cmsTagTypeHandler* TypeHandler;
+
+
+    for (i=0; i < Icc -> TagCount; i++) {
+
+
+        if (Icc ->TagNames[i] == 0) continue;
+
+        // Linked tags are not written
+        if (Icc ->TagLinked[i] != (cmsTagSignature) 0) continue;
+
+        Icc -> TagOffsets[i] = Begin = io ->UsedSpace;
+
+        Data = (cmsUInt8Number*)  Icc -> TagPtrs[i];
+
+        if (!Data) {
+
+            // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user.
+            // In this case a blind copy of the block data is performed
+            if (FileOrig != NULL && Icc -> TagOffsets[i]) {
+
+                cmsUInt32Number TagSize   = FileOrig -> TagSizes[i];
+                cmsUInt32Number TagOffset = FileOrig -> TagOffsets[i];
+                void* Mem;
+
+                if (!FileOrig ->IOhandler->Seek(FileOrig ->IOhandler, TagOffset)) return FALSE;
+
+                Mem = _cmsMalloc(Icc ->ContextID, TagSize);
+                if (Mem == NULL) return FALSE;
+
+                if (FileOrig ->IOhandler->Read(FileOrig->IOhandler, Mem, TagSize, 1) != 1) return FALSE;
+                if (!io ->Write(io, TagSize, Mem)) return FALSE;
+                _cmsFree(Icc ->ContextID, Mem);
+
+                Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
+
+
+                // Align to 32 bit boundary.
+                if (! _cmsWriteAlignment(io))
+                    return FALSE;
+            }
+
+            continue;
+        }
+
+
+        // Should this tag be saved as RAW? If so, tagsizes should be specified in advance (no further cooking is done)
+        if (Icc ->TagSaveAsRaw[i]) {
+
+            if (io -> Write(io, Icc ->TagSizes[i], Data) != 1) return FALSE;
+        }
+        else {
+
+            // Search for support on this tag
+            TagDescriptor = _cmsGetTagDescriptor(Icc -> TagNames[i]);
+            if (TagDescriptor == NULL) continue;                        // Unsupported, ignore it
+
+            TypeHandler = Icc ->TagTypeHandlers[i];
+
+            if (TypeHandler == NULL) {
+                cmsSignalError(Icc ->ContextID, cmsERROR_INTERNAL, "(Internal) no handler for tag %x", Icc -> TagNames[i]);
+                continue;
+            }
+
+            TypeBase    = TypeHandler ->Signature;
+            if (!_cmsWriteTypeBase(io, TypeBase))
+                return FALSE;
+
+            if (!TypeHandler ->WritePtr(TypeHandler, io, Data, TagDescriptor ->ElemCount)) {
+
+                char String[5];
 
-       cmsSignalError(LCMS_ERRC_ABORTED, "Seek error; probably corrupted file");
-       return TRUE;
+                _cmsTagSignature2String(String, (cmsTagSignature) TypeBase);
+                cmsSignalError(Icc ->ContextID, cmsERROR_WRITE, "Couldn't write type '%s'", String);
+                return FALSE;
+            }
+        }
+
+
+        Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
+
+        // Align to 32 bit boundary.
+        if (! _cmsWriteAlignment(io))
+            return FALSE;
+    }
+
+
+    return TRUE;
+}
+
+
+// Fill the offset and size fields for all linked tags
+static
+cmsBool SetLinks( _cmsICCPROFILE* Icc)
+{
+    cmsUInt32Number i;
+
+    for (i=0; i < Icc -> TagCount; i++) {
+
+        cmsTagSignature lnk = Icc ->TagLinked[i];
+        if (lnk != (cmsTagSignature) 0) {
+
+            int j = _cmsSearchTag(Icc, lnk, FALSE);
+            if (j >= 0) {
+
+                Icc ->TagOffsets[i] = Icc ->TagOffsets[j];
+                Icc ->TagSizes[i]   = Icc ->TagSizes[j];
+            }
+
+        }
+    }
+
+    return TRUE;
+}
+
+// Low-level save to IOHANDLER. It returns the number of bytes used to
+// store the profile, or zero on error. io may be NULL and in this case
+// no data is written--only sizes are calculated
+cmsUInt32Number CMSEXPORT cmsSaveProfileToIOhandler(cmsHPROFILE hProfile, cmsIOHANDLER* io)
+{
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    _cmsICCPROFILE Keep;
+    cmsIOHANDLER* PrevIO;
+    cmsUInt32Number UsedSpace;
+    cmsContext ContextID;
+
+    memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
+
+    ContextID = cmsGetProfileContextID(hProfile);
+    PrevIO = Icc ->IOhandler = cmsOpenIOhandlerFromNULL(ContextID);
+    if (PrevIO == NULL) return 0;
+
+    // Pass #1 does compute offsets
+
+    if (!_cmsWriteHeader(Icc, 0)) return 0;
+    if (!SaveTags(Icc, &Keep)) return 0;
+
+    UsedSpace = PrevIO ->UsedSpace;
+
+    // Pass #2 does save to iohandler
+
+    if (io != NULL) {
+        Icc ->IOhandler = io;
+        if (!SetLinks(Icc)) goto CleanUp;
+        if (!_cmsWriteHeader(Icc, UsedSpace)) goto CleanUp;
+        if (!SaveTags(Icc, &Keep)) goto CleanUp;
+    }
+
+    memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
+    if (!cmsCloseIOhandler(PrevIO)) return 0;
+
+    return UsedSpace;
+
+
+CleanUp:
+    cmsCloseIOhandler(PrevIO);
+    memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
+    return 0;
+}
+
+
+// Low-level save to disk.
+cmsBool  CMSEXPORT cmsSaveProfileToFile(cmsHPROFILE hProfile, const char* FileName)
+{
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+    cmsIOHANDLER* io = cmsOpenIOhandlerFromFile(ContextID, FileName, "w");
+    cmsBool rc;
+
+    if (io == NULL) return FALSE;
+
+    rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
+    rc &= cmsCloseIOhandler(io);
+
+    if (rc == FALSE) {          // remove() is C99 per 7.19.4.1
+            remove(FileName);   // We have to IGNORE return value in this case
+    }
+    return rc;
+}
+
+// Same as anterior, but for streams
+cmsBool CMSEXPORT cmsSaveProfileToStream(cmsHPROFILE hProfile, FILE* Stream)
+{
+    cmsBool rc;
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+    cmsIOHANDLER* io = cmsOpenIOhandlerFromStream(ContextID, Stream);
+
+    if (io == NULL) return FALSE;
+
+    rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
+    rc &= cmsCloseIOhandler(io);
+
+    return rc;
+}
+
+
+// Same as anterior, but for memory blocks. In this case, a NULL as MemPtr means calculate needed space only
+cmsBool CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUInt32Number* BytesNeeded)
+{
+    cmsBool rc;
+    cmsIOHANDLER* io;
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+
+    // Should we just calculate the needed space?
+    if (MemPtr == NULL) {
+
+           *BytesNeeded =  cmsSaveProfileToIOhandler(hProfile, NULL);
+            return TRUE;
+    }
+
+    // That is a real write operation
+    io =  cmsOpenIOhandlerFromMem(ContextID, MemPtr, *BytesNeeded, "w");
+    if (io == NULL) return FALSE;
+
+    rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
+    rc &= cmsCloseIOhandler(io);
+
+    return rc;
+}
+
+
+
+// Closes a profile freeing any involved resources
+cmsBool  CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
+{
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    cmsBool  rc = TRUE;
+    cmsUInt32Number i;
+
+    if (!Icc) return FALSE;
+
+    // Was open in write mode?
+    if (Icc ->IsWrite) {
+
+        Icc ->IsWrite = FALSE;      // Assure no further writting
+        rc &= cmsSaveProfileToFile(hProfile, Icc ->IOhandler->PhysicalFile);
+    }
+
+    for (i=0; i < Icc -> TagCount; i++) {
+
+        if (Icc -> TagPtrs[i]) {
+
+            cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
+
+            if (TypeHandler != NULL)
+                TypeHandler ->FreePtr(TypeHandler, Icc -> TagPtrs[i]);
+            else
+                _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
+        }
+    }
+
+    if (Icc ->IOhandler != NULL) {
+        rc &= cmsCloseIOhandler(Icc->IOhandler);
+    }
+
+    _cmsFree(Icc ->ContextID, Icc);   // Free placeholder memory
+
+    return rc;
+}
+
+
+// -------------------------------------------------------------------------------------------------------------------
+
+
+// Returns TRUE if a given tag is supported by a plug-in
+static
+cmsBool IsTypeSupported(cmsTagDescriptor* TagDescriptor, cmsTagTypeSignature Type)
+{
+    cmsUInt32Number i, nMaxTypes;
+
+    nMaxTypes = TagDescriptor->nSupportedTypes;
+    if (nMaxTypes >= MAX_TYPES_IN_LCMS_PLUGIN)
+        nMaxTypes = MAX_TYPES_IN_LCMS_PLUGIN;
+
+    for (i=0; i < nMaxTypes; i++) {
+        if (Type == TagDescriptor ->SupportedTypes[i]) return TRUE;
     }
 
     return FALSE;
 }
 
 
-static
-size_t FileTell(struct _lcms_iccprofile_struct* Icc)
-{
-    return ftell((FILE*) Icc ->stream);
-}
-
-// Writes data to stream, also keeps used space for further reference
-
-
-static
-LCMSBOOL FileWrite(struct _lcms_iccprofile_struct* Icc, size_t size, LPVOID Ptr)
+// That's the main read function
+void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
 {
-       if (size == 0) return TRUE;
-
-       Icc->UsedSpace += size;
-
-       if (Icc->stream == NULL) {
-
-              return TRUE;
-       }
-
-       return (fwrite(Ptr, size, 1, (FILE*) Icc->stream) == 1);
-}
-
-
-static
-LCMSBOOL FileGrow(struct _lcms_iccprofile_struct* Icc, size_t size)
-{
-  return TRUE;
-}
-
-
-static
-LCMSBOOL FileClose(struct _lcms_iccprofile_struct* Icc)
-{
-    return fclose((FILE*) Icc ->stream);
-}
-
-// ----------------------------------------------------------------------------------------------------
-
-
-// Creates an empty structure holding all required parameters
-
-cmsHPROFILE _cmsCreateProfilePlaceholder(void)
-{
-
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) _cmsMalloc(sizeof(LCMSICCPROFILE));
-    if (Icc == NULL) return NULL;
-
-    // Empty values
-    ZeroMemory(Icc, sizeof(LCMSICCPROFILE));
-
-    // Make sure illuminant is correct
-    Icc ->Illuminant = *cmsD50_XYZ();
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    cmsIOHANDLER* io = Icc ->IOhandler;
+    cmsTagTypeHandler* TypeHandler;
+    cmsTagDescriptor*  TagDescriptor;
+    cmsTagTypeSignature BaseType;
+    cmsUInt32Number Offset, TagSize;
+    cmsUInt32Number ElemCount;
+    int n;
 
-    // Set it to empty
-    Icc -> TagCount   = 0;
-
-    // Return the handle
-    return (cmsHPROFILE) Icc;
-}
-
-
-// Return the number of tags
-icInt32Number LCMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
-    return  Icc->TagCount;
-}
-
-// Return the tag signature of a given tag number
-icTagSignature LCMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, icInt32Number n)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) hProfile;
-
-    if (n < 0 || n > Icc->TagCount) return (icTagSignature) 0;  // Mark as not available
-
-    return Icc ->TagNames[n];
-}
-
-
-// Search for a specific tag in tag dictionary
-// Returns position or -1 if tag not found
-
-icInt32Number _cmsSearchTag(LPLCMSICCPROFILE Profile, icTagSignature sig, LCMSBOOL lSignalError)
-{
-       icInt32Number i;
-
-       if (sig == 0) return -1;     // 0 identifies a special tag holding raw memory.
-
-       for (i=0; i < Profile -> TagCount; i++) {
-
-              if (sig == Profile -> TagNames[i])
-                            return i;
-       }
-
-       if (lSignalError)
-            cmsSignalError(LCMS_ERRC_ABORTED, "Tag '%lx' not found", sig);
-
-       return -1;
-}
-
-
-// Check existance
-
-LCMSBOOL LCMSEXPORT cmsIsTag(cmsHPROFILE hProfile, icTagSignature sig)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-       return _cmsSearchTag(Icc, sig, FALSE) >= 0;
-}
+    n = _cmsSearchTag(Icc, sig, TRUE);
+    if (n < 0) return NULL;                 // Not found, return NULL
 
 
 
-// Search for a particular tag, replace if found or add new one else
+    // If the element is already in memory, return the pointer
+    if (Icc -> TagPtrs[n]) {
+
+        if (Icc ->TagSaveAsRaw[n]) return NULL;  // We don't support read raw tags as cooked
+        return Icc -> TagPtrs[n];
+    }
+
+    // We need to read it. Get the offset and size to the file
+    Offset    = Icc -> TagOffsets[n];
+    TagSize   = Icc -> TagSizes[n];
 
-LPVOID _cmsInitTag(LPLCMSICCPROFILE Icc, icTagSignature sig, size_t size, const void* Init)
-{
-    LPVOID Ptr;
-    icInt32Number i;
+    // Seek to its location
+    if (!io -> Seek(io, Offset))
+            return NULL;
+
+    // Search for support on this tag
+    TagDescriptor = _cmsGetTagDescriptor(sig);
+    if (TagDescriptor == NULL) return NULL;     // Unsupported.
 
-    i = _cmsSearchTag(Icc, sig, FALSE);
+    // if supported, get type and check if in list
+    BaseType = _cmsReadTypeBase(io);
+    if (BaseType == 0) return NULL;
 
-    if (i >=0) {
+    if (!IsTypeSupported(TagDescriptor, BaseType)) return NULL;
+
+    TagSize  -= 8;                      // Alredy read by the type base logic
 
-        if (Icc -> TagPtrs[i]) _cmsFree(Icc -> TagPtrs[i]);
-    }
-    else  {
+    // Get type handler
+    TypeHandler = _cmsGetTagTypeHandler(BaseType);
+    if (TypeHandler == NULL) return NULL;
+
 
-        i = Icc -> TagCount;
-        Icc -> TagCount++;
+    // Read the tag
+    Icc -> TagTypeHandlers[n] = TypeHandler;
+    Icc -> TagPtrs[n] = TypeHandler ->ReadPtr(TypeHandler, io, &ElemCount, TagSize);
+
+    // The tag type is supported, but something wrong happend and we cannot read the tag.
+    // let know the user about this (although it is just a warning)
+    if (Icc -> TagPtrs[n] == NULL) {
+
+        char String[5];
 
-        if (Icc ->TagCount >= MAX_TABLE_TAG) {
+        _cmsTagSignature2String(String, sig);
+        cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Corrupted tag '%s'", String);
+        return NULL;
+    }
 
-            cmsSignalError(LCMS_ERRC_ABORTED, "Too many tags (%d)", MAX_TABLE_TAG);
-            Icc ->TagCount = MAX_TABLE_TAG-1;
-            return NULL;
-        }
+    // This is a weird error that may be a symptom of something more serious, the number of
+    // stored item is actually less than the number of required elements.
+    if (ElemCount < TagDescriptor ->ElemCount) {
+
+        char String[5];
+
+        _cmsTagSignature2String(String, sig);
+        cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "'%s' Inconsistent number of items: expected %d, got %d",
+                                                             String, TagDescriptor ->ElemCount, ElemCount);
     }
 
 
-    Ptr = _cmsMalloc(size);
-    if (Ptr == NULL) return NULL;
-
-    CopyMemory(Ptr, Init, size);
-
-    Icc ->TagNames[i] = sig;
-    Icc ->TagSizes[i] = size;
-    Icc ->TagPtrs[i]  = Ptr;
-
-    return Ptr;
+    // Return the data
+    return Icc -> TagPtrs[n];
 }
 
 
-
-
-
-// Creates a profile from file read placeholder
-
-LPLCMSICCPROFILE _cmsCreateProfileFromFilePlaceholder(const char* FileName)
+// Get true type of data
+cmsTagTypeSignature _cmsGetTagTrueType(cmsHPROFILE hProfile, cmsTagSignature sig)
 {
-    LPLCMSICCPROFILE NewIcc;
-    LPVOID ICCfile = FileOpen(FileName);
-
-    if (ICCfile == NULL) {
-
-              cmsSignalError(LCMS_ERRC_ABORTED, "File '%s' not found", FileName);
-              return NULL;
-    }
-
-    NewIcc = (LPLCMSICCPROFILE) _cmsCreateProfilePlaceholder();
-    if (NewIcc == NULL) return NULL;
-
-    strncpy(NewIcc -> PhysicalFile, FileName, MAX_PATH-1);
-    NewIcc -> PhysicalFile[MAX_PATH-1] = 0;
-
-    NewIcc ->stream = ICCfile;
-
-    NewIcc ->Read  = FileRead;
-    NewIcc ->Seek  = FileSeek;
-    NewIcc ->Tell  = FileTell;
-    NewIcc ->Close = FileClose;
-    NewIcc ->Grow  = FileGrow;
-    NewIcc ->Write = NULL;
-
-    NewIcc ->IsWrite = FALSE;
-
-
-
-
-    return NewIcc;
-}
-
-
-// Creates a profile from memory read placeholder
-
-LPLCMSICCPROFILE _cmsCreateProfileFromMemPlaceholder(LPVOID MemPtr, DWORD dwSize)
-{
-
-    LPLCMSICCPROFILE NewIcc;
-    LPVOID ICCfile = MemoryOpen((LPBYTE) MemPtr, (size_t) dwSize, 'r');
-
-
-    if (ICCfile == NULL) {
-
-        cmsSignalError(LCMS_ERRC_ABORTED, "Couldn't allocate %ld bytes for profile", dwSize);
-        return NULL;
-    }
-
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    cmsTagTypeHandler* TypeHandler;
+    int n;
 
-    NewIcc = (LPLCMSICCPROFILE) _cmsCreateProfilePlaceholder();
-    if (NewIcc == NULL) return NULL;
-
-    NewIcc -> PhysicalFile[0] = 0;
-    NewIcc ->stream = ICCfile;
-
-    NewIcc ->Read  = MemoryRead;
-    NewIcc ->Seek  = MemorySeek;
-    NewIcc ->Tell  = MemoryTell;
-    NewIcc ->Close = MemoryClose;
-    NewIcc ->Grow  = MemoryGrow;
-    NewIcc ->Write = MemoryWrite;
-
-    NewIcc ->IsWrite = FALSE;
-
-
-    return NewIcc;
-}
-
-
-// Turn a placeholder into file writter
-
-void _cmsSetSaveToDisk(LPLCMSICCPROFILE Icc, const char* FileName)
-{
-
-    if (FileName == NULL) {
+    // Search for given tag in ICC profile directory
+    n = _cmsSearchTag(Icc, sig, TRUE);
+    if (n < 0) return (cmsTagTypeSignature) 0;                // Not found, return NULL
 
-          Icc ->stream = NULL;
-    }
-    else {
-
-          Icc ->stream = fopen(FileName, "wb");
-          if (Icc ->stream == NULL)
-                cmsSignalError(LCMS_ERRC_ABORTED, "Couldn't write to file '%s'", FileName);
-    }
-
-    Icc ->Write = FileWrite;   // Save to disk
-    Icc ->Close = FileClose;
-}
-
-
-
-// Turn a  placeholder into memory writter
-
-void _cmsSetSaveToMemory(LPLCMSICCPROFILE Icc, LPVOID MemPtr, size_t dwSize)
-{
-
-    if (MemPtr == NULL) {
-
-        Icc ->stream = NULL;
-    }
-    else {
-
-        Icc ->stream = (FILEMEM*) MemoryOpen((LPBYTE) MemPtr, dwSize, 'w');
-        if (Icc ->stream == NULL)
-                cmsSignalError(LCMS_ERRC_ABORTED, "Couldn't write to memory");
-    }
-
-    Icc ->Write = MemoryWrite;
-    Icc ->Close = MemoryClose;
+    // Get the handler. The true type is there
+    TypeHandler =  Icc -> TagTypeHandlers[n];
+    return TypeHandler ->Signature;
 }
 
 
-// ----------------------------------------------------------------------- Set/Get several struct members
-
-
-
-
-LCMSBOOL LCMSEXPORT cmsTakeMediaWhitePoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
-{
-     LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) hProfile;
-     *Dest = Icc -> MediaWhitePoint;
-     return TRUE;
-}
-
-
-LCMSBOOL LCMSEXPORT cmsTakeMediaBlackPoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
+// Write a single tag. This just keeps track of the tak into a list of "to be written". If the tag is already
+// in that list, the previous version is deleted.
+cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data)
 {
-      LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) hProfile;
-      *Dest = Icc -> MediaBlackPoint;
-      return TRUE;
-}
-
-LCMSBOOL  LCMSEXPORT cmsTakeIluminant(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       *Dest = Icc -> Illuminant;
-       return TRUE;
-}
-
-int LCMSEXPORT cmsTakeRenderingIntent(cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       return (int) Icc -> RenderingIntent;
-}
-
-void LCMSEXPORT cmsSetRenderingIntent(cmsHPROFILE hProfile, int RenderingIntent)
-{
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-    Icc -> RenderingIntent = (icRenderingIntent) RenderingIntent;
-}
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    cmsTagTypeHandler* TypeHandler = NULL;
+    cmsTagDescriptor* TagDescriptor = NULL;
+    cmsTagTypeSignature Type;
+    int i;
+    cmsFloat64Number Version;
 
 
-DWORD LCMSEXPORT cmsTakeHeaderFlags(cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       return (DWORD) Icc -> flags;
-}
+    if (data == NULL) {
 
-void LCMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, DWORD Flags)
-{
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-    Icc -> flags = (icUInt32Number) Flags;
-}
+         cmsSignalError(cmsGetProfileContextID(hProfile), cmsERROR_NULL, "couldn't wite NULL to tag");
+         return FALSE;
+    }
+
+    i = _cmsSearchTag(Icc, sig, FALSE);
+    if (i >=0) {
+
+        if (Icc -> TagPtrs[i] != NULL) {
 
-DWORD LCMSEXPORT cmsTakeHeaderAttributes(cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       return (DWORD) Icc -> attributes;
-}
+            // Already exists. Free previous version
+            if (Icc ->TagSaveAsRaw[i]) {
+                _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
+            }
+            else {
+                TypeHandler = Icc ->TagTypeHandlers[i];
+                TypeHandler->FreePtr(TypeHandler, Icc -> TagPtrs[i]);
+            }
+        }
+    }
+    else  {
+        // New one
+        i = Icc -> TagCount;
 
-void LCMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, DWORD Flags)
-{
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-    Icc -> attributes = (icUInt32Number) Flags;
-}
+        if (i >= MAX_TABLE_TAG) {
+            cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
+            return FALSE;
+        }
+
+        Icc -> TagCount++;
+    }
+
+    // This is not raw
+    Icc ->TagSaveAsRaw[i] = FALSE;
+
+    // This is not a link
+    Icc ->TagLinked[i] = (cmsTagSignature) 0;
+
+    // Get information about the TAG.
+    TagDescriptor = _cmsGetTagDescriptor(sig);
+    if (TagDescriptor == NULL){
+         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag '%x'", sig);
+        return FALSE;
+    }
 
 
-const BYTE* LCMSEXPORT cmsTakeProfileID(cmsHPROFILE hProfile)
-{
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-    return Icc ->ProfileID;
-}
+    // Now we need to know which type to use. It depends on the version.
+    Version = cmsGetProfileVersion(hProfile);
+    if (TagDescriptor ->DecideType != NULL) {
+
+        // Let the tag descriptor to decide the type base on depending on
+        // the data. This is useful for example on parametric curves, where
+        // curves specified by a table cannot be saved as parametric and needs
+        // to be revented to single v2-curves, even on v4 profiles.
+
+        Type = TagDescriptor ->DecideType(Version, data);
+    }
+    else {
+
+        Type = TagDescriptor ->SupportedTypes[0];
+    }
+
+    // Does the tag support this type?
+    if (!IsTypeSupported(TagDescriptor, Type)) {
+        cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%x' for tag '%x'", Type, sig);
+        return FALSE;
+    }
 
-void LCMSEXPORT cmsSetProfileID(cmsHPROFILE hProfile, LPBYTE ProfileID)
-{
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-    CopyMemory(Icc -> ProfileID, ProfileID, 16);
-}
+    // Does we have a handler for this type?
+    TypeHandler =  _cmsGetTagTypeHandler(Type);
+    if (TypeHandler == NULL) {
+        cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%x' for tag '%x'", Type, sig);
+        return FALSE;           // Should never happen
+    }
 
+    // Fill fields on icc structure
+    Icc ->TagTypeHandlers[i]  = TypeHandler;
+    Icc ->TagNames[i]         = sig;
+    Icc ->TagSizes[i]         = 0;
+    Icc ->TagOffsets[i]       = 0;
+    Icc ->TagPtrs[i]          = TypeHandler ->DupPtr(TypeHandler, data, TagDescriptor ->ElemCount);
 
-LCMSBOOL LCMSEXPORT cmsTakeCreationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
-{
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    CopyMemory(Dest, &Icc ->Created, sizeof(struct tm));
+    if (Icc ->TagPtrs[i] == NULL)  {
+
+        TypeHandler ->DupPtr(TypeHandler, data, TagDescriptor ->ElemCount);
+        cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Malformed struct in type '%x' for tag '%x'", Type, sig);
+
+        return FALSE;
+    }
+
     return TRUE;
 }
 
-
-icColorSpaceSignature LCMSEXPORT cmsGetPCS(cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       return Icc -> PCS;
-}
-
-
-void LCMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, icColorSpaceSignature pcs)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       Icc -> PCS = pcs;
-}
+// Read and write raw data. The only way those function would work and keep consistence with normal read and write
+// is to do an additional step of serialization. That means, readRaw would issue a normal read and then convert the obtained
+// data to raw bytes by using the "write" serialization logic. And vice-versa. I know this may end in situations where
+// raw data written does not exactly correspond with the raw data proposed to cmsWriteRaw data, but this approach allows
+// to write a tag as raw data and the read it as handled.
 
-icColorSpaceSignature LCMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       return Icc -> ColorSpace;
-}
-
-void LCMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, icColorSpaceSignature sig)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       Icc -> ColorSpace = sig;
-}
-
-icProfileClassSignature LCMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
+cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, void* data, cmsUInt32Number BufferSize)
 {
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       return Icc -> DeviceClass;
-}
-
-DWORD LCMSEXPORT cmsGetProfileICCversion(cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       return (DWORD) Icc -> Version;
-}
-
-void LCMSEXPORT cmsSetProfileICCversion(cmsHPROFILE hProfile, DWORD Version)
-{
-   LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-   Icc -> Version = Version;
-}
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    void *Object;
+    int i;
+    cmsIOHANDLER* MemIO;
+    cmsTagTypeHandler* TypeHandler = NULL;
+    cmsTagDescriptor* TagDescriptor = NULL;
+    cmsUInt32Number rc;
+    cmsUInt32Number Offset, TagSize;
 
-
-void LCMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, icProfileClassSignature sig)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
-       Icc -> DeviceClass = sig;
-}
-
+    // Search for given tag in ICC profile directory
+    i = _cmsSearchTag(Icc, sig, TRUE);
+    if (i < 0) return 0;                 // Not found, return 0
 
-// --------------------------------------------------------------------------------------------------------------
-
+    // It is already read?
+    if (Icc -> TagPtrs[i] == NULL) {
 
-static
-int SizeOfGammaTab(LPGAMMATABLE In)
-{
-       return sizeof(GAMMATABLE) + (In -> nEntries - 1)*sizeof(WORD);
-}
+        // No yet, get original position
+        Offset   = Icc ->TagOffsets[i];
+        TagSize  = Icc ->TagSizes[i];
 
 
-// Creates a phantom tag holding a memory block
+        // read the data directly, don't keep copy
+        if (data != NULL) {
+
+            if (BufferSize < TagSize)
+                 TagSize = BufferSize;
+
+            if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) return 0;
+            if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) return 0;
+        }
+
+        return Icc ->TagSizes[i];
+    }
+
+    // The data has been already read, or written. But wait!, maybe the user choosed to save as
+    // raw data. In this case, return the raw data directly
+    if (Icc ->TagSaveAsRaw[i]) {
+
+        if (data != NULL)  {
+
+            TagSize  = Icc ->TagSizes[i];
+            if (BufferSize < TagSize)
+                       TagSize = BufferSize;
+
+            memmove(data, Icc ->TagPtrs[i], TagSize);
+        }
 
-static
-LPVOID DupBlock(LPLCMSICCPROFILE Icc, LPVOID Block, size_t size)
-{
-    if (Block != NULL && size > 0)
-        return _cmsInitTag(Icc, (icTagSignature) 0, size, Block);
-    else
-        return NULL;
+        return Icc ->TagSizes[i];
+    }
+
+    // Already readed, or previously set by cmsWriteTag(). We need to serialize that
+    // data to raw in order to maintain consistency.
+    Object = cmsReadTag(hProfile, sig);
+    if (Object == NULL) return 0;
+
+    // Now we need to serialize to a memory block: just use a memory iohandler
 
+    if (data == NULL) {
+        MemIO = cmsOpenIOhandlerFromNULL(cmsGetProfileContextID(hProfile));
+    } else{
+          MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
+    }
+    if (MemIO == NULL) return 0;
+
+    // Obtain type handling for the tag
+    TypeHandler = Icc ->TagTypeHandlers[i];
+    TagDescriptor = _cmsGetTagDescriptor(sig);
+
+    // Serialize
+    if (!TypeHandler ->WritePtr(TypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) return 0;
+
+    // Get Size and close
+    rc = MemIO ->Tell(MemIO);
+    cmsCloseIOhandler(MemIO);      // Ignore return code this time
+
+    return rc;
 }
 
-// This is tricky, since LUT structs does have pointers
-
-LCMSBOOL LCMSEXPORT _cmsAddLUTTag(cmsHPROFILE hProfile, icTagSignature sig, const void* lut)
+// Similar to the anterior. This function allows to write directly to the ICC profile any data, without
+// checking anything. As a rule, mixing Raw with cooked doesn't work, so writting a tag as raw and then reading
+// it as cooked without serializing does result into an error. If that is wha you want, you will need to dump
+// the profile to memry or disk and then reopen it.
+cmsBool CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data, cmsUInt32Number Size)
 {
-       LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-       LPLUT Orig, Stored;
-       unsigned int i;
-
-       // The struct itself
-
-       Orig   = (LPLUT) lut;
-       Stored = (LPLUT) _cmsInitTag(Icc, (icTagSignature) sig, sizeof(LUT), lut);
-
-       // dup' the memory blocks
-       for (i=0; i < Orig ->InputChan; i++)
-            Stored -> L1[i] = (LPWORD) DupBlock(Icc, (LPWORD) Orig ->L1[i],
-                                            sizeof(WORD) * Orig ->In16params.nSamples);
-
-       for (i=0; i < Orig ->OutputChan; i++)
-            Stored -> L2[i] = (LPWORD) DupBlock(Icc, (LPWORD) Orig ->L2[i],
-                                            sizeof(WORD) * Orig ->Out16params.nSamples);
-
-       Stored -> T     = (LPWORD) DupBlock(Icc, (LPWORD) Orig ->T, Orig -> Tsize);
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    int i;
 
-       // Zero any additional pointer
-       Stored ->CLut16params.p8 = NULL;
-       return TRUE;
-}
-
-
-LCMSBOOL LCMSEXPORT _cmsAddXYZTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* XYZ)
-{
-       LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-       _cmsInitTag(Icc, sig, sizeof(cmsCIEXYZ), XYZ);
-       return TRUE;
-}
+    if (!_cmsNewTag(Icc, sig, &i)) return FALSE;
 
-
-LCMSBOOL LCMSEXPORT _cmsAddTextTag(cmsHPROFILE hProfile, icTagSignature sig, const char* Text)
-{
-       LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
+    // Mark the tag as being written as RAW
+    Icc ->TagSaveAsRaw[i] = TRUE;
+    Icc ->TagNames[i]     = sig;
+    Icc ->TagLinked[i]    = (cmsTagSignature) 0;
 
-       _cmsInitTag(Icc, sig, strlen(Text)+1, (LPVOID) Text);
-       return TRUE;
-}
+    // Keep a copy of the block
+    Icc ->TagPtrs[i]  = _cmsDupMem(Icc ->ContextID, data, Size);
+    Icc ->TagSizes[i] = Size;
 
-LCMSBOOL LCMSEXPORT _cmsAddGammaTag(cmsHPROFILE hProfile, icTagSignature sig, LPGAMMATABLE TransferFunction)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-    _cmsInitTag(Icc, sig, SizeOfGammaTab(TransferFunction), TransferFunction);
     return TRUE;
 }
 
-
-LCMSBOOL LCMSEXPORT _cmsAddChromaticityTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIExyYTRIPLE Chrm)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-    _cmsInitTag(Icc, sig, sizeof(cmsCIExyYTRIPLE), Chrm);
-    return TRUE;
-}
-
-
-LCMSBOOL LCMSEXPORT _cmsAddSequenceDescriptionTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsSEQ pseq)
+// Using this function you can collapse several tag entries to the same block in the profile
+cmsBool CMSEXPORT cmsLinkTag(cmsHPROFILE hProfile, cmsTagSignature sig, cmsTagSignature dest)
 {
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
+     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    int i;
 
-    _cmsInitTag(Icc, sig, sizeof(int) + pseq -> n * sizeof(cmsPSEQDESC), pseq);
-    return TRUE;
-
-}
+    if (!_cmsNewTag(Icc, sig, &i)) return FALSE;
 
+    // Keep necessary information
+    Icc ->TagSaveAsRaw[i] = FALSE;
+    Icc ->TagNames[i]     = sig;
+    Icc ->TagLinked[i]    = dest;
 
-LCMSBOOL LCMSEXPORT _cmsAddNamedColorTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
+    Icc ->TagPtrs[i]    = NULL;
+    Icc ->TagSizes[i]   = 0;
+    Icc ->TagOffsets[i] = 0;
 
-    _cmsInitTag(Icc, sig, sizeof(cmsNAMEDCOLORLIST) + (nc ->nColors - 1) * sizeof(cmsNAMEDCOLOR), nc);
     return TRUE;
 }
-
-
-LCMSBOOL LCMSEXPORT _cmsAddDateTimeTag(cmsHPROFILE hProfile, icTagSignature sig, struct tm *DateTime)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-    _cmsInitTag(Icc, sig, sizeof(struct tm), DateTime);
-    return TRUE;
-}
-
-
-LCMSBOOL LCMSEXPORT _cmsAddColorantTableTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-    _cmsInitTag(Icc, sig, sizeof(cmsNAMEDCOLORLIST) + (nc ->nColors - 1) * sizeof(cmsNAMEDCOLOR), nc);
-    return TRUE;
-}
-
-
-LCMSBOOL LCMSEXPORT _cmsAddChromaticAdaptationTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* mat)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-    _cmsInitTag(Icc, sig, 3*sizeof(cmsCIEXYZ), mat);
-    return TRUE;
-
-}
-
-
--- a/src/share/native/sun/java2d/cmm/lcms/cmsio1.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsio1.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,1860 +49,108 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// ICC profile serialization
-
-
-#include "lcms.h"
-
-// ----------------------------------------------------------------- Tag Serialization
-
-// Alignment of ICC file format uses 4 bytes DWORD
-
-#define ALIGNLONG(x) (((x)+3) & ~(3))         // Aligns to DWORD boundary
-
-
-static int GlobalLanguageCode;   // Language & country descriptors, for ICC 4.0 support
-static int GlobalCountryCode;
-
-
-#ifdef __BEOS__
-#       define USE_CUSTOM_SWAB  1
-#endif
-
-
-#ifdef USE_CUSTOM_SWAB
-
-// Replacement to swab function, thanks to YNOP
-// for providing the BeOS port
 //
-// from: @(#)swab.c       5.10 (Berkeley)  3/6/91
-
-static
-void xswab(const void *from, void *to, size_t len)
-{
-         register unsigned long temp;
-         register int n;
-         register char *fp, *tp;
-
-         n = (len >> 1) + 1;
-         fp = (char *)from;
-         tp = (char *)to;
-#define STEP    temp = *fp++,*tp++ = *fp++,*tp++ = temp
-         /* round to multiple of 8 */
-         while ((--n) & 07)
-                 STEP;
-         n >>= 3;
-         while (--n >= 0) {
-
-                 STEP; STEP; STEP; STEP;
-                 STEP; STEP; STEP; STEP;
-         }
-#undef STEP
-}
-#else
-#define xswab swab
-#endif
-
-
-//
-//      Little-Endian to Big-Endian
+//---------------------------------------------------------------------------------
 //
 
-#ifdef USE_BIG_ENDIAN
-#define AdjustEndianess16(a)
-#define AdjustEndianess32(a)
-#define AdjustEndianessArray16(a, b)
-#else
-
-static
-void AdjustEndianess16(LPBYTE pByte)
-{
-       BYTE tmp;
-
-       tmp = pByte[0];
-       pByte[0] = pByte[1];
-       pByte[1] = tmp;
-}
-
-static
-void AdjustEndianess32(LPBYTE pByte)
-{
-        BYTE temp1;
-        BYTE temp2;
-
-        temp1 = *pByte++;
-        temp2 = *pByte++;
-        *(pByte-1) = *pByte;
-        *pByte++ = temp2;
-        *(pByte-3) = *pByte;
-        *pByte = temp1;
-}
-
-
-// swap bytes in a array of words
-
-static
-void AdjustEndianessArray16(LPWORD p, size_t num_words)
-{
-       xswab((char*) p, (char*)p, (int) num_words * sizeof(WORD));
-}
-
-#endif
-
-
-// Transports to properly encoded values - note that icc profiles does use
-// big endian notation.
-
-static
-icInt32Number TransportValue32(icInt32Number Value)
-{
-       icInt32Number Temp = Value;
+#include "lcms2_internal.h"
 
-       AdjustEndianess32((LPBYTE) &Temp);
-       return Temp;
-}
-
-static
-WORD TransportValue16(WORD Value)
-{
-       WORD Temp = Value;
-
-       AdjustEndianess16((LPBYTE) &Temp);
-       return Temp;
-}
-
-
-// from Fixed point 8.8 to double
-
-static
-double Convert8Fixed8(WORD fixed8)
-{
-       BYTE msb, lsb;
-
-       lsb = (BYTE) (fixed8 & 0xff);
-       msb = (BYTE) (((WORD) fixed8 >> 8) & 0xff);
-
-       return (double) ((double) msb + ((double) lsb / 256.0));
-}
-
-
-// from Fixed point 15.16 to double
-static
-double Convert15Fixed16(icS15Fixed16Number fix32)
-{
-    double floater, sign, mid, hack;
-    int Whole, FracPart;
-
-
-    AdjustEndianess32((LPBYTE) &fix32);
-
-    sign  = (fix32 < 0 ? -1 : 1);
-    fix32 = abs(fix32);
-
-    Whole = LOWORD(fix32 >> 16);
-    FracPart  = LOWORD(fix32 & 0x0000ffffL);
-
-    hack    = 65536.0;
-    mid     = (double) FracPart / hack;
-    floater = (double) Whole + mid;
-
-    return sign * floater;
-}
-
-
-// Auxiliar-- read base and return type
+// Read tags using low-level functions, provides necessary glue code to adapt versions, etc.
 
-static
-icTagTypeSignature ReadBase(LPLCMSICCPROFILE Icc)
-{
-    icTagBase Base;
-
-    if (Icc -> Read(&Base, sizeof(icTagBase), 1, Icc) != 1)
-                return (icTagTypeSignature) 0;
-    AdjustEndianess32((LPBYTE) &Base.sig);
-
-    return Base.sig;
-}
-
-
-static
-void DecodeDateTimeNumber(const icDateTimeNumber *Source, struct tm *Dest)
-{
-    Dest->tm_sec   = TransportValue16(Source->seconds);
-    Dest->tm_min   = TransportValue16(Source->minutes);
-    Dest->tm_hour  = TransportValue16(Source->hours);
-    Dest->tm_mday  = TransportValue16(Source->day);
-    Dest->tm_mon   = TransportValue16(Source->month) - 1;
-    Dest->tm_year  = TransportValue16(Source->year) - 1900;
-    Dest->tm_wday  = -1;
-    Dest->tm_yday  = -1;
-    Dest->tm_isdst = 0;
-}
-
-static
-void EncodeDateTimeNumber(icDateTimeNumber *Dest, const struct tm *Source)
-{
-    Dest->seconds = TransportValue16((WORD) Source->tm_sec);
-    Dest->minutes = TransportValue16((WORD) Source->tm_min);
-    Dest->hours   = TransportValue16((WORD) Source->tm_hour);
-    Dest->day     = TransportValue16((WORD) Source->tm_mday);
-    Dest->month   = TransportValue16((WORD) (Source->tm_mon + 1));
-    Dest->year    = TransportValue16((WORD) (Source->tm_year + 1900));
-}
-
-
-// Jun-21-2000: Some profiles (those that comes with W2K) comes
-// with the media white (media black?) x 100. Add a sanity check
-
-static
-void NormalizeXYZ(LPcmsCIEXYZ Dest)
-{
-    while (Dest -> X > 2. &&
-           Dest -> Y > 2. &&
-           Dest -> Z > 2.) {
-
-               Dest -> X /= 10.;
-               Dest -> Y /= 10.;
-               Dest -> Z /= 10.;
-       }
-}
-
-// Evaluates a XYZ tristimulous across chromatic adaptation matrix
-
-static
-void EvalCHRM(LPcmsCIEXYZ Dest, LPMAT3 Chrm, LPcmsCIEXYZ Src)
-{
-    VEC3 d, s;
-
-    s.n[VX] = Src -> X;
-    s.n[VY] = Src -> Y;
-    s.n[VZ] = Src -> Z;
-
-    MAT3eval(&d, Chrm, &s);
-
-    Dest ->X = d.n[VX];
-    Dest ->Y = d.n[VY];
-    Dest ->Z = d.n[VZ];
-
-}
-
-
-// Read profile header and validate it
-
-static
-LPLCMSICCPROFILE ReadHeader(LPLCMSICCPROFILE Icc, LCMSBOOL lIsFromMemory)
-{
-     icTag Tag;
-     icHeader Header;
-     icInt32Number TagCount, i;
-     icUInt32Number extent;
-
-       if (Icc -> Read(&Header, sizeof(icHeader), 1, Icc) != 1)
-                      goto ErrorCleanup;
-
-       // Convert endian
-
-       AdjustEndianess32((LPBYTE) &Header.size);
-       AdjustEndianess32((LPBYTE) &Header.cmmId);
-       AdjustEndianess32((LPBYTE) &Header.version);
-       AdjustEndianess32((LPBYTE) &Header.deviceClass);
-       AdjustEndianess32((LPBYTE) &Header.colorSpace);
-       AdjustEndianess32((LPBYTE) &Header.pcs);
-       AdjustEndianess32((LPBYTE) &Header.magic);
-       AdjustEndianess32((LPBYTE) &Header.flags);
-       AdjustEndianess32((LPBYTE) &Header.attributes[0]);
-       AdjustEndianess32((LPBYTE) &Header.renderingIntent);
-
-       // Validate it
-
-       if (Header.magic != icMagicNumber) goto ErrorCleanup;
-
-       if (Icc ->Read(&TagCount, sizeof(icInt32Number), 1, Icc) != 1)
-                     goto ErrorCleanup;
-
-       AdjustEndianess32((LPBYTE) &TagCount);
+// LUT tags
+static const cmsTagSignature Device2PCS16[]   =  {cmsSigAToB0Tag,     // Perceptual
+                                                  cmsSigAToB1Tag,     // Relative colorimetric
+                                                  cmsSigAToB2Tag,     // Saturation
+                                                  cmsSigAToB1Tag };   // Absolute colorimetric
 
-       Icc -> DeviceClass     = Header.deviceClass;
-       Icc -> ColorSpace      = Header.colorSpace;
-       Icc -> PCS             = Header.pcs;
-       Icc -> RenderingIntent = (icRenderingIntent) Header.renderingIntent;
-       Icc -> flags           = Header.flags;
-       Icc -> attributes      = Header.attributes[0];
-       Icc -> Illuminant.X    = Convert15Fixed16(Header.illuminant.X);
-       Icc -> Illuminant.Y    = Convert15Fixed16(Header.illuminant.Y);
-       Icc -> Illuminant.Z    = Convert15Fixed16(Header.illuminant.Z);
-       Icc -> Version         = Header.version;
-
-       // Get creation date/time
-
-       DecodeDateTimeNumber(&Header.date, &Icc ->Created);
-
-       // Fix illuminant, some profiles are broken in this field!
-
-       Icc ->Illuminant = *cmsD50_XYZ();
-
-       // The profile ID are 16 raw bytes
-
-       CopyMemory(Icc ->ProfileID, Header.reserved, 16);
-
-       // Get rid of possible wrong profiles
-
-       NormalizeXYZ(&Icc  -> Illuminant);
-
-       // Read tag directory
-
-       if (TagCount > MAX_TABLE_TAG || TagCount < 0) {
-
-           cmsSignalError(LCMS_ERRC_ABORTED, "Too many tags (%d)", TagCount);
-           goto ErrorCleanup;
-       }
-
-       Icc -> TagCount = TagCount;
-       for (i=0; i < TagCount; i++) {
-
-              if (Icc ->Read(&Tag, sizeof(icTag), 1, Icc) != 1)
-                  goto ErrorCleanup;
-
-              AdjustEndianess32((LPBYTE) &Tag.offset);
-              AdjustEndianess32((LPBYTE) &Tag.size);
-              AdjustEndianess32((LPBYTE) &Tag.sig);            // Signature
-
-              // Perform some sanity check. Offset + size should fall inside file.
-              extent = Tag.offset + Tag.size;
-              if (extent > Header.size || extent < Tag.offset)
-                  goto ErrorCleanup;
-
-              Icc -> TagNames[i]   = Tag.sig;
-              Icc -> TagOffsets[i] = Tag.offset;
-              Icc -> TagSizes[i]   = Tag.size;
-       }
-
-       return Icc;
-
-
-ErrorCleanup:
-
-       Icc ->Close(Icc);
-
-       if (lIsFromMemory)
-             cmsSignalError(LCMS_ERRC_ABORTED, "Corrupted memory profile");
-       else
-             cmsSignalError(LCMS_ERRC_ABORTED, "Corrupted profile: '%s'", Icc->PhysicalFile);
-
-
-        _cmsFree(Icc);
-       return NULL;
-}
-
-static
-unsigned int uipow(unsigned int a, unsigned int b) {
-        unsigned int rv = 1;
-        for (; b > 0; b--)
-                rv *= a;
-        return rv;
-}
-
-
-
-// Convert between notations.
-
-#define TO16_TAB(x)      (WORD) (((x) << 8) | (x))
-
-
-// LUT8 can come only in Lab space. There is a fatal flaw in
-// converting from Lut8 to Lut16. Due to particular encoding
-// of Lab, different actions should be taken from input and
-// output Lab8 LUTS. For input, is as easy as applying a << 8,
-// since numbers comes in fixed point. However, for output LUT
-// things goes a bit more complex.... LUT 16 is supposed to
-// have a domain of 0..ff00, so we should remap the LUT in order
-// to get things working. Affected signatures are B2Axx tags,
-// preview and gamut.
-
-// I do solve it by multiplying input matrix by:
-//
-//  | 0xffff/0xff00   0                0              |
-//  |       0         0xffff/0xff00    0              |
-//  |       0         0                0xffff/0xff00  |
-//
-// The input values got then remapped to adequate domain
-
-static
-void FixLUT8(LPLUT Lut, icTagSignature sig, size_t nTabSize)
-{
-    MAT3 Fixup, Original, Result;
-    LPWORD PtrW;
-    size_t i;
-
-    switch (sig) {
-
+static const cmsTagSignature Device2PCSFloat[] = {cmsSigDToB0Tag,     // Perceptual
+                                                  cmsSigDToB1Tag,     // Relative colorimetric
+                                                  cmsSigDToB2Tag,     // Saturation
+                                                  cmsSigDToB3Tag };   // Absolute colorimetric
 
-       case icSigBToA0Tag:
-       case icSigBToA1Tag:
-       case icSigBToA2Tag:
-       case icSigGamutTag:
-       case icSigPreview0Tag:
-       case icSigPreview1Tag:
-       case icSigPreview2Tag:
-
-
-                VEC3init(&Fixup.v[0], (double) 0xFFFF/0xFF00, 0, 0);
-                VEC3init(&Fixup.v[1], 0, (double) 0xFFFF/0xFF00, 0);
-                VEC3init(&Fixup.v[2], 0, 0, (double) 0xFFFF/0xFF00);
-
-
-                MAT3fromFix(&Original, &Lut->Matrix);
-                MAT3per(&Result, &Original, &Fixup);
-                MAT3toFix(&Lut->Matrix, &Result);
-
-                Lut -> wFlags |= LUT_HASMATRIX;
-                break;
-
-       // For input, clear low part since this has to be
-       // Lab in fixed point
-
-       default:
-
-                PtrW = Lut -> T;
-                for (i = 0; i < nTabSize; i++) {
-
-                             *PtrW++ &= 0xFF00;
-                }
-    }
-
-}
-
-// On Lab -> Lab abstract or Lab identities, fix both sides of LUT
-
-static
-void FixLUT8bothSides(LPLUT Lut, size_t nTabSize)
-{
-    MAT3 Fixup, Original, Result;
-    LPWORD PtrW;
-    size_t i;
-
-        VEC3init(&Fixup.v[0], (double) 0xFFFF/0xFF00, 0, 0);
-        VEC3init(&Fixup.v[1], 0, (double) 0xFFFF/0xFF00, 0);
-        VEC3init(&Fixup.v[2], 0, 0, (double) 0xFFFF/0xFF00);
-
-        MAT3fromFix(&Original, &Lut->Matrix);
-        MAT3per(&Result, &Original, &Fixup);
-        MAT3toFix(&Lut->Matrix, &Result);
-
-        Lut -> wFlags |= LUT_HASMATRIX;
-
-        PtrW = Lut -> T;
-        for (i = 0; i < nTabSize; i++) {
-
-                     *PtrW++ &= 0xFF00;
-        }
+static const cmsTagSignature PCS2Device16[]    = {cmsSigBToA0Tag,     // Perceptual
+                                                  cmsSigBToA1Tag,     // Relative colorimetric
+                                                  cmsSigBToA2Tag,     // Saturation
+                                                  cmsSigBToA1Tag };   // Absolute colorimetric
 
-}
-
-
-// The infamous LUT 8
-
-static
-LCMSBOOL ReadLUT8(LPLCMSICCPROFILE Icc, LPLUT NewLUT, icTagSignature sig)
-{
-    icLut8 LUT8;
-    LPBYTE Temp;
-    size_t nTabSize;
-    unsigned int i, j;
-    unsigned int AllLinear;
-    LPWORD PtrW;
-
-       if (Icc ->Read(&LUT8, sizeof(icLut8) - SIZEOF_UINT8_ALIGNED, 1, Icc) != 1) return FALSE;
-
-       NewLUT -> wFlags        = LUT_HASTL1|LUT_HASTL2|LUT_HAS3DGRID;
-       NewLUT -> cLutPoints    = LUT8.clutPoints;
-       NewLUT -> InputChan     = LUT8.inputChan;
-       NewLUT -> OutputChan    = LUT8.outputChan;
-       NewLUT -> InputEntries  = 256;
-       NewLUT -> OutputEntries = 256;
-
-       // Do some checking
-       if (!_cmsValidateLUT(NewLUT)) {
-          return FALSE;
-       }
-
-       AdjustEndianess32((LPBYTE) &LUT8.e00);
-       AdjustEndianess32((LPBYTE) &LUT8.e01);
-       AdjustEndianess32((LPBYTE) &LUT8.e02);
-       AdjustEndianess32((LPBYTE) &LUT8.e10);
-       AdjustEndianess32((LPBYTE) &LUT8.e11);
-       AdjustEndianess32((LPBYTE) &LUT8.e12);
-       AdjustEndianess32((LPBYTE) &LUT8.e20);
-       AdjustEndianess32((LPBYTE) &LUT8.e21);
-       AdjustEndianess32((LPBYTE) &LUT8.e22);
-
-
-       // Matrix handling
-
-       NewLUT -> Matrix.v[0].n[0] = (Fixed32) LUT8.e00;
-       NewLUT -> Matrix.v[0].n[1] = (Fixed32) LUT8.e01;
-       NewLUT -> Matrix.v[0].n[2] = (Fixed32) LUT8.e02;
-       NewLUT -> Matrix.v[1].n[0] = (Fixed32) LUT8.e10;
-       NewLUT -> Matrix.v[1].n[1] = (Fixed32) LUT8.e11;
-       NewLUT -> Matrix.v[1].n[2] = (Fixed32) LUT8.e12;
-       NewLUT -> Matrix.v[2].n[0] = (Fixed32) LUT8.e20;
-       NewLUT -> Matrix.v[2].n[1] = (Fixed32) LUT8.e21;
-       NewLUT -> Matrix.v[2].n[2] = (Fixed32) LUT8.e22;
-
-
-       // Only operates if not identity...
-
-       if ((NewLUT -> InputChan == 3) && !MAT3isIdentity(&NewLUT -> Matrix, 0.0001)) {
-
-              NewLUT -> wFlags |= LUT_HASMATRIX;
-       }
+static const cmsTagSignature PCS2DeviceFloat[] = {cmsSigBToD0Tag,     // Perceptual
+                                                  cmsSigBToD1Tag,     // Relative colorimetric
+                                                  cmsSigBToD2Tag,     // Saturation
+                                                  cmsSigBToD3Tag };   // Absolute colorimetric
 
 
-       // Copy input tables
-
-       Temp = (LPBYTE) _cmsMalloc(256);
-       if (Temp == NULL) return FALSE;
-
-       AllLinear = 0;
-       for (i=0; i < NewLUT -> InputChan; i++) {
-
-              PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * 256);
-              if (PtrW == NULL) {
-                   _cmsFree(Temp);
-                  return FALSE;
-                  }
-
-              NewLUT -> L1[i] = PtrW;
-              if (Icc ->Read(Temp, 1, 256, Icc) != 256) {
-                   _cmsFree(Temp);
-                  return FALSE;
-                  }
-
-              for (j=0; j < 256; j++)
-                     PtrW[j] = TO16_TAB(Temp[j]);
-                     AllLinear += cmsIsLinear(NewLUT -> L1[i], NewLUT -> InputEntries);
-              }
-
-       // Linear input, so ignore full step
-
-       if (AllLinear == NewLUT -> InputChan) {
-
-              NewLUT -> wFlags &= ~LUT_HASTL1;
-       }
-
-        _cmsFree(Temp);
-
-       // Copy 3D CLUT
-
-       nTabSize = (NewLUT -> OutputChan * uipow(NewLUT->cLutPoints,
-                                                NewLUT->InputChan));
-
-       if (nTabSize > 0) {
-
-            PtrW = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
-            if (PtrW == NULL) return FALSE;
-
-            Temp = (LPBYTE) _cmsMalloc(nTabSize);
-            if (Temp == NULL) {
-                 _cmsFree(PtrW);
-                return FALSE;
-                }
-
-            if (Icc ->Read(Temp, 1, nTabSize, Icc) != nTabSize) {
-                 _cmsFree(Temp);
-                _cmsFree(PtrW);
-                return FALSE;
-                }
-
-            NewLUT -> T = PtrW;
-            NewLUT -> Tsize = (unsigned int) (nTabSize * sizeof(WORD));
-
-            for (i = 0; i < nTabSize; i++) {
-
-                     *PtrW++ = TO16_TAB(Temp[i]);
-            }
-            _cmsFree(Temp);
-       }
-       else {
-           NewLUT ->T = NULL;
-           NewLUT ->Tsize = 0;
-           NewLUT ->wFlags &= ~LUT_HAS3DGRID;
-       }
-
-
-       // Copy output tables
-
-       Temp = (LPBYTE) _cmsMalloc(256);
-       if (Temp == NULL) {
-           return FALSE;
-           }
-
-       AllLinear = 0;
-       for (i=0; i < NewLUT -> OutputChan; i++) {
-
-              PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * 256);
-              if (PtrW == NULL) {
-                  _cmsFree(Temp);
-                  return FALSE;
-                  }
-
-              NewLUT -> L2[i] = PtrW;
-              if (Icc ->Read(Temp, 1, 256, Icc) != 256) {
-                  _cmsFree(Temp);
-                  return FALSE;
-                  }
-
-              for (j=0; j < 256; j++)
-                     PtrW[j] = TO16_TAB(Temp[j]);
-                     AllLinear += cmsIsLinear(NewLUT -> L2[i], 256);
-              }
-
-       // Linear input, so ignore full step
-
-       if (AllLinear == NewLUT -> OutputChan) {
-
-              NewLUT -> wFlags &= ~LUT_HASTL2;
-       }
-
-
-       _cmsFree(Temp);
-
-       cmsCalcL16Params(NewLUT -> InputEntries,  &NewLUT -> In16params);
-       cmsCalcL16Params(NewLUT -> OutputEntries, &NewLUT -> Out16params);
-       cmsCalcCLUT16Params(NewLUT -> cLutPoints,  NewLUT -> InputChan,
-                                                  NewLUT -> OutputChan,
-                                                 &NewLUT -> CLut16params);
-       // Fixup
-
-       if (Icc ->PCS == icSigLabData) {
-
-           // Abstract or Lab identity
-
-           if (Icc -> ColorSpace == icSigLabData)
-
-                FixLUT8bothSides(NewLUT, nTabSize);
-           else
-                FixLUT8(NewLUT, sig, nTabSize);
-
-
-           // Now some additional fixup. Lab encoding on 8 bit makes
-           // impossible to place gray axis on a exact node. However,
-           // some profiles does claim to do that. Poor lcms will try
-           // to detect such condition and fix up "on the fly".
-
-           switch (sig) {
-
-            case icSigBToA0Tag:
-            case icSigBToA1Tag:
-            case icSigBToA2Tag:
-            case icSigGamutTag:
-            case icSigPreview0Tag:
-            case icSigPreview1Tag:
-            case icSigPreview2Tag:
-           {
-               LPWORD WhiteLab, ExpectedWhite;
-               WORD WhiteFixed[MAXCHANNELS], WhiteUnfixed[MAXCHANNELS];
-               int j, nChannels;
-               double Dist, DistFixed, DistUnfixed;
-
-               _cmsEndPointsBySpace(icSigLabData, &WhiteLab, NULL, NULL);
+// Factors to convert from 1.15 fixed point to 0..1.0 range and vice-versa
+#define InpAdj   (1.0/MAX_ENCODEABLE_XYZ)     // (65536.0/(65535.0*2.0))
+#define OutpAdj  (MAX_ENCODEABLE_XYZ)         // ((2.0*65535.0)/65536.0)
 
-               if (_cmsEndPointsBySpace(Icc -> ColorSpace,
-                                &ExpectedWhite, NULL, &nChannels)) {
-
-                   // 1.- Find white obtained by both combinations
-
-                   NewLUT -> FixGrayAxes = FALSE;
-                   cmsEvalLUT(NewLUT, WhiteLab, WhiteUnfixed);
-
-                   NewLUT -> FixGrayAxes = TRUE;
-                   cmsEvalLUT(NewLUT, WhiteLab, WhiteFixed);
-
-                   // 2.- Which method gives closer white?
-
-                   DistFixed = DistUnfixed = 0;
-                   for (j=0; j < nChannels; j++) {
-
-                       Dist = ExpectedWhite[j] - WhiteFixed[j];
-                       DistFixed += Dist*Dist;
-                       Dist = ExpectedWhite[j] - WhiteUnfixed[j];
-                       DistUnfixed += Dist*Dist;
-                   }
-
-                   // 3.- Decide method
-
-                   if (sqrt(DistFixed) < sqrt(DistUnfixed))
-                       NewLUT -> FixGrayAxes = TRUE;
-                   else
-                       NewLUT -> FixGrayAxes = FALSE;
-               }
-
-           }
-           break;
-
-        default:;
-        }
-       }
-
-       return TRUE;
-}
-
-
-
-
-// Case LUT 16
-
-static
-LCMSBOOL ReadLUT16(LPLCMSICCPROFILE Icc, LPLUT NewLUT)
-{
-    icLut16 LUT16;
-    size_t nTabSize;
-    unsigned int i;
-    unsigned int AllLinear;
-    LPWORD PtrW;
-
-
-       if (Icc ->Read(&LUT16, sizeof(icLut16)- SIZEOF_UINT16_ALIGNED, 1, Icc) != 1)
-            return FALSE;
-
-       NewLUT -> wFlags        = LUT_HASTL1 | LUT_HASTL2 | LUT_HAS3DGRID;
-       NewLUT -> cLutPoints    = LUT16.clutPoints;
-       NewLUT -> InputChan     = LUT16.inputChan;
-       NewLUT -> OutputChan    = LUT16.outputChan;
-
-       AdjustEndianess16((LPBYTE) &LUT16.inputEnt);
-       AdjustEndianess16((LPBYTE) &LUT16.outputEnt);
-
-       NewLUT -> InputEntries  = LUT16.inputEnt;
-       NewLUT -> OutputEntries = LUT16.outputEnt;
-
-       if (!_cmsValidateLUT(NewLUT)) {
-         return FALSE;
-       }
-
-       // Matrix handling
-
-       AdjustEndianess32((LPBYTE) &LUT16.e00);
-       AdjustEndianess32((LPBYTE) &LUT16.e01);
-       AdjustEndianess32((LPBYTE) &LUT16.e02);
-       AdjustEndianess32((LPBYTE) &LUT16.e10);
-       AdjustEndianess32((LPBYTE) &LUT16.e11);
-       AdjustEndianess32((LPBYTE) &LUT16.e12);
-       AdjustEndianess32((LPBYTE) &LUT16.e20);
-       AdjustEndianess32((LPBYTE) &LUT16.e21);
-       AdjustEndianess32((LPBYTE) &LUT16.e22);
-
-       NewLUT -> Matrix.v[0].n[0] = (Fixed32) LUT16.e00;
-       NewLUT -> Matrix.v[0].n[1] = (Fixed32) LUT16.e01;
-       NewLUT -> Matrix.v[0].n[2] = (Fixed32) LUT16.e02;
-       NewLUT -> Matrix.v[1].n[0] = (Fixed32) LUT16.e10;
-       NewLUT -> Matrix.v[1].n[1] = (Fixed32) LUT16.e11;
-       NewLUT -> Matrix.v[1].n[2] = (Fixed32) LUT16.e12;
-       NewLUT -> Matrix.v[2].n[0] = (Fixed32) LUT16.e20;
-       NewLUT -> Matrix.v[2].n[1] = (Fixed32) LUT16.e21;
-       NewLUT -> Matrix.v[2].n[2] = (Fixed32) LUT16.e22;
-
-       // Only operates if not identity...
-
-       if ((NewLUT -> InputChan == 3) && !MAT3isIdentity(&NewLUT -> Matrix, 0.0001)) {
-
-              NewLUT -> wFlags |= LUT_HASMATRIX;
-       }
-
-
-       // Copy input tables
-
-       AllLinear = 0;
-       for (i=0; i < NewLUT -> InputChan; i++) {
-
-              PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> InputEntries);
-              if (PtrW == NULL) return FALSE;
-
-              NewLUT -> L1[i] = PtrW;
-              if (Icc ->Read(PtrW, sizeof(WORD), NewLUT -> InputEntries, Icc) != NewLUT -> InputEntries) {
-                  return FALSE;
-                  }
-
-              AdjustEndianessArray16(PtrW, NewLUT -> InputEntries);
-              AllLinear += cmsIsLinear(NewLUT -> L1[i], NewLUT -> InputEntries);
-              }
-
-       // Linear input, so ignore full step
-
-       if (AllLinear == NewLUT -> InputChan) {
-
-              NewLUT -> wFlags &= ~LUT_HASTL1;
-       }
-
-
-       // Copy 3D CLUT
-
-       nTabSize = (NewLUT -> OutputChan * uipow(NewLUT->cLutPoints,
-                                                NewLUT->InputChan));
-       if (nTabSize > 0) {
-
-           PtrW = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
-           if (PtrW == NULL)
-               return FALSE;
-
-           NewLUT -> T = PtrW;
-           NewLUT -> Tsize = (unsigned int) (nTabSize * sizeof(WORD));
-
-           if (Icc -> Read(PtrW, sizeof(WORD), nTabSize, Icc) != nTabSize) {
-               return FALSE;
-           }
-
-           AdjustEndianessArray16(NewLUT -> T, nTabSize);
-       }
-       else {
-           NewLUT ->T = NULL;
-           NewLUT ->Tsize = 0;
-           NewLUT -> wFlags &= ~LUT_HAS3DGRID;
-       }
+// Several resources for gray conversions.
+static const cmsFloat64Number GrayInputMatrix[] = { (InpAdj*cmsD50X),  (InpAdj*cmsD50Y),  (InpAdj*cmsD50Z) };
+static const cmsFloat64Number OneToThreeInputMatrix[] = { 1, 1, 1 };
+static const cmsFloat64Number PickYMatrix[] = { 0, (OutpAdj*cmsD50Y), 0 };
+static const cmsFloat64Number PickLstarMatrix[] = { 1, 0, 0 };
 
-       // Copy output tables
-
-       AllLinear = 0;
-       for (i=0; i < NewLUT -> OutputChan; i++) {
-
-              PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> OutputEntries);
-              if (PtrW == NULL) {
-                  return FALSE;
-                  }
-
-              NewLUT -> L2[i] = PtrW;
-              if (Icc ->Read(PtrW, sizeof(WORD), NewLUT -> OutputEntries, Icc) != NewLUT -> OutputEntries) {
-                  return FALSE;
-                  }
-
-              AdjustEndianessArray16(PtrW, NewLUT -> OutputEntries);
-              AllLinear += cmsIsLinear(NewLUT -> L2[i], NewLUT -> OutputEntries);
-              }
-
-       // Linear output, ignore step
-
-       if (AllLinear == NewLUT -> OutputChan)
-       {
-              NewLUT -> wFlags &= ~LUT_HASTL2;
-       }
-
-
-       cmsCalcL16Params(NewLUT -> InputEntries,  &NewLUT -> In16params);
-       cmsCalcL16Params(NewLUT -> OutputEntries, &NewLUT -> Out16params);
-       cmsCalcCLUT16Params(NewLUT -> cLutPoints,  NewLUT -> InputChan,
-                                                  NewLUT -> OutputChan,
-                                                  &NewLUT -> CLut16params);
-
-       return TRUE;
-}
-
-
-// This is a shared routine for reading curves. It can handle v2 curves
-// as linear, single gamma and table-based as well as v4 parametric curves.
-
-static
-LPGAMMATABLE ReadCurve(LPLCMSICCPROFILE  Icc)
+// Get a media white point fixing some issues found in certain old profiles
+cmsBool  _cmsReadMediaWhitePoint(cmsCIEXYZ* Dest, cmsHPROFILE hProfile)
 {
-    icUInt32Number      Count;
-    LPGAMMATABLE        NewGamma;
-    icTagTypeSignature  BaseType;
-    int                 n;
-
-
-       BaseType = ReadBase(Icc);
-       switch (BaseType) {
-
-
-       case ((icTagTypeSignature) 0x9478ee00):    // Monaco 2 profiler is BROKEN!
-       case icSigCurveType:
-
-           if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
-           AdjustEndianess32((LPBYTE) &Count);
-
-           switch (Count) {
-
-           case 0:   // Linear.
-
-                     NewGamma = cmsAllocGamma(2);
-                     if (!NewGamma) return NULL;
-                     NewGamma -> GammaTable[0] = 0;
-                     NewGamma -> GammaTable[1] = 0xFFFF;
-                     return NewGamma;
-
-           case 1:  // Specified as the exponent of gamma function
-                    {
-                     WORD SingleGammaFixed;
+    cmsCIEXYZ* Tag;
 
-                     if (Icc ->Read(&SingleGammaFixed, sizeof(WORD), 1, Icc) != 1) return NULL;
-                     AdjustEndianess16((LPBYTE) &SingleGammaFixed);
-                     return cmsBuildGamma(4096, Convert8Fixed8(SingleGammaFixed));
-                     }
-
-           default: { // Curve
-
-                     NewGamma = cmsAllocGamma(Count);
-                     if (!NewGamma) return NULL;
-
-                     if (Icc ->Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc) != Count)
-                         return NULL;
-                     AdjustEndianessArray16(NewGamma -> GammaTable, Count);
-                     return NewGamma;
-                    }
-              }
-              break;
-
-
-       // Parametric curves
-       case icSigParametricCurveType: {
-
-           int ParamsByType[] = { 1, 3, 4, 5, 7 };
-           double Params[10];
-           icS15Fixed16Number Num;
-           icUInt32Number Reserved;
-           icUInt16Number   Type;
-           int i;
-
-           if (Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
-           if (Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
-
-           AdjustEndianess16((LPBYTE) &Type);
-           if (Type > 4) {
-
-                cmsSignalError(LCMS_ERRC_ABORTED, "Unknown parametric curve type '%d' found.", Type);
-                return NULL;
-           }
-
-          ZeroMemory(Params, 10* sizeof(double));
-          n = ParamsByType[Type];
-
-          for (i=0; i < n; i++) {
-                Num = 0;
-                if (Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc) != 1) return NULL;
-                Params[i] = Convert15Fixed16(Num);
-          }
-
-
-           NewGamma = cmsBuildParametricGamma(4096, Type+1, Params);
-           return NewGamma;
-          }
-
-
-       default:
-              cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature '%lx' found.", BaseType);
-              return NULL;
-       }
-
-}
-
-
-// Similar to anterior, but curve is reversed
-
-static
-LPGAMMATABLE ReadCurveReversed(LPLCMSICCPROFILE Icc)
-{
-
-     icTagTypeSignature BaseType;
-     LPGAMMATABLE       NewGamma, ReturnGamma;
-     icUInt32Number     Count;
-     int                n;
-
-
-       BaseType = ReadBase(Icc);
-
-       switch (BaseType) {
-
+    _cmsAssert(Dest != NULL);
 
-       case 0x9478ee00L:    // Monaco 2 profiler is BROKEN!
-       case icSigCurveType:
-
-           if (Icc -> Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
-           AdjustEndianess32((LPBYTE) &Count);
-
-
-           switch (Count) {
-
-           case 0:   // Linear, reverse is same.
-
-                     NewGamma = cmsAllocGamma(2);
-                     if (!NewGamma) return NULL;
-
-                     NewGamma -> GammaTable[0] = 0;
-                     NewGamma -> GammaTable[1] = 0xFFFF;
-                     return NewGamma;
-
-           case 1:  {
-                     WORD SingleGammaFixed;
-
-                     if (Icc -> Read(&SingleGammaFixed, sizeof(WORD), 1, Icc) != 1) return NULL;
-                     AdjustEndianess16((LPBYTE) &SingleGammaFixed);
-                     return cmsBuildGamma(4096, 1./Convert8Fixed8(SingleGammaFixed));
-                     }
-
-           default: { // Curve. Do our best to trying to reverse the curve
-
-                     NewGamma = cmsAllocGamma(Count);
-                     if (!NewGamma) return NULL;
-
-                     if (Icc -> Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc) != Count)
-                         return NULL;
-
-                     AdjustEndianessArray16(NewGamma -> GammaTable, Count);
-
-                     if (Count < 256)
-                         Count = 256;      // Reverse of simple curve has not necesarely to be simple
-
-                     ReturnGamma = cmsReverseGamma(Count, NewGamma);
-                     cmsFreeGamma(NewGamma);
-
-                     return ReturnGamma;
-                    }
-              }
-              break;
-
-
-       // Parametric curves
-       case icSigParametricCurveType: {
-
-           int ParamsByType[] = { 1, 3, 4, 5, 7 };
-           double Params[10];
-           icS15Fixed16Number Num;
-           icUInt32Number Reserved;
-           icUInt16Number   Type;
-           int i;
-
-
-           if (Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
-           if (Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
-
-           AdjustEndianess16((LPBYTE) &Type);
-           if (Type > 4) {
-
-                cmsSignalError(LCMS_ERRC_ABORTED, "Unknown parametric curve type '%d' found.", Type);
-                return NULL;
-           }
-
-          ZeroMemory(Params, 10* sizeof(double));
-          n = ParamsByType[Type];
+    Tag = (cmsCIEXYZ*) cmsReadTag(hProfile, cmsSigMediaWhitePointTag);
 
-          for (i=0; i < n; i++) {
-                if (Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc) != 1) return NULL;
-                Params[i] = Convert15Fixed16(Num);
-          }
-
-
-           // Negative type as a mark of reversed curve
-           NewGamma = cmsBuildParametricGamma(4096, -(Type+1), Params);
-           return NewGamma;
-          }
-
-
-       default:
-              cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature '%lx' found.", BaseType);
-              return NULL;
-       }
-
-}
-
-
-// V4 stuff. Read matrix for LutAtoB and LutBtoA
-
-static
-LCMSBOOL ReadMatrixOffset(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, DWORD dwFlags)
-{
-
-    icS15Fixed16Number All[12];
-    int i;
-    MAT3 m;
-    VEC3 o;
-
-    if (Icc -> Seek(Icc, Offset)) return FALSE;
-
-    if (Icc ->Read(All, sizeof(icS15Fixed16Number), 12, Icc) != 12)
-        return FALSE;
-
-    for (i=0; i < 12;  i++)
-              AdjustEndianess32((LPBYTE) &All[i]);
-
-
-       m.v[0].n[0] = FIXED_TO_DOUBLE((Fixed32) All[0]);
-       m.v[0].n[1] = FIXED_TO_DOUBLE((Fixed32) All[1]);
-       m.v[0].n[2] = FIXED_TO_DOUBLE((Fixed32) All[2]);
-       m.v[1].n[0] = FIXED_TO_DOUBLE((Fixed32) All[3]);
-       m.v[1].n[1] = FIXED_TO_DOUBLE((Fixed32) All[4]);
-       m.v[1].n[2] = FIXED_TO_DOUBLE((Fixed32) All[5]);
-       m.v[2].n[0] = FIXED_TO_DOUBLE((Fixed32) All[6]);
-       m.v[2].n[1] = FIXED_TO_DOUBLE((Fixed32) All[7]);
-       m.v[2].n[2] = FIXED_TO_DOUBLE((Fixed32) All[8]);
-
-       o.n[0] = FIXED_TO_DOUBLE((Fixed32) All[9]);
-       o.n[1] = FIXED_TO_DOUBLE((Fixed32) All[10]);
-       o.n[2] = FIXED_TO_DOUBLE((Fixed32) All[11]);
-
-       cmsSetMatrixLUT4(NewLUT, &m, &o, dwFlags);
-
-       return TRUE;
-}
-
-
-//  V4 stuff. Read CLUT part for LutAtoB and LutBtoA
-
-static
-LCMSBOOL ReadCLUT(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT)
-{
-    unsigned int j;
-    icCLutStruct CLUT;
-
-    if (Icc -> Seek(Icc, Offset)) return FALSE;
-    if (Icc ->Read(&CLUT, sizeof(icCLutStruct), 1, Icc) != 1) return FALSE;
-
-
-    for (j=1; j < NewLUT ->InputChan; j++) {
-        if (CLUT.gridPoints[0] != CLUT.gridPoints[j]) {
-            cmsSignalError(LCMS_ERRC_ABORTED, "CLUT with different granulatity is currently unsupported.");
-            return FALSE;
-        }
-
-
+    // If no wp, take D50
+    if (Tag == NULL) {
+        *Dest = *cmsD50_XYZ();
+        return TRUE;
     }
 
-    if (cmsAlloc3DGrid(NewLUT, CLUT.gridPoints[0], NewLUT ->InputChan,
-                                               NewLUT ->OutputChan) == NULL) return FALSE;
-
-    // Precission can be 1 or 2 bytes
-
-    if (CLUT.prec == 1) {
+    // V2 display profiles should give D50
+    if (cmsGetEncodedICCversion(hProfile) < 0x4000000) {
 
-        BYTE v;
-        unsigned int i;
-
-        for (i=0; i < NewLUT->Tsize / sizeof(WORD); i++) {
-                if (Icc ->Read(&v, sizeof(BYTE), 1, Icc) != 1) return FALSE;
-                NewLUT->T[i] = TO16_TAB(v);
+        if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) {
+            *Dest = *cmsD50_XYZ();
+            return TRUE;
         }
-
-    }
-    else
-        if (CLUT.prec == 2) {
-
-         size_t n = NewLUT->Tsize / sizeof(WORD);
-
-         if (Icc ->Read(NewLUT ->T, sizeof(WORD), n, Icc) != n) return FALSE;
-         AdjustEndianessArray16(NewLUT ->T, NewLUT->Tsize / sizeof(WORD));
-    }
-    else {
-        cmsSignalError(LCMS_ERRC_ABORTED, "Unknow precission of '%d'", CLUT.prec);
-        return FALSE;
     }
 
+    // All seems ok
+    *Dest = *Tag;
     return TRUE;
 }
 
 
-static
-void ResampleCurves(LPGAMMATABLE Curves[], int nCurves)
-{
-    int i;
-    LPSAMPLEDCURVE sc;
-
-    for (i=0; i < nCurves; i++) {
-        sc = cmsConvertGammaToSampledCurve(Curves[i], 4096);
-        cmsFreeGamma(Curves[i]);
-        Curves[i] = cmsConvertSampledCurveToGamma(sc, 0xFFFF);
-        cmsFreeSampledCurve(sc);
-    }
-
-}
-
-
-static
-void SkipAlignment(LPLCMSICCPROFILE Icc)
-{
-    BYTE Buffer[4];
-    size_t At = Icc ->Tell(Icc);
-    int BytesToNextAlignedPos = (int) (At % 4);
-
-    Icc ->Read(Buffer, 1, BytesToNextAlignedPos, Icc);
-}
-
-// Read a set of curves from specific offset
-static
-LCMSBOOL ReadSetOfCurves(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, int nLocation)
+// Chromatic adaptation matrix. Fix some issues as well
+cmsBool  _cmsReadCHAD(cmsMAT3* Dest, cmsHPROFILE hProfile)
 {
-    LPGAMMATABLE Curves[MAXCHANNELS];
-    unsigned int i, nCurves;
-
-    if (Icc -> Seek(Icc, Offset)) return FALSE;
-
-    if (nLocation == 1 ||  nLocation == 3)
-
-        nCurves = NewLUT ->InputChan;
-    else
-        nCurves = NewLUT ->OutputChan;
-
-    ZeroMemory(Curves, sizeof(Curves));
-    for (i=0; i < nCurves; i++) {
-
-        Curves[i] = ReadCurve(Icc);
-        if (Curves[i] == NULL) goto Error;
-        SkipAlignment(Icc);
-    }
-
-    // March-26'08: some V4 profiles may have different sampling
-    // rates, in this case resample all curves to maximum
-
-    for (i=1; i < nCurves; i++) {
-        if (Curves[i]->nEntries != Curves[0]->nEntries) {
-            ResampleCurves(Curves, nCurves);
-        break;
-        }
-    }
-
-    NewLUT = cmsAllocLinearTable(NewLUT, Curves, nLocation);
-    if (NewLUT == NULL) goto Error;
-
-    for (i=0; i < nCurves; i++)
-        cmsFreeGamma(Curves[i]);
-
-    return TRUE;
-
-Error:
+    cmsMAT3* Tag;
 
-    for (i=0; i < nCurves; i++)
-        if (Curves[i])
-            cmsFreeGamma(Curves[i]);
-
-    return FALSE;
-
-
-}
-
-// V4 stuff. LutAtoB type
-//
-//  [L1] -> [CLUT] -> [L4] -> [Mat4] -> [Ofs4] -> [L2]
-//
-//  Mat, Mat3, Ofs3, L3 are missing
-//   L1 = A curves
-//   L4 = M curves
-//   L2 = B curves
-
-static
-LCMSBOOL ReadLUT_A2B(LPLCMSICCPROFILE Icc, LPLUT NewLUT, size_t BaseOffset, icTagSignature sig)
-{
-    icLutAtoB LUT16;
-
-       if (Icc ->Read(&LUT16, sizeof(icLutAtoB), 1, Icc) != 1) return FALSE;
-
-       NewLUT -> InputChan     = LUT16.inputChan;
-       NewLUT -> OutputChan    = LUT16.outputChan;
-
-       // Validate the NewLUT here to avoid excessive number of channels
-       // (leading to stack-based buffer overflow in ReadSetOfCurves).
-       // Needs revalidation after table size is filled in.
-       if (!_cmsValidateLUT(NewLUT)) {
-           return FALSE;
-       }
-
-       AdjustEndianess32((LPBYTE) &LUT16.offsetB);
-       AdjustEndianess32((LPBYTE) &LUT16.offsetMat);
-       AdjustEndianess32((LPBYTE) &LUT16.offsetM);
-       AdjustEndianess32((LPBYTE) &LUT16.offsetC);
-       AdjustEndianess32((LPBYTE) &LUT16.offsetA);
-
-       if (LUT16.offsetB != 0)
-                ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetB, NewLUT, 2);
-
-       if (LUT16.offsetMat != 0)
-            ReadMatrixOffset(Icc, BaseOffset + LUT16.offsetMat, NewLUT, LUT_HASMATRIX4);
-
-
-       if (LUT16.offsetM != 0)
-                ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetM, NewLUT, 4);
-
-       if (LUT16.offsetC != 0)
-           ReadCLUT(Icc, BaseOffset + LUT16.offsetC, NewLUT);
-
-       if (LUT16.offsetA!= 0)
-                ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetA, NewLUT, 1);
-
-        // Convert to v2 PCS
-
-       if (Icc ->PCS == icSigLabData) {
-
-       switch (sig) {
-
-       case icSigAToB0Tag:
-       case icSigAToB1Tag:
-       case icSigAToB2Tag:
-       case icSigGamutTag:
-       case icSigPreview0Tag:
-       case icSigPreview1Tag:
-       case icSigPreview2Tag:
-
-               NewLUT ->wFlags |= LUT_V4_INPUT_EMULATE_V2;
-               break;
+    _cmsAssert(Dest != NULL);
 
-       default:;
-       }
-       }
-
-
-       return TRUE;
-}
-
-// V4 stuff. LutBtoA type
-
-static
-LCMSBOOL ReadLUT_B2A(LPLCMSICCPROFILE Icc, LPLUT NewLUT,  size_t BaseOffset, icTagSignature sig)
-{
-  icLutBtoA LUT16;
-
-       if (Icc ->Read(&LUT16, sizeof(icLutBtoA), 1, Icc) != 1) return FALSE;
-
-       NewLUT -> InputChan     = LUT16.inputChan;
-       NewLUT -> OutputChan    = LUT16.outputChan;
-
-       // Validate the NewLUT here to avoid excessive number of channels
-       // (leading to stack-based buffer overflow in ReadSetOfCurves).
-       // Needs revalidation after table size is filled in.
-       if (!_cmsValidateLUT(NewLUT)) {
-           return FALSE;
-       }
-
-       AdjustEndianess32((LPBYTE) &LUT16.offsetB);
-       AdjustEndianess32((LPBYTE) &LUT16.offsetMat);
-       AdjustEndianess32((LPBYTE) &LUT16.offsetM);
-       AdjustEndianess32((LPBYTE) &LUT16.offsetC);
-       AdjustEndianess32((LPBYTE) &LUT16.offsetA);
-
-
-       if (LUT16.offsetB != 0)
-                ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetB, NewLUT, 1);
-
-       if (LUT16.offsetMat != 0)
-            ReadMatrixOffset(Icc, BaseOffset + LUT16.offsetMat, NewLUT, LUT_HASMATRIX3);
-
-       if (LUT16.offsetM != 0)
-                ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetM, NewLUT, 3);
-
-       if (LUT16.offsetC != 0)
-           ReadCLUT(Icc, BaseOffset + LUT16.offsetC, NewLUT);
-
-       if (LUT16.offsetA!= 0)
-                ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetA, NewLUT, 2);
-
-
-       // Convert to v2 PCS
-
-       if (Icc ->PCS == icSigLabData) {
-
-       switch (sig) {
-
-       case icSigBToA0Tag:
-       case icSigBToA1Tag:
-       case icSigBToA2Tag:
-       case icSigGamutTag:
-       case icSigPreview0Tag:
-       case icSigPreview1Tag:
-       case icSigPreview2Tag:
-
-               NewLUT ->wFlags |= LUT_V4_OUTPUT_EMULATE_V2;
-               break;
-
-       default:;
-       }
-       }
+    Tag = (cmsMAT3*) cmsReadTag(hProfile, cmsSigChromaticAdaptationTag);
 
-       return TRUE;
-}
-
-// CLUT main reader
-
-LPLUT LCMSEXPORT cmsReadICCLut(cmsHPROFILE hProfile, icTagSignature sig)
-{
-
-    LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    icTagTypeSignature  BaseType;
-    int                 n;
-    size_t              offset;
-    LPLUT               NewLUT;
-
-    n = _cmsSearchTag(Icc, sig, TRUE);
-    if (n < 0)
-        return NULL;
-
-
-    // If is in memory, the LUT is already there, so throw a copy
-    if (Icc -> TagPtrs[n]) {
-        if (!_cmsValidateLUT((LPLUT) Icc ->TagPtrs[n])) {
-            return NULL;
-        }
-
-        return cmsDupLUT((LPLUT) Icc ->TagPtrs[n]);
-    }
-
-    offset = Icc -> TagOffsets[n];
-
-    if (Icc -> Seek(Icc, offset))
-            return NULL;
-
-    BaseType = ReadBase(Icc);
-
+    if (Tag != NULL) {
 
-    NewLUT = cmsAllocLUT();
-    if (!NewLUT) {
-
-       cmsSignalError(LCMS_ERRC_ABORTED, "cmsAllocLUT() failed");
-       return NULL;
-    }
-
-
-    switch (BaseType) {
-
-    case icSigLut8Type:    if (!ReadLUT8(Icc, NewLUT, sig)) {
-                                cmsFreeLUT(NewLUT);
-                                return NULL;
-                           }
-                           break;
-
-    case icSigLut16Type:   if (!ReadLUT16(Icc, NewLUT)) {
-                                cmsFreeLUT(NewLUT);
-                                return NULL;
-                           }
-                           break;
-
-    case icSiglutAtoBType: if (!ReadLUT_A2B(Icc, NewLUT, offset, sig)) {
-                                cmsFreeLUT(NewLUT);
-                                return NULL;
-                           }
-                           break;
-
-    case icSiglutBtoAType: if (!ReadLUT_B2A(Icc, NewLUT, offset, sig)) {
-                                cmsFreeLUT(NewLUT);
-                                return NULL;
-                           }
-                           break;
-
-    default:  cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature %lx found.", BaseType);
-              cmsFreeLUT(NewLUT);
-              return NULL;
+        *Dest = *Tag;
+        return TRUE;
     }
 
-
-    return NewLUT;
-}
-
-
-// Sets the language & country preferences. Used only in ICC 4.0 profiles
-
-void LCMSEXPORT cmsSetLanguage(const char LanguageCode[4], const char CountryCode[4])
-{
-
-    int LanguageCodeInt = *(int *) LanguageCode;
-    int CountryCodeInt  = *(int *) CountryCode;
-
-    AdjustEndianess32((LPBYTE) &LanguageCodeInt);
-    AdjustEndianess32((LPBYTE) &CountryCodeInt);
-
-    GlobalLanguageCode = LanguageCodeInt;
-    GlobalCountryCode  = CountryCodeInt;
-}
-
-
-
-// Some tags (e.g, 'pseq') can have text tags embedded. This function
-// handles such special case. Returns -1 on error, or the number of bytes left on success.
-
-static
-int ReadEmbeddedTextTag(LPLCMSICCPROFILE Icc, size_t size, char* Name, size_t size_max)
-{
-    icTagTypeSignature  BaseType;
-
-
-    BaseType = ReadBase(Icc);
-    size -= sizeof(icTagBase);
-
-    switch (BaseType) {
-
-    case icSigTextDescriptionType: {
-
-           icUInt32Number  AsciiCount;
-           icUInt32Number  i, UnicodeCode, UnicodeCount;
-           icUInt16Number  ScriptCodeCode, Dummy;
-           icUInt8Number   ScriptCodeCount;
-
-           if (Icc ->Read(&AsciiCount, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
+    // No CHAD available, default it to identity
+    _cmsMAT3identity(Dest);
 
-           if (size < sizeof(icUInt32Number)) return (int) size;
-           size -= sizeof(icUInt32Number);
-
-           AdjustEndianess32((LPBYTE) &AsciiCount);
-           Icc ->Read(Name, 1,
-                (AsciiCount >= size_max) ? (size_max-1) : AsciiCount, Icc);
-
-           if (size < AsciiCount) return (int) size;
-           size -= AsciiCount;
-
-           // Skip Unicode code
-
-           if (Icc ->Read(&UnicodeCode,  sizeof(icUInt32Number), 1, Icc) != 1) return -1;
-           if (size < sizeof(icUInt32Number)) return (int) size;
-           size -= sizeof(icUInt32Number);
-
-           if (Icc ->Read(&UnicodeCount, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
-           if (size < sizeof(icUInt32Number)) return (int) size;
-           size -= sizeof(icUInt32Number);
-
-           AdjustEndianess32((LPBYTE) &UnicodeCount);
-
-           if (UnicodeCount > size) return (int) size;
-
-           for (i=0; i < UnicodeCount; i++) {
-                size_t nread = Icc ->Read(&Dummy, sizeof(icUInt16Number), 1, Icc);
-                if (nread != 1) return (int) size;
-                size -= sizeof(icUInt16Number);
-           }
-
-          // Skip ScriptCode code
-
-           if (Icc ->Read(&ScriptCodeCode,  sizeof(icUInt16Number), 1, Icc) != 1) return -1;
-           size -= sizeof(icUInt16Number);
-           if (Icc ->Read(&ScriptCodeCount, sizeof(icUInt8Number), 1, Icc) != 1) return -1;
-           size -= sizeof(icUInt8Number);
-
-           // Should remain 67 bytes as filler
-
-           if (size < 67) return (int) size;
-
-           for (i=0; i < 67; i++) {
-                size_t nread = Icc ->Read(&Dummy, sizeof(icUInt8Number), 1, Icc);
-                if (nread != 1) return (int) size;
-                size --;
-               }
-           }
-           break;
-
+    // V2 display profiles should give D50
+    if (cmsGetEncodedICCversion(hProfile) < 0x4000000) {
 
-    case icSigCopyrightTag:   // Broken profiles from agfa does store copyright info in such type
-    case icSigTextType:
-         {
-         char Dummy;
-         size_t i, Missing = 0;
-
-         if (size >= size_max) {
-
-             Missing = size - size_max + 1;
-             size = size_max - 1;
-         }
-
-         if (Icc -> Read(Name, 1, size, Icc) != size) return -1;
-
-         for (i=0; i < Missing; i++)
-             Icc -> Read(&Dummy, 1, 1, Icc);
-         }
-         break;
-
-    // MultiLocalizedUnicodeType, V4 only
+        if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) {
 
-    case icSigMultiLocalizedUnicodeType: {
-
-        icUInt32Number Count, RecLen;
-        icUInt16Number Language, Country;
-        icUInt32Number ThisLen, ThisOffset;
-        size_t         Offset = 0;
-        size_t         Len    = 0;
-        size_t         i;
-        wchar_t*       wchar  = L"";
-
-
-            if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
-            AdjustEndianess32((LPBYTE) &Count);
-            if (Icc ->Read(&RecLen, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
-            AdjustEndianess32((LPBYTE) &RecLen);
-
-            if (RecLen != 12) {
-
-                    cmsSignalError(LCMS_ERRC_ABORTED, "multiLocalizedUnicodeType of len != 12 is not supported.");
-                    return -1;
-            }
-
-            for (i=0; i < Count; i++) {
+            cmsCIEXYZ* White = (cmsCIEXYZ*) cmsReadTag(hProfile, cmsSigMediaWhitePointTag);
 
-                if (Icc ->Read(&Language, sizeof(icUInt16Number), 1, Icc) != 1) return -1;
-                AdjustEndianess16((LPBYTE) &Language);
-                if (Icc ->Read(&Country, sizeof(icUInt16Number), 1, Icc) != 1) return -1;
-                AdjustEndianess16((LPBYTE) &Country);
-
-                if (Icc ->Read(&ThisLen, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
-                AdjustEndianess32((LPBYTE) &ThisLen);
-
-                if (Icc ->Read(&ThisOffset, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
-                AdjustEndianess32((LPBYTE) &ThisOffset);
-
-                if (Language == GlobalLanguageCode || Offset == 0) {
-
-                    Len = ThisLen; Offset = ThisOffset;
-                    if (Country == GlobalCountryCode)
-                                    break;              // Found
-                }
-
-            }
-
-
-            if (Offset == 0) {
-
-                    strcpy(Name, "(no info)");
-                    break;
-            }
+            if (White == NULL) {
 
-            // Compute true offset
-            Offset -= 12 * Count + 8 + sizeof(icTagBase);
-
-            // Skip unused bytes
-            for (i=0; i < Offset; i++) {
-
-                    char Discard;
-                    if (Icc ->Read(&Discard, 1, 1, Icc) != 1) return -1;
-            }
-
-
-            // Bound len
-            if (Len < 0) Len = 0;
-            if (Len > 20*1024) Len = 20 * 1024;
-
-            wchar = (wchar_t*) _cmsMalloc(Len*sizeof(wchar_t)+2);
-            if (!wchar) return -1;
-
-            if (Icc ->Read(wchar, 1, Len, Icc) != Len) return -1;
-            AdjustEndianessArray16((LPWORD) wchar, Len / 2);
-
-            wchar[Len / 2] = L'\0';
-            i = wcstombs(Name, wchar, size_max );
-            if (i == ((size_t) -1)) {
-
-                Name[0] = 0;    // Error
+                _cmsMAT3identity(Dest);
+                return TRUE;
             }
 
-            _cmsFree((void*) wchar);
-            }
-            break;
-
-    default:
-            cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature %lx found.", BaseType);
-            return -1;
-    }
-
-    return (int) size;
-}
-
-
-// Take an ASCII item. Takes at most size_max bytes
-
-int LCMSEXPORT cmsReadICCTextEx(cmsHPROFILE hProfile, icTagSignature sig, char *Name, size_t size_max)
-{
-    LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    size_t              offset, size;
-    int                 n;
-
-    n = _cmsSearchTag(Icc, sig, TRUE);
-    if (n < 0)
-        return -1;
-
-     size   = Icc -> TagSizes[n];
-
-    if (Icc -> TagPtrs[n]) {
-
-        if (size > size_max)
-            size = size_max;
-
-        CopyMemory(Name, Icc -> TagPtrs[n], size);
-
-        return (int) Icc -> TagSizes[n];
-    }
-
-    offset = Icc -> TagOffsets[n];
-
-
-    if (Icc -> Seek(Icc, offset))
-            return -1;
-
-    if (ReadEmbeddedTextTag(Icc, size, Name, size_max) < 0) return -1;
-
-        return size;
-}
-
-// Keep compatibility with older versions
-
-int LCMSEXPORT cmsReadICCText(cmsHPROFILE hProfile, icTagSignature sig, char *Text)
-{
-    return cmsReadICCTextEx(hProfile, sig, Text, LCMS_DESC_MAX);
-}
-
-
-// Take an XYZ item
-
-static
-int ReadICCXYZ(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIEXYZ Value, LCMSBOOL lIsFatal)
-{
-    LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    icTagTypeSignature  BaseType;
-    size_t              offset;
-    int                 n;
-    icXYZNumber         XYZ;
-
-    n = _cmsSearchTag(Icc, sig, FALSE);
-    if (n < 0)
-            return -1;
-
-    if (Icc -> TagPtrs[n]) {
-
-         CopyMemory(Value, Icc -> TagPtrs[n], Icc -> TagSizes[n]);
-         return (int) Icc -> TagSizes[n];
-    }
-
-    offset = Icc -> TagOffsets[n];
-
-    if (Icc -> Seek(Icc, offset))
-            return -1;
-
-
-    BaseType = ReadBase(Icc);
-
-    switch (BaseType) {
-
-
-    case 0x7c3b10cL:    // Some apple broken embedded profiles does not have correct type
-    case icSigXYZType:
-
-           Icc ->Read(&XYZ, sizeof(icXYZNumber), 1, Icc);
-           Value -> X = Convert15Fixed16(XYZ.X);
-           Value -> Y = Convert15Fixed16(XYZ.Y);
-           Value -> Z = Convert15Fixed16(XYZ.Z);
-           break;
-
-    // Aug/21-2001 - Monaco 2 does have WRONG values.
-
-    default:
-           if (lIsFatal)
-                cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature %lx found.", BaseType);
-           return -1;
-    }
-
-    return 1;
-}
-
-
-// Read a icSigS15Fixed16ArrayType (currently only a 3x3 matrix)
-
-static
-int ReadICCXYZArray(cmsHPROFILE hProfile, icTagSignature sig, LPMAT3 v)
-{
-    LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    icTagTypeSignature  BaseType;
-    size_t              offset, sz;
-    int                 i, n;
-    icXYZNumber         XYZ[3];
-    cmsCIEXYZ           XYZdbl[3];
-
-
-    n = _cmsSearchTag(Icc, sig, FALSE);
-    if (n < 0)
-            return -1; // Not found
-
-    if (Icc -> TagPtrs[n]) {
-
-            CopyMemory(v, Icc -> TagPtrs[n], Icc -> TagSizes[n]);
-            return (int) Icc -> TagSizes[n];
-    }
-
-    offset = Icc -> TagOffsets[n];
-
-    if (Icc -> Seek(Icc, offset))
-            return -1;
-
-    BaseType = ReadBase(Icc);
-
-    switch (BaseType) {
-
-    case icSigS15Fixed16ArrayType:
-
-         sz = Icc ->TagSizes[n] / sizeof(icXYZNumber);
-
-         if (sz != 3) {
-             cmsSignalError(LCMS_ERRC_ABORTED, "Bad array size of %d entries.", sz);
-             return -1;
-         }
-
-         Icc ->Read(XYZ, sizeof(icXYZNumber), 3, Icc);
-
-         for (i=0; i < 3; i++) {
-
-            XYZdbl[i].X = Convert15Fixed16(XYZ[i].X);
-            XYZdbl[i].Y = Convert15Fixed16(XYZ[i].Y);
-            XYZdbl[i].Z = Convert15Fixed16(XYZ[i].Z);
-         }
-
-         CopyMemory(v, XYZdbl, 3*sizeof(cmsCIEXYZ));
-         break;
-
-    default:
-         cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature %lx found.", BaseType);
-         return -1;
-
-    }
-
-   return sizeof(MAT3);
-}
-
-
-
-// Primaries are to be in xyY notation
-
-LCMSBOOL LCMSEXPORT cmsTakeColorants(LPcmsCIEXYZTRIPLE Dest, cmsHPROFILE hProfile)
-{
-       if (ReadICCXYZ(hProfile, icSigRedColorantTag, &Dest -> Red, TRUE) < 0) return FALSE;
-       if (ReadICCXYZ(hProfile, icSigGreenColorantTag, &Dest -> Green, TRUE) < 0) return FALSE;
-       if (ReadICCXYZ(hProfile, icSigBlueColorantTag, &Dest -> Blue, TRUE) < 0) return FALSE;
-
-       return TRUE;
-}
-
-
-LCMSBOOL cmsReadICCMatrixRGB2XYZ(LPMAT3 r, cmsHPROFILE hProfile)
-{
-       cmsCIEXYZTRIPLE Primaries;
-
-       if (!cmsTakeColorants(&Primaries, hProfile)) return FALSE;
-
-       VEC3init(&r -> v[0], Primaries.Red.X, Primaries.Green.X,  Primaries.Blue.X);
-       VEC3init(&r -> v[1], Primaries.Red.Y, Primaries.Green.Y,  Primaries.Blue.Y);
-       VEC3init(&r -> v[2], Primaries.Red.Z, Primaries.Green.Z,  Primaries.Blue.Z);
-
-       return TRUE;
-
-}
-
-
-// Always return a suitable matrix
-
-LCMSBOOL cmsReadChromaticAdaptationMatrix(LPMAT3 r, cmsHPROFILE hProfile)
-{
-
-    if (ReadICCXYZArray(hProfile, icSigChromaticAdaptationTag, r) < 0) {
-
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-       // For display profiles, revert to bradford. Else take identity.
-
-       MAT3identity(r);
-
-       // Emissive devices have non-identity chad
-
-       if ((cmsGetDeviceClass(hProfile) == icSigDisplayClass) ||
-           cmsTakeHeaderFlags(hProfile) & icTransparency) {
-
-            // NULL for cone defaults to Bradford, from media to D50
-            cmsAdaptationMatrix(r, NULL, &Icc ->MediaWhitePoint, &Icc ->Illuminant);
+            return _cmsAdaptationMatrix(Dest, NULL, cmsD50_XYZ(), White);
         }
     }
 
@@ -1909,1850 +158,599 @@
 }
 
 
-
-LPGAMMATABLE LCMSEXPORT cmsReadICCGamma(cmsHPROFILE hProfile, icTagSignature sig)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-       size_t         offset;
-       int            n;
-
-
-       n = _cmsSearchTag(Icc, sig, TRUE);
-       if (n < 0)
-           return NULL;
-
-       if (Icc -> TagPtrs[n]) {
-
-            return cmsDupGamma((LPGAMMATABLE) Icc -> TagPtrs[n]);
-       }
-
-       offset = Icc -> TagOffsets[n];
-
-       if (Icc -> Seek(Icc, offset))
-            return NULL;
-
-       return ReadCurve(Icc);
-
-}
-
-
-// Some ways have analytical revese. This function accounts for that
-
-LPGAMMATABLE LCMSEXPORT cmsReadICCGammaReversed(cmsHPROFILE hProfile, icTagSignature sig)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-       size_t         offset;
-       int            n;
-
-
-       n = _cmsSearchTag(Icc, sig, TRUE);
-       if (n < 0)
-            return NULL;
-
-       if (Icc -> TagPtrs[n]) {
-
-            return cmsReverseGamma(256, (LPGAMMATABLE) Icc -> TagPtrs[n]);
-       }
-
-       offset = Icc -> TagOffsets[n];
-
-       if (Icc -> Seek(Icc, offset))
-            return NULL;
-
-       return ReadCurveReversed(Icc);
-}
-
-// Check Named color header
-
+// Auxiliar, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
 static
-LCMSBOOL CheckHeader(LPcmsNAMEDCOLORLIST v, icNamedColor2* nc2)
-{
-    if (v ->Prefix[0] == 0 && v ->Suffix[0] == 0 && v ->ColorantCount == 0) return TRUE;
-
-    if (stricmp(v ->Prefix, (const char*) nc2 ->prefix) != 0) return FALSE;
-    if (stricmp(v ->Suffix, (const char*) nc2 ->suffix) != 0) return FALSE;
-
-    return ((int) v ->ColorantCount == (int) nc2 ->nDeviceCoords);
-}
-
-// Read named color list
-
-int cmsReadICCnamedColorList(cmsHTRANSFORM xform, cmsHPROFILE hProfile, icTagSignature sig)
+cmsBool ReadICCMatrixRGB2XYZ(cmsMAT3* r, cmsHPROFILE hProfile)
 {
-       _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
-       LPLCMSICCPROFILE   Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-       int                n;
-       icTagTypeSignature BaseType;
-       size_t             offset;
-
-       n = _cmsSearchTag(Icc, sig, TRUE);
-       if (n < 0)
-            return 0;
-
-       if (Icc -> TagPtrs[n]) {
-
-            // This replaces actual named color list.
-            size_t size   = Icc -> TagSizes[n];
-
-            if (v ->NamedColorList) cmsFreeNamedColorList(v ->NamedColorList);
-            v -> NamedColorList = (LPcmsNAMEDCOLORLIST) _cmsMalloc(size);
-            CopyMemory(v -> NamedColorList, Icc ->TagPtrs[n], size);
-            return v ->NamedColorList->nColors;
-       }
-
-       offset = Icc -> TagOffsets[n];
-
-       if (Icc -> Seek(Icc, offset))
-            return 0;
-
-       BaseType = ReadBase(Icc);
-
-       switch (BaseType) {
-
-        // I never have seen one of these. Probably is not worth of implementing.
-
-       case icSigNamedColorType: {
-
-              cmsSignalError(LCMS_ERRC_WARNING, "Ancient named color profiles are not supported.");
-              return 0;
-            }
-
-        // The named color struct
-
-       case icSigNamedColor2Type: {
-
-                icNamedColor2 nc2;
-                unsigned int i, j;
-
-                if (Icc -> Read(&nc2, sizeof(icNamedColor2) - SIZEOF_UINT8_ALIGNED, 1, Icc) != 1) return 0;
-                AdjustEndianess32((LPBYTE) &nc2.vendorFlag);
-                AdjustEndianess32((LPBYTE) &nc2.count);
-                AdjustEndianess32((LPBYTE) &nc2.nDeviceCoords);
-
-                if (!CheckHeader(v->NamedColorList, &nc2)) {
-                     cmsSignalError(LCMS_ERRC_WARNING, "prefix/suffix/device for named color profiles mismatch.");
-                     return 0;
-                }
-
-                if (nc2.nDeviceCoords > MAXCHANNELS) {
-                          cmsSignalError(LCMS_ERRC_WARNING, "Too many device coordinates.");
-                          return 0;
-                }
-
-                strncpy(v ->NamedColorList->Prefix, (const char*) nc2.prefix, 32);
-                strncpy(v ->NamedColorList->Suffix, (const char*) nc2.suffix, 32);
-                v ->NamedColorList->Prefix[32] = v->NamedColorList->Suffix[32] = 0;
-
-                v ->NamedColorList ->ColorantCount = nc2.nDeviceCoords;
-
-                for (i=0; i < nc2.count; i++) {
-
-                    WORD PCS[3];
-                    WORD Colorant[MAXCHANNELS];
-                    char Root[33];
-
-                    ZeroMemory(Colorant, sizeof(WORD) * MAXCHANNELS);
-                    Icc -> Read(Root, 1, 32, Icc);
-                    Icc -> Read(PCS,  3, sizeof(WORD), Icc);
-
-                    for (j=0; j < 3; j++)
-                        AdjustEndianess16((LPBYTE) &PCS[j]);
-
-                    Icc -> Read(Colorant, sizeof(WORD), nc2.nDeviceCoords, Icc);
-
-                    for (j=0; j < nc2.nDeviceCoords; j++)
-                            AdjustEndianess16((LPBYTE) &Colorant[j]);
-
-                    cmsAppendNamedColor(v, Root, PCS, Colorant);
-                }
-
-            return v ->NamedColorList->nColors;
-            }
-            break;
-
-       default:
-              cmsSignalError(LCMS_ERRC_WARNING, "Bad tag signature '%lx' found.", BaseType);
-              return 0;
-       }
-
-       // It would never reach here
-       // return 0;
-}
-
-
-
-// Read colorant tables
-
-LPcmsNAMEDCOLORLIST LCMSEXPORT cmsReadColorantTable(cmsHPROFILE hProfile, icTagSignature sig)
-{
-    icInt32Number n;
-    icUInt32Number Count, i;
-    size_t offset;
-    icTagTypeSignature  BaseType;
-    LPLCMSICCPROFILE   Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    LPcmsNAMEDCOLORLIST List;
-
-    n = _cmsSearchTag(Icc, sig, FALSE);
-    if (n < 0)
-            return NULL; // Not found
-
-    if (Icc -> TagPtrs[n]) {
-
-            size_t size   = Icc -> TagSizes[n];
-            void* v = _cmsMalloc(size);
-
-            if (v == NULL) return NULL;
-            CopyMemory(v, Icc -> TagPtrs[n], size);
-            return (LPcmsNAMEDCOLORLIST) v;
-    }
-
-
-    offset = Icc -> TagOffsets[n];
-
-    if (Icc -> Seek(Icc, offset))
-            return NULL;
-
-    BaseType = ReadBase(Icc);
-
-    if (BaseType != icSigColorantTableType) {
-            cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature '%lx' found.", BaseType);
-            return NULL;
-    }
-
-
-    if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
-    AdjustEndianess32((LPBYTE) &Count);
-
-    if (Count > MAXCHANNELS) {
-        cmsSignalError(LCMS_ERRC_ABORTED, "Too many colorants '%lx'", Count);
-        return NULL;
-    }
+    cmsCIEXYZ *PtrRed, *PtrGreen, *PtrBlue;
 
-    List = cmsAllocNamedColorList(Count);
-    for (i=0; i < Count; i++) {
-
-        if (!Icc ->Read(List->List[i].Name, 1, 32 , Icc)) goto Error;
-        if (!Icc ->Read(List->List[i].PCS, sizeof(icUInt16Number), 3, Icc)) goto Error;
-        AdjustEndianessArray16(List->List[i].PCS, 3);
-    }
-
-    return List;
-
-Error:
-    cmsFreeNamedColorList(List);
-    return NULL;
-
-}
-
-
-
-// Uncooked manufacturer
-
-const char* LCMSEXPORT cmsTakeManufacturer(cmsHPROFILE hProfile)
-{
-
-    static char Manufacturer[LCMS_DESC_MAX] = "";
-
-       Manufacturer[0] = 0;
-
-       if (cmsIsTag(hProfile, icSigDeviceMfgDescTag)) {
-
-            cmsReadICCTextEx(hProfile, icSigDeviceMfgDescTag, Manufacturer, LCMS_DESC_MAX);
-       }
-
-    return Manufacturer;
-}
-
-// Uncooked model
-
-const char* LCMSEXPORT cmsTakeModel(cmsHPROFILE hProfile)
-{
-
-    static char Model[LCMS_DESC_MAX] = "";
-
-       Model[0] = 0;
-
-       if (cmsIsTag(hProfile, icSigDeviceModelDescTag)) {
-
-            cmsReadICCTextEx(hProfile, icSigDeviceModelDescTag, Model, LCMS_DESC_MAX);
-       }
-
-    return Model;
-}
-
-
-const char* LCMSEXPORT cmsTakeCopyright(cmsHPROFILE hProfile)
-{
-
-    static char Copyright[LCMS_DESC_MAX] = "";
-
-       Copyright[0] = 0;
-       if (cmsIsTag(hProfile, icSigCopyrightTag)) {
-
-            cmsReadICCTextEx(hProfile, icSigCopyrightTag, Copyright, LCMS_DESC_MAX);
-       }
-
-    return Copyright;
-}
-
-
-// We compute name with model - manufacturer
-
-const char*  LCMSEXPORT cmsTakeProductName(cmsHPROFILE hProfile)
-{
-    static char Name[LCMS_DESC_MAX*2+4];
-    char Manufacturer[LCMS_DESC_MAX], Model[LCMS_DESC_MAX];
-
-    Name[0] = '\0';
-    Manufacturer[0] = Model[0] = '\0';
-
-    if (cmsIsTag(hProfile, icSigDeviceMfgDescTag)) {
-
-        cmsReadICCTextEx(hProfile, icSigDeviceMfgDescTag, Manufacturer, LCMS_DESC_MAX);
-    }
-
-    if (cmsIsTag(hProfile, icSigDeviceModelDescTag)) {
-
-        cmsReadICCTextEx(hProfile, icSigDeviceModelDescTag, Model, LCMS_DESC_MAX);
-    }
-
-    if (!Manufacturer[0] && !Model[0]) {
-
-        if (cmsIsTag(hProfile, icSigProfileDescriptionTag)) {
-
-            cmsReadICCTextEx(hProfile, icSigProfileDescriptionTag, Name, LCMS_DESC_MAX);
-            return Name;
-        }
-        else return "{no name}";
-    }
-
-
-    if (!Manufacturer[0] ||
-            strncmp(Model, Manufacturer, 8) == 0 || strlen(Model) > 30)
-        strcpy(Name, Model);
-    else
-        sprintf(Name, "%s - %s", Model, Manufacturer);
-
-    return Name;
-
-}
+    _cmsAssert(r != NULL);
 
-
-// We compute desc with manufacturer - model
-
-const char*  LCMSEXPORT cmsTakeProductDesc(cmsHPROFILE hProfile)
-{
-       static char Name[2048];
-
-       if (cmsIsTag(hProfile, icSigProfileDescriptionTag)) {
-
-              cmsReadICCText(hProfile, icSigProfileDescriptionTag, Name);
-       }
-       else return cmsTakeProductName(hProfile);
-
-       if (strncmp(Name, "Copyrig", 7) == 0)
-              return cmsTakeProductName(hProfile);
-
-       return Name;
-}
-
-
-const char*  LCMSEXPORT cmsTakeProductInfo(cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-       static char Info[4096];
-
-       Info[0] = '\0';
-
-       if (cmsIsTag(hProfile, icSigProfileDescriptionTag))
-       {
-       char Desc[1024];
-
-       cmsReadICCText(hProfile, icSigProfileDescriptionTag, Desc);
-       strcat(Info, Desc);
-       strcat(Info, "\r\n\r\n");
-       }
-
-
-       if (cmsIsTag(hProfile, icSigCopyrightTag))
-       {
-       char Copyright[LCMS_DESC_MAX];
-
-       cmsReadICCText(hProfile, icSigCopyrightTag, Copyright);
-       strcat(Info, Copyright);
-       strcat(Info, "\r\n\r\n");
-       }
-
-
-
-// KODAK private tag... But very useful
-
-#define K007         (icTagSignature)0x4B303037
-
-       // MonCal
+    PtrRed   = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigRedColorantTag);
+    PtrGreen = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigGreenColorantTag);
+    PtrBlue  = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigBlueColorantTag);
 
-       if (cmsIsTag(hProfile, K007))
-       {
-       char MonCal[LCMS_DESC_MAX];
-
-       cmsReadICCText(hProfile, K007, MonCal);
-       strcat(Info, MonCal);
-       strcat(Info, "\r\n\r\n");
-       }
-       else
-       {
-       cmsCIEXYZ WhitePt;
-       char WhiteStr[1024];
-
-       cmsTakeMediaWhitePoint(&WhitePt, hProfile);
-       _cmsIdentifyWhitePoint(WhiteStr, &WhitePt);
-       strcat(WhiteStr, "\r\n\r\n");
-       strcat(Info, WhiteStr);
-       }
-
-
-       if (Icc -> stream) {
-              strcat(Info, Icc -> PhysicalFile);
-       }
-       return Info;
-}
-
-// Extract the target data as a big string. Does not signal if tag is not present.
-
-LCMSBOOL LCMSEXPORT cmsTakeCharTargetData(cmsHPROFILE hProfile, char** Data, size_t* len)
-{
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    int n;
-
-    *Data = NULL;
-    *len  = 0;
-
-    n = _cmsSearchTag(Icc, icSigCharTargetTag, FALSE);
-    if (n < 0) return FALSE;
-
-
-    *len =  Icc -> TagSizes[n];
-
-    // Make sure that is reasonable (600K)
-    if (*len > 600*1024) *len = 600*1024;
-
-    *Data = (char*) _cmsMalloc(*len + 1);  // Plus zero marker
-
-    if (!*Data) {
-
-        cmsSignalError(LCMS_ERRC_ABORTED, "Out of memory allocating CharTarget space!");
-        return FALSE;
-    }
-
-    if (cmsReadICCTextEx(hProfile, icSigCharTargetTag, *Data, *len) < 0)
+    if (PtrRed == NULL || PtrGreen == NULL || PtrBlue == NULL)
         return FALSE;
 
-    (*Data)[*len] = 0;  // Force a zero marker. Shouldn't be needed, but is
-                        // here to simplify things.
+    _cmsVEC3init(&r -> v[0], PtrRed -> X, PtrGreen -> X,  PtrBlue -> X);
+    _cmsVEC3init(&r -> v[1], PtrRed -> Y, PtrGreen -> Y,  PtrBlue -> Y);
+    _cmsVEC3init(&r -> v[2], PtrRed -> Z, PtrGreen -> Z,  PtrBlue -> Z);
 
     return TRUE;
 }
 
 
-
-
-LCMSBOOL LCMSEXPORT cmsTakeCalibrationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
+// Gray input pipeline
+static
+cmsPipeline* BuildGrayInputMatrixPipeline(cmsHPROFILE hProfile)
 {
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    int n;
+    cmsToneCurve *GrayTRC;
+    cmsPipeline* Lut;
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+
+    GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);
+    if (GrayTRC == NULL) return NULL;
 
-    n = _cmsSearchTag(Icc, icSigCalibrationDateTimeTag, FALSE);
-    if (n < 0) return FALSE;
+    Lut = cmsPipelineAlloc(ContextID, 1, 3);
+    if (Lut == NULL) return NULL;
+
+    if (cmsGetPCS(hProfile) == cmsSigLabData) {
 
-    if (Icc ->TagPtrs[n]) {
+        // In this case we implement the profile as an  identity matrix plus 3 tone curves
+        cmsUInt16Number Zero[2] = { 0x8080, 0x8080 };
+        cmsToneCurve* EmptyTab;
+        cmsToneCurve* LabCurves[3];
 
-        CopyMemory(Dest, Icc ->TagPtrs[n],  sizeof(struct tm));
-    }
-    else
-    {
-        icDateTimeNumber timestamp;
+        EmptyTab = cmsBuildTabulatedToneCurve16(ContextID, 2, Zero);
+
+        if (EmptyTab == NULL) {
+
+                 cmsPipelineFree(Lut);
+                 return NULL;
+        }
 
-        if (Icc -> Seek(Icc, Icc -> TagOffsets[n] + sizeof(icTagBase)))
-            return FALSE;
+        LabCurves[0] = GrayTRC;
+        LabCurves[1] = EmptyTab;
+        LabCurves[2] = EmptyTab;
+
+        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3,  1, OneToThreeInputMatrix, NULL));
+        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, LabCurves));
 
-        if (Icc ->Read(&timestamp, 1, sizeof(icDateTimeNumber), Icc) != sizeof(icDateTimeNumber))
-            return FALSE;
+        cmsFreeToneCurve(EmptyTab);
 
-        DecodeDateTimeNumber(&timestamp, Dest);
+    }
+    else  {
+       cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &GrayTRC));
+       cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3,  1, GrayInputMatrix, NULL));
     }
 
-
-    return TRUE;
+    return Lut;
 }
 
-
-
-// PSEQ Tag, used in devicelink profiles
-
-LPcmsSEQ LCMSEXPORT cmsReadProfileSequenceDescription(cmsHPROFILE hProfile)
+// RGB Matrix shaper
+static
+cmsPipeline* BuildRGBInputMatrixShaper(cmsHPROFILE hProfile)
 {
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    int n;
-    icUInt32Number     i, Count;
-    icDescStruct       DescStruct;
-    icTagTypeSignature BaseType;
-    size_t             size, offset;
-    LPcmsSEQ           OutSeq;
+    cmsPipeline* Lut;
+    cmsMAT3 Mat;
+    cmsToneCurve *Shapes[3];
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+    int i, j;
+
+    if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile)) return NULL;
+
+    // XYZ PCS in encoded in 1.15 format, and the matrix output comes in 0..0xffff range, so
+    // we need to adjust the output by a factor of (0x10000/0xffff) to put data in
+    // a 1.16 range, and then a >> 1 to obtain 1.15. The total factor is (65536.0)/(65535.0*2)
+
+    for (i=0; i < 3; i++)
+        for (j=0; j < 3; j++)
+            Mat.v[i].n[j] *= InpAdj;
 
 
-    n = _cmsSearchTag(Icc, icSigProfileSequenceDescTag, FALSE);
-    if (n < 0) return NULL;
-
-    size   = Icc -> TagSizes[n];
-    if (size < 12)  return NULL;
+    Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);
+    Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
+    Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
 
-    if (Icc -> TagPtrs[n]) {
+    if (!Shapes[0] || !Shapes[1] || !Shapes[2])
+        return NULL;
 
-            OutSeq = (LPcmsSEQ) _cmsMalloc(size);
-            if (OutSeq == NULL) return NULL;
-            CopyMemory(OutSeq, Icc ->TagPtrs[n], size);
-            return OutSeq;
+    Lut = cmsPipelineAlloc(ContextID, 3, 3);
+    if (Lut != NULL) {
+
+        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, Shapes));
+        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Mat, NULL));
     }
 
-    offset = Icc -> TagOffsets[n];
-
-    if (Icc -> Seek(Icc, offset))
-            return NULL;
-
-    BaseType = ReadBase(Icc);
+    return Lut;
+}
 
-    if (BaseType != icSigProfileSequenceDescType) return NULL;
+// Read and create a BRAND NEW MPE LUT from a given profile. All stuff dependent of version, etc
+// is adjusted here in order to create a LUT that takes care of all those details
+cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent)
+{
+    cmsTagTypeSignature OriginalType;
+    cmsTagSignature tag16    = Device2PCS16[Intent];
+    cmsTagSignature tagFloat = Device2PCSFloat[Intent];
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
-    Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
-    AdjustEndianess32((LPBYTE) &Count);
+    if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 
-    if (Count > 1000) {
-         return NULL;
+        // Floating point LUT are always V4, so no adjustment is required
+        return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
+    }
+
+    // Revert to perceptual if no tag is found
+    if (!cmsIsTag(hProfile, tag16)) {
+        tag16 = Device2PCS16[0];
     }
 
-    size = sizeof(int) + Count * sizeof(cmsPSEQDESC);
-    OutSeq = (LPcmsSEQ) _cmsMalloc(size);
-    if (OutSeq == NULL) return NULL;
+    if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
 
-    OutSeq ->n = Count;
+        // Check profile version and LUT type. Do the necessary adjustments if needed
 
-    // Get structures as well
-
-    for (i=0; i < Count; i++) {
+        // First read the tag
+        cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
+        if (Lut == NULL) return NULL;
 
-        LPcmsPSEQDESC sec = &OutSeq -> seq[i];
+        // After reading it, we have now info about the original type
+        OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
 
-        Icc -> Read(&DescStruct, sizeof(icDescStruct) - SIZEOF_UINT8_ALIGNED, 1, Icc);
+        // The profile owns the Lut, so we need to copy it
+        Lut = cmsPipelineDup(Lut);
 
-        AdjustEndianess32((LPBYTE) &DescStruct.deviceMfg);
-        AdjustEndianess32((LPBYTE) &DescStruct.deviceModel);
-        AdjustEndianess32((LPBYTE) &DescStruct.technology);
-        AdjustEndianess32((LPBYTE) &DescStruct.attributes[0]);
-        AdjustEndianess32((LPBYTE) &DescStruct.attributes[1]);
+        // We need to adjust data only for Lab16 on output
+        if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
+            return Lut;
+
+        // Add a matrix for conversion V2 to V4 Lab PCS
+        cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
+        return Lut;
+    }
 
-        sec ->attributes[0] = DescStruct.attributes[0];
-        sec ->attributes[1] = DescStruct.attributes[1];
-        sec ->deviceMfg     = DescStruct.deviceMfg;
-        sec ->deviceModel   = DescStruct.deviceModel;
-        sec ->technology    = DescStruct.technology;
+    // Lut was not found, try to create a matrix-shaper
 
-        if (ReadEmbeddedTextTag(Icc, size, sec ->Manufacturer, LCMS_DESC_MAX) < 0) return NULL;
-        if (ReadEmbeddedTextTag(Icc, size, sec ->Model, LCMS_DESC_MAX) < 0) return NULL;
+    // Check if this is a grayscale profile.
+    if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
 
+        // if so, build appropiate conversion tables.
+        // The tables are the PCS iluminant, scaled across GrayTRC
+        return BuildGrayInputMatrixPipeline(hProfile);
     }
 
-    return OutSeq;
+    // Not gray, create a normal matrix-shaper
+    return BuildRGBInputMatrixShaper(hProfile);
 }
 
+// ---------------------------------------------------------------------------------------------------------------
 
-void LCMSEXPORT cmsFreeProfileSequenceDescription(LPcmsSEQ pseq)
+// Gray output pipeline.
+// XYZ -> Gray or Lab -> Gray. Since we only know the GrayTRC, we need to do some assumptions. Gray component will be
+// given by Y on XYZ PCS and by L* on Lab PCS, Both across inverse TRC curve.
+// The complete pipeline on XYZ is Matrix[3:1] -> Tone curve and in Lab Matrix[3:1] -> Tone Curve as well.
+
+static
+cmsPipeline* BuildGrayOutputPipeline(cmsHPROFILE hProfile)
 {
-    if (pseq)
-        _cmsFree(pseq);
+    cmsToneCurve *GrayTRC, *RevGrayTRC;
+    cmsPipeline* Lut;
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+
+    GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);
+    if (GrayTRC == NULL) return NULL;
+
+    RevGrayTRC = cmsReverseToneCurve(GrayTRC);
+    if (RevGrayTRC == NULL) return NULL;
+
+    Lut = cmsPipelineAlloc(ContextID, 3, 1);
+    if (Lut == NULL) {
+        cmsFreeToneCurve(RevGrayTRC);
+        return NULL;
+    }
+
+    if (cmsGetPCS(hProfile) == cmsSigLabData) {
+
+        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickLstarMatrix, NULL));
+    }
+    else  {
+        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickYMatrix, NULL));
+    }
+
+    cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &RevGrayTRC));
+    cmsFreeToneCurve(RevGrayTRC);
+
+    return Lut;
 }
 
 
 
 
+static
+cmsPipeline* BuildRGBOutputMatrixShaper(cmsHPROFILE hProfile)
+{
+    cmsPipeline* Lut;
+    cmsToneCurve *Shapes[3], *InvShapes[3];
+    cmsMAT3 Mat, Inv;
+    int i, j;
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
-// Read a few tags that are hardly required
+    if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile))
+        return NULL;
 
+    if (!_cmsMAT3inverse(&Mat, &Inv))
+        return NULL;
+
+    // XYZ PCS in encoded in 1.15 format, and the matrix input should come in 0..0xffff range, so
+    // we need to adjust the input by a << 1 to obtain a 1.16 fixed and then by a factor of
+    // (0xffff/0x10000) to put data in 0..0xffff range. Total factor is (2.0*65535.0)/65536.0;
 
-static
-void ReadCriticalTags(LPLCMSICCPROFILE Icc)
-{
-    cmsHPROFILE hProfile = (cmsHPROFILE) Icc;
+    for (i=0; i < 3; i++)
+        for (j=0; j < 3; j++)
+            Inv.v[i].n[j] *= OutpAdj;
+
+    Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);
+    Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
+    Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
 
-    if (Icc ->Version >= 0x4000000) {
+    if (!Shapes[0] || !Shapes[1] || !Shapes[2])
+        return NULL;
+
+    InvShapes[0] = cmsReverseToneCurve(Shapes[0]);
+    InvShapes[1] = cmsReverseToneCurve(Shapes[1]);
+    InvShapes[2] = cmsReverseToneCurve(Shapes[2]);
+
+    if (!InvShapes[0] || !InvShapes[1] || !InvShapes[2]) {
+        return NULL;
+    }
 
-        // v4 profiles
+    Lut = cmsPipelineAlloc(ContextID, 3, 3);
+    if (Lut != NULL) {
+
+        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Inv, NULL));
+        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, InvShapes));
+    }
 
-        MAT3 ChrmCanonical;
+    cmsFreeToneCurveTriple(InvShapes);
+    return Lut;
+}
+
+// Create an output MPE LUT from agiven profile. Version mismatches are handled here
+cmsPipeline* _cmsReadOutputLUT(cmsHPROFILE hProfile, int Intent)
+{
+    cmsTagTypeSignature OriginalType;
+    cmsTagSignature tag16    = PCS2Device16[Intent];
+    cmsTagSignature tagFloat = PCS2DeviceFloat[Intent];
+    cmsContext ContextID     = cmsGetProfileContextID(hProfile);
 
-         if (ReadICCXYZ(hProfile,
-                      icSigMediaWhitePointTag,
-                      &Icc ->MediaWhitePoint, FALSE) < 0) {
+    if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
+
+        // Floating point LUT are always V4, so no adjustment is required
+        return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
+    }
+
+    // Revert to perceptual if no tag is found
+    if (!cmsIsTag(hProfile, tag16)) {
+        tag16 = PCS2Device16[0];
+    }
 
-              Icc ->MediaWhitePoint = *cmsD50_XYZ();
-       }
+    if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
+
+        // Check profile version and LUT type. Do the necessary adjustments if needed
 
-       // Read media black
+        // First read the tag
+        cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
+        if (Lut == NULL) return NULL;
+
+        // After reading it, we have info about the original type
+        OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
 
-       if (ReadICCXYZ(hProfile,
-                      icSigMediaBlackPointTag,
-                      &Icc ->MediaBlackPoint, FALSE) < 0) {
+        // The profile owns the Lut, so we need to copy it
+        Lut = cmsPipelineDup(Lut);
+
+        // We need to adjust data only for Lab and Lut16 type
+        if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
+            return Lut;
+
+        // Add a matrix for conversion V4 to V2 Lab PCS
+        cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
+        return Lut;
+    }
+
+    // Lut not found, try to create a matrix-shaper
+
+    // Check if this is a grayscale profile.
+     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
 
-              Icc ->MediaBlackPoint.X = 0;
-              Icc ->MediaBlackPoint.Y = 0;
-              Icc ->MediaBlackPoint.X = 0;
+              // if so, build appropiate conversion tables.
+              // The tables are the PCS iluminant, scaled across GrayTRC
+              return BuildGrayOutputPipeline(hProfile);
+    }
+
+    // Not gray, create a normal matrix-shaper
+    return BuildRGBOutputMatrixShaper(hProfile);
+}
+
+// ---------------------------------------------------------------------------------------------------------------
 
-       }
+// This one includes abstract profiles as well. Matrix-shaper cannot be obtained on that device class. The
+// tag name here may default to AToB0
+cmsPipeline* _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent)
+{
+    cmsPipeline* Lut;
+    cmsTagTypeSignature OriginalType;
+    cmsTagSignature tag16    = Device2PCS16[Intent];
+    cmsTagSignature tagFloat = Device2PCSFloat[Intent];
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+
+    if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 
-       NormalizeXYZ(&Icc ->MediaWhitePoint);
-       NormalizeXYZ(&Icc ->MediaBlackPoint);
+        // Floating point LUT are always V4, no adjustment is required
+        return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
+    }
+
+    tagFloat = Device2PCSFloat[0];
+    if (cmsIsTag(hProfile, tagFloat)) {
 
-      if (ReadICCXYZArray(hProfile,
-                                icSigChromaticAdaptationTag,
-                                &ChrmCanonical) > 0) {
+        return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
+    }
+
+    if (!cmsIsTag(hProfile, tag16)) {  // Is there any LUT-Based table?
+
+        tag16    = Device2PCS16[0];
+        if (!cmsIsTag(hProfile, tag16)) return NULL;
+    }
+
+    // Check profile version and LUT type. Do the necessary adjustments if needed
 
-                MAT3inverse(&ChrmCanonical, &Icc ->ChromaticAdaptation);
+    // Read the tag
+    Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
+    if (Lut == NULL) return NULL;
+
+    // The profile owns the Lut, so we need to copy it
+    Lut = cmsPipelineDup(Lut);
+
+    // After reading it, we have info about the original type
+    OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
 
-      }
-      else {
+    // We need to adjust data for Lab16 on output
+    if (OriginalType != cmsSigLut16Type) return Lut;
+
+    // Here it is possible to get Lab on both sides
 
-                MAT3identity(&Icc ->ChromaticAdaptation);
-      }
+    if (cmsGetPCS(hProfile) == cmsSigLabData) {
+            cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
+    }
+
+    if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
+            cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
+    }
+
+    return Lut;
 
 
-      // Convert media white, black to absolute under original illuminant
+}
 
-      EvalCHRM(&Icc ->MediaWhitePoint, &Icc ->ChromaticAdaptation, &Icc ->MediaWhitePoint);
-      EvalCHRM(&Icc ->MediaBlackPoint, &Icc ->ChromaticAdaptation, &Icc ->MediaBlackPoint);
+// ---------------------------------------------------------------------------------------------------------------
 
+// Returns TRUE if the profile is implemented as matrix-shaper
+cmsBool  CMSEXPORT cmsIsMatrixShaper(cmsHPROFILE hProfile)
+{
+    switch (cmsGetColorSpace(hProfile)) {
 
-    }
-    else {
-
-        // v2 profiles
+    case cmsSigGrayData:
 
-       // Read media white
+        return cmsIsTag(hProfile, cmsSigGrayTRCTag);
+
+    case cmsSigRgbData:
 
-       if (ReadICCXYZ(hProfile,
-                      icSigMediaWhitePointTag,
-                      &Icc ->MediaWhitePoint, FALSE) < 0) {
+        return (cmsIsTag(hProfile, cmsSigRedColorantTag) &&
+                cmsIsTag(hProfile, cmsSigGreenColorantTag) &&
+                cmsIsTag(hProfile, cmsSigBlueColorantTag) &&
+                cmsIsTag(hProfile, cmsSigRedTRCTag) &&
+                cmsIsTag(hProfile, cmsSigGreenTRCTag) &&
+                cmsIsTag(hProfile, cmsSigBlueTRCTag));
 
-              Icc ->MediaWhitePoint = *cmsD50_XYZ();
-       }
-
-       // Read media black
+    default:
 
-       if (ReadICCXYZ(hProfile,
-                      icSigMediaBlackPointTag,
-                      &Icc ->MediaBlackPoint, FALSE) < 0) {
+        return FALSE;
+    }
+}
 
-              Icc ->MediaBlackPoint.X = 0;
-              Icc ->MediaBlackPoint.Y = 0;
-              Icc ->MediaBlackPoint.X = 0;
+// Returns TRUE if the intent is implemented as CLUT
+cmsBool  CMSEXPORT cmsIsCLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent, int UsedDirection)
+{
+    const cmsTagSignature* TagTable;
 
-       }
-
-       NormalizeXYZ(&Icc ->MediaWhitePoint);
-       NormalizeXYZ(&Icc ->MediaBlackPoint);
-
+    // For devicelinks, the supported intent is that one stated in the header
+    if (cmsGetDeviceClass(hProfile) == cmsSigLinkClass) {
+            return (cmsGetHeaderRenderingIntent(hProfile) == Intent);
+    }
 
-       // Take Bradford as default for Display profiles only.
+    switch (UsedDirection) {
 
-       if (cmsGetDeviceClass(hProfile) == icSigDisplayClass) {
-
+       case LCMS_USED_AS_INPUT: TagTable = Device2PCS16; break;
+       case LCMS_USED_AS_OUTPUT:TagTable = PCS2Device16; break;
 
-            cmsAdaptationMatrix(&Icc -> ChromaticAdaptation,
-                                NULL,
-                                &Icc -> Illuminant,
-                                &Icc -> MediaWhitePoint);
-       }
-       else
-            MAT3identity(&Icc ->ChromaticAdaptation);
+       // For proofing, we need rel. colorimetric in output. Let's do some recursion
+       case LCMS_USED_AS_PROOF:
+           return cmsIsIntentSupported(hProfile, Intent, LCMS_USED_AS_INPUT) &&
+                  cmsIsIntentSupported(hProfile, INTENT_RELATIVE_COLORIMETRIC, LCMS_USED_AS_OUTPUT);
 
+       default:
+           cmsSignalError(cmsGetProfileContextID(hProfile), cmsERROR_RANGE, "Unexpected direction (%d)", UsedDirection);
+           return FALSE;
     }
 
+    return cmsIsTag(hProfile, TagTable[Intent]);
+
 }
 
 
-// Create profile from disk file
-
-cmsHPROFILE LCMSEXPORT cmsOpenProfileFromFile(const char *lpFileName, const char *sAccess)
+// Return info about supported intents
+cmsBool  CMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
+                                        cmsUInt32Number Intent, int UsedDirection)
 {
-       LPLCMSICCPROFILE NewIcc;
-       cmsHPROFILE hEmpty;
-
-
-       // Open for write means an empty profile
-
-       if (*sAccess == 'W' || *sAccess == 'w') {
-
-           hEmpty = _cmsCreateProfilePlaceholder();
-           NewIcc = (LPLCMSICCPROFILE) (LPSTR) hEmpty;
-           NewIcc -> IsWrite = TRUE;
-           strncpy(NewIcc ->PhysicalFile, lpFileName, MAX_PATH-1);
-           NewIcc ->PhysicalFile[MAX_PATH-1] = 0;
-
-           // Save LUT as 8 bit
 
-           sAccess++;
-           if (*sAccess == '8') NewIcc ->SaveAs8Bits = TRUE;
-
-           return hEmpty;
-       }
-
-
-       // Open for read means a file placeholder
-
-       NewIcc = _cmsCreateProfileFromFilePlaceholder(lpFileName);
-        if (!NewIcc) return NULL;
-
-       if (!ReadHeader(NewIcc, FALSE)) return NULL;
-
-       ReadCriticalTags(NewIcc);
-
-       return (cmsHPROFILE) (LPSTR) NewIcc;
-}
-
-
-
-
-// Open from memory block
+    if (cmsIsCLUT(hProfile, Intent, UsedDirection)) return TRUE;
 
-cmsHPROFILE LCMSEXPORT cmsOpenProfileFromMem(LPVOID MemPtr, DWORD dwSize)
-{
-       LPLCMSICCPROFILE NewIcc;
-
-
-       NewIcc = _cmsCreateProfileFromMemPlaceholder(MemPtr, dwSize);
-       if (!NewIcc) return NULL;
-
-       if (!ReadHeader(NewIcc, TRUE)) return NULL;
-
-       ReadCriticalTags(NewIcc);
-
-       return (cmsHPROFILE) (LPSTR) NewIcc;
-
-}
-
-
+    // Is there any matrix-shaper? If so, the intent is supported. This is a bit odd, since V2 matrix shaper
+    // does not fully support relative colorimetric because they cannot deal with non-zero black points, but
+    // many profiles claims that, and this is certainly not true for V4 profiles. Lets answer "yes" no matter
+    // the accuracy would be less than optimal in rel.col and v2 case.
 
-LCMSBOOL LCMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
-{
-       LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-       LCMSBOOL rc = TRUE;
-       icInt32Number i;
-
-       if (!Icc) return FALSE;
-
-       // Was open in write mode?
-       if (Icc ->IsWrite) {
-
-           Icc ->IsWrite = FALSE;      // Assure no further writting
-           rc = _cmsSaveProfile(hProfile, Icc ->PhysicalFile);
-       }
-
-       for (i=0; i < Icc -> TagCount; i++) {
-
-                  if (Icc -> TagPtrs[i])
-                            free(Icc -> TagPtrs[i]);
-       }
-
-       if (Icc -> stream != NULL) {     // Was a memory (i.e. not serialized) profile?
-                 Icc -> Close(Icc);     // No, close the stream
-       }
-
-       free(Icc);   // Free placeholder memory
-
-       return rc;
+    return cmsIsMatrixShaper(hProfile);
 }
 
 
-
-// Write profile ------------------------------------------------------------
-
+// ---------------------------------------------------------------------------------------------------------------
 
+// Read both, profile sequence description and profile sequence id if present. Then combine both to
+// create qa unique structure holding both. Shame on ICC to store things in such complicated way.
 
-static
-LCMSBOOL SaveWordsTable(int nEntries, LPWORD Tab, LPLCMSICCPROFILE Icc)
+cmsSEQ* _cmsReadProfileSequence(cmsHPROFILE hProfile)
 {
-   size_t nTabSize = sizeof(WORD) * nEntries;
-   LPWORD PtrW = (LPWORD) _cmsMalloc(nTabSize);
-   LCMSBOOL rc;
+    cmsSEQ* ProfileSeq;
+    cmsSEQ* ProfileId;
+    cmsSEQ* NewSeq;
+    cmsUInt32Number i;
+
+    // Take profile sequence description first
+    ProfileSeq = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceDescTag);
+
+    // Take profile sequence ID
+    ProfileId  = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceIdTag);
+
+    if (ProfileSeq == NULL && ProfileId == NULL) return NULL;
 
-   if (!PtrW) return FALSE;
-   CopyMemory(PtrW, Tab, nTabSize);
-   AdjustEndianessArray16(PtrW, nEntries);
-   rc = Icc ->Write(Icc, nTabSize, PtrW);
-   free(PtrW);
+    if (ProfileSeq == NULL) return cmsDupProfileSequenceDescription(ProfileId);
+    if (ProfileId  == NULL) return cmsDupProfileSequenceDescription(ProfileSeq);
+
+    // We have to mix both together. For that they must agree
+    if (ProfileSeq ->n != ProfileId ->n) return cmsDupProfileSequenceDescription(ProfileSeq);
+
+    NewSeq = cmsDupProfileSequenceDescription(ProfileSeq);
 
-   return rc;
+    // Ok, proceed to the mixing
+    for (i=0; i < ProfileSeq ->n; i++) {
+
+        memmove(&NewSeq ->seq[i].ProfileID, &ProfileId ->seq[i].ProfileID, sizeof(cmsProfileID));
+        NewSeq ->seq[i].Description = cmsMLUdup(ProfileId ->seq[i].Description);
+    }
+
+    return NewSeq;
 }
 
-
-
-// Saves profile header
-
-static
-LCMSBOOL SaveHeader(LPLCMSICCPROFILE Icc)
+// Dump the contents of profile sequence in both tags (if v4 available)
+cmsBool _cmsWriteProfileSequence(cmsHPROFILE hProfile, const cmsSEQ* seq)
 {
-  icHeader Header;
-  time_t now = time(NULL);
-
-       Header.size        = TransportValue32((icInt32Number) Icc ->UsedSpace);
-       Header.cmmId       = TransportValue32(lcmsSignature);
-       Header.version     = TransportValue32((icInt32Number) 0x02300000);
-       Header.deviceClass = (icProfileClassSignature) TransportValue32(Icc -> DeviceClass);
-       Header.colorSpace  = (icColorSpaceSignature) TransportValue32(Icc -> ColorSpace);
-       Header.pcs         = (icColorSpaceSignature) TransportValue32(Icc -> PCS);
-
-       //   NOTE: in v4 Timestamp must be in UTC rather than in local time
-       EncodeDateTimeNumber(&Header.date, gmtime(&now));
-
-       Header.magic       = TransportValue32(icMagicNumber);
-
-#ifdef NON_WINDOWS
-       Header.platform    = (icPlatformSignature)TransportValue32(icSigMacintosh);
-#else
-       Header.platform    = (icPlatformSignature)TransportValue32(icSigMicrosoft);
-#endif
-
-       Header.flags        = TransportValue32(Icc -> flags);
-       Header.manufacturer = TransportValue32(lcmsSignature);
-       Header.model        = TransportValue32(0);
-       Header.attributes[0]= TransportValue32(Icc -> attributes);
-       Header.attributes[1]= TransportValue32(0);
-
-       Header.renderingIntent = TransportValue32(Icc -> RenderingIntent);
-
-       // Illuminant is D50
-
-       Header.illuminant.X = TransportValue32(DOUBLE_TO_FIXED(Icc -> Illuminant.X));
-       Header.illuminant.Y = TransportValue32(DOUBLE_TO_FIXED(Icc -> Illuminant.Y));
-       Header.illuminant.Z = TransportValue32(DOUBLE_TO_FIXED(Icc -> Illuminant.Z));
-
-       Header.creator      = TransportValue32(lcmsSignature);
-
-       ZeroMemory(&Header.reserved, sizeof(Header.reserved));
-
-       // Set profile ID
-       CopyMemory(Header.reserved, Icc ->ProfileID, 16);
-
-
-       Icc ->UsedSpace = 0; // Mark as begin-of-file
+    if (!cmsWriteTag(hProfile, cmsSigProfileSequenceDescTag, seq)) return FALSE;
 
-       return Icc ->Write(Icc, sizeof(icHeader), &Header);
-}
-
-
-
-// Setup base marker
-
-static
-LCMSBOOL SetupBase(icTagTypeSignature sig, LPLCMSICCPROFILE Icc)
-{
-    icTagBase  Base;
-
-    Base.sig = (icTagTypeSignature) TransportValue32(sig);
-    ZeroMemory(&Base.reserved, sizeof(Base.reserved));
-    return Icc -> Write(Icc, sizeof(icTagBase), &Base);
-}
-
-
-// Store a XYZ tag
-
-static
-LCMSBOOL SaveXYZNumber(LPcmsCIEXYZ Value, LPLCMSICCPROFILE Icc)
-{
-
-    icXYZNumber XYZ;
-
-    if (!SetupBase(icSigXYZType, Icc)) return FALSE;
+    if (cmsGetProfileVersion(hProfile) >= 4.0) {
 
-    XYZ.X = TransportValue32(DOUBLE_TO_FIXED(Value -> X));
-    XYZ.Y = TransportValue32(DOUBLE_TO_FIXED(Value -> Y));
-    XYZ.Z = TransportValue32(DOUBLE_TO_FIXED(Value -> Z));
-
-
-    return Icc -> Write(Icc, sizeof(icXYZNumber), &XYZ);
-}
-
-
-// Store a XYZ array.
-
-static
-LCMSBOOL SaveXYZArray(int n, LPcmsCIEXYZ Value, LPLCMSICCPROFILE Icc)
-{
-    int i;
-    icXYZNumber XYZ;
-
-    if (!SetupBase(icSigS15Fixed16ArrayType, Icc)) return FALSE;
-
-    for (i=0; i < n; i++) {
-
-        XYZ.X = TransportValue32(DOUBLE_TO_FIXED(Value -> X));
-        XYZ.Y = TransportValue32(DOUBLE_TO_FIXED(Value -> Y));
-        XYZ.Z = TransportValue32(DOUBLE_TO_FIXED(Value -> Z));
-
-        if (!Icc -> Write(Icc, sizeof(icXYZNumber), &XYZ)) return FALSE;
-
-        Value++;
+            if (!cmsWriteTag(hProfile, cmsSigProfileSequenceIdTag, seq)) return FALSE;
     }
 
     return TRUE;
 }
 
 
-
-// Save a gamma structure as a table
-
+// Auxiliar, read and duplicate a MLU if found.
 static
-LCMSBOOL SaveGammaTable(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
-{
-    icInt32Number Count;
-
-        if (!SetupBase(icSigCurveType, Icc)) return FALSE;
-
-        Count = TransportValue32(Gamma->nEntries);
-
-        if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
-
-        return SaveWordsTable(Gamma->nEntries, Gamma ->GammaTable, Icc);
-}
-
-
-// Save a gamma structure as a one-value
-
-static
-LCMSBOOL SaveGammaOneValue(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+cmsMLU* GetMLUFromProfile(cmsHPROFILE h, cmsTagSignature sig)
 {
-    icInt32Number Count;
-    Fixed32 GammaFixed32;
-    WORD    GammaFixed8;
-
-        if (!SetupBase(icSigCurveType, Icc)) return FALSE;
-
-        Count = TransportValue32(1);
-        if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
-
-        GammaFixed32 = DOUBLE_TO_FIXED(Gamma ->Seed.Params[0]);
-        GammaFixed8  = (WORD) ((GammaFixed32 >> 8) & 0xFFFF);
-        GammaFixed8  = TransportValue16(GammaFixed8);
-
-        return Icc ->Write(Icc, sizeof(icInt16Number), &GammaFixed8);
-}
-
-// Save a gamma structure as a parametric gamma
-
-static
-LCMSBOOL SaveGammaParametric(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
-{
-    icUInt16Number Type, Reserved;
-    int i, nParams;
-    int ParamsByType[] = { 1, 3, 4, 5, 7 };
+    cmsMLU* mlu = (cmsMLU*) cmsReadTag(h, sig);
+    if (mlu == NULL) return NULL;
 
-    if (!SetupBase(icSigParametricCurveType, Icc)) return FALSE;
-
-    nParams = ParamsByType[Gamma -> Seed.Type];
-
-    Type      = (icUInt16Number) TransportValue16((WORD) Gamma -> Seed. Type);
-    Reserved  = (icUInt16Number) TransportValue16((WORD) 0);
-
-    Icc -> Write(Icc, sizeof(icInt16Number),  &Type);
-    Icc -> Write(Icc, sizeof(icUInt16Number), &Reserved);
-
-    for (i=0; i < nParams; i++) {
-
-        icInt32Number val = TransportValue32(DOUBLE_TO_FIXED(Gamma -> Seed.Params[i]));
-        Icc ->Write(Icc, sizeof(icInt32Number), &val);
-    }
-
-
-    return TRUE;
-
-}
-
-
-// Save a gamma table
-
-static
-LCMSBOOL SaveGamma(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
-{
-        // Is the gamma curve type supported by ICC format?
-
-        if (Gamma -> Seed.Type < 0 || Gamma -> Seed.Type > 5 ||
-
-            // has been modified by user?
-
-            _cmsCrc32OfGammaTable(Gamma) != Gamma -> Seed.Crc32) {
-
-            return SaveGammaTable(Gamma, Icc);
-        }
-
-        if (Gamma -> Seed.Type == 1) return SaveGammaOneValue(Gamma, Icc);
-
-        // Only v4 profiles are allowed to hold parametric curves
-
-        if (cmsGetProfileICCversion((cmsHPROFILE) Icc) >= 0x4000000)
-                return SaveGammaParametric(Gamma, Icc);
-
-        // Defaults to save as table
-
-        return SaveGammaTable(Gamma, Icc);
-
+    return cmsMLUdup(mlu);
 }
 
-
-
-
-// Save an DESC Tag
-
-static
-LCMSBOOL SaveDescription(const char *Text, LPLCMSICCPROFILE Icc)
+// Create a sequence description out of an array of profiles
+cmsSEQ* _cmsCompileProfileSequence(cmsContext ContextID, cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[])
 {
+    cmsUInt32Number i;
+    cmsSEQ* seq = cmsAllocProfileSequenceDescription(ContextID, nProfiles);
 
-    icUInt32Number len, Count, TotalSize, AlignedSize;
-    char Filler[256];
+    if (seq == NULL) return NULL;
 
-    len = (icUInt32Number) (strlen(Text) + 1);
+    for (i=0; i < nProfiles; i++) {
 
-    // * icInt8Number         desc[count]     * NULL terminated ascii string
-    // * icUInt32Number       ucLangCode;     * UniCode language code
-    // * icUInt32Number       ucCount;        * UniCode description length
-    // * icInt16Number        ucDesc[ucCount];* The UniCode description
-    // * icUInt16Number       scCode;         * ScriptCode code
-    // * icUInt8Number        scCount;        * ScriptCode count
-    // * icInt8Number         scDesc[67];     * ScriptCode Description
+        cmsPSEQDESC* ps = &seq ->seq[i];
+        cmsHPROFILE h = hProfiles[i];
+        cmsTechnologySignature* techpt;
 
-    TotalSize = sizeof(icTagBase) + sizeof(icUInt32Number) + len +
-                sizeof(icUInt32Number) + sizeof(icUInt32Number) +
-                sizeof(icUInt16Number) + sizeof(icUInt8Number) + 67;
-
-    AlignedSize = TotalSize;  // Can be unaligned!!
-
-    if (!SetupBase(icSigTextDescriptionType, Icc)) return FALSE;
-    AlignedSize -= sizeof(icTagBase);
-
-    Count = TransportValue32(len);
-    if (!Icc ->Write(Icc, sizeof(icUInt32Number), &Count)) return FALSE;
-    AlignedSize -= sizeof(icUInt32Number);
+        cmsGetHeaderAttributes(h, &ps ->attributes);
+        cmsGetHeaderProfileID(h, ps ->ProfileID.ID8);
+        ps ->deviceMfg   = cmsGetHeaderManufacturer(h);
+        ps ->deviceModel = cmsGetHeaderModel(h);
 
-    if (!Icc ->Write(Icc, len, (LPVOID)Text)) return FALSE;
-    AlignedSize -= len;
+        techpt = (cmsTechnologySignature*) cmsReadTag(h, cmsSigTechnologyTag);
+        if (techpt == NULL)
+            ps ->technology   =  (cmsTechnologySignature) 0;
+        else
+            ps ->technology   = *techpt;
 
-    if (AlignedSize < 0)
-            AlignedSize = 0;
-    if (AlignedSize > 255)
-            AlignedSize = 255;
+        ps ->Manufacturer = GetMLUFromProfile(h,  cmsSigDeviceMfgDescTag);
+        ps ->Model        = GetMLUFromProfile(h,  cmsSigDeviceModelDescTag);
+        ps ->Description  = GetMLUFromProfile(h, cmsSigProfileDescriptionTag);
 
-    ZeroMemory(Filler, AlignedSize);
-    if (!Icc ->Write(Icc, AlignedSize, Filler)) return FALSE;
+    }
 
-    return TRUE;
+    return seq;
 }
 
-// Save an ASCII Tag
-
-static
-LCMSBOOL SaveText(const char *Text, LPLCMSICCPROFILE Icc)
-{
-    size_t len = strlen(Text) + 1;
-
-    if (!SetupBase(icSigTextType, Icc)) return FALSE;
-    if (!Icc ->Write(Icc, len, (LPVOID) Text)) return FALSE;
-    return TRUE;
-}
-
-
-// Save one of these new chromaticity values
-
-static
-LCMSBOOL SaveOneChromaticity(double x, double y, LPLCMSICCPROFILE Icc)
-{
-       Fixed32 xf, yf;
-
-       xf = TransportValue32(DOUBLE_TO_FIXED(x));
-       yf = TransportValue32(DOUBLE_TO_FIXED(y));
-
-       if (!Icc ->Write(Icc, sizeof(Fixed32), &xf)) return FALSE;
-       if (!Icc ->Write(Icc, sizeof(Fixed32), &yf)) return FALSE;
-
-       return TRUE;
-}
-
-
-// New tag added in Addendum II of old spec.
-
-static
-LCMSBOOL SaveChromaticities(LPcmsCIExyYTRIPLE chrm, LPLCMSICCPROFILE Icc)
-{
-       WORD nChans, Table;
-
-       if (!SetupBase(icSigChromaticityType, Icc)) return FALSE;
-
-       nChans = TransportValue16(3);
-       if (!Icc ->Write(Icc, sizeof(WORD) , &nChans)) return FALSE;
-       Table =  TransportValue16(0);
-       if (!Icc ->Write(Icc, sizeof(WORD) , &Table)) return FALSE;
-
-       if (!SaveOneChromaticity(chrm -> Red.x, chrm -> Red.y, Icc)) return FALSE;
-       if (!SaveOneChromaticity(chrm -> Green.x, chrm -> Green.y, Icc)) return FALSE;
-       if (!SaveOneChromaticity(chrm -> Blue.x, chrm -> Blue.y, Icc)) return FALSE;
-
-       return TRUE;
-}
+// -------------------------------------------------------------------------------------------------------------------
 
 
 static
-LCMSBOOL SaveSequenceDescriptionTag(LPcmsSEQ seq, LPLCMSICCPROFILE Icc)
+const cmsMLU* GetInfo(cmsHPROFILE hProfile, cmsInfoType Info)
 {
-    icUInt32Number nSeqs;
-    icDescStruct   DescStruct;
-    int i, n = seq ->n;
-    LPcmsPSEQDESC pseq = seq ->seq;
-
-    if (!SetupBase(icSigProfileSequenceDescType, Icc)) return FALSE;
-
-    nSeqs = TransportValue32(n);
-
-    if (!Icc ->Write(Icc, sizeof(icUInt32Number) , &nSeqs)) return FALSE;
-
-    for (i=0; i < n; i++) {
-
-        LPcmsPSEQDESC sec = pseq + i;
-
-
-        DescStruct.deviceMfg    = (icTagTypeSignature) TransportValue32(sec ->deviceMfg);
-        DescStruct.deviceModel  = (icTagTypeSignature) TransportValue32(sec ->deviceModel);
-        DescStruct.technology   = (icTechnologySignature) TransportValue32(sec ->technology);
-        DescStruct.attributes[0]= TransportValue32(sec ->attributes[0]);
-        DescStruct.attributes[1]= TransportValue32(sec ->attributes[1]);
+    cmsTagSignature sig;
 
-        if (!Icc ->Write(Icc, sizeof(icDescStruct) - SIZEOF_UINT8_ALIGNED, &DescStruct)) return FALSE;
-
-        if (!SaveDescription(sec ->Manufacturer, Icc)) return FALSE;
-        if (!SaveDescription(sec ->Model, Icc)) return FALSE;
-    }
-
-    return TRUE;
-}
-
-
-// Saves a timestamp tag
+    switch (Info) {
 
-static
-LCMSBOOL SaveDateTimeNumber(const struct tm *DateTime, LPLCMSICCPROFILE Icc)
-{
-    icDateTimeNumber Dest;
-
-    if (!SetupBase(icSigDateTimeType, Icc)) return FALSE;
-    EncodeDateTimeNumber(&Dest, DateTime);
-    if (!Icc ->Write(Icc, sizeof(icDateTimeNumber), &Dest)) return FALSE;
-
-    return TRUE;
-}
-
+    case cmsInfoDescription:
+        sig = cmsSigProfileDescriptionTag;
+        break;
 
-// Saves a named color list into a named color profile
-static
-LCMSBOOL SaveNamedColorList(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
-{
-
-    icUInt32Number      vendorFlag;     // Bottom 16 bits for IC use
-    icUInt32Number      count;          // Count of named colors
-    icUInt32Number      nDeviceCoords;  // Num of device coordinates
-    char                prefix[32];     // Prefix for each color name
-    char                suffix[32];     // Suffix for each color name
-    int i;
-
-    if (!SetupBase(icSigNamedColor2Type, Icc)) return FALSE;
-
-    vendorFlag    = TransportValue32(0);
-    count         = TransportValue32(NamedColorList ->nColors);
-    nDeviceCoords = TransportValue32(NamedColorList ->ColorantCount);
-
-    strncpy(prefix, (const char*) NamedColorList->Prefix, 31);
-    strncpy(suffix, (const char*) NamedColorList->Suffix, 31);
-
-    suffix[31] = prefix[31] = 0;
+    case cmsInfoManufacturer:
+        sig = cmsSigDeviceMfgDescTag;
+        break;
 
-    if (!Icc ->Write(Icc, sizeof(icUInt32Number), &vendorFlag)) return FALSE;
-    if (!Icc ->Write(Icc, sizeof(icUInt32Number), &count)) return FALSE;
-    if (!Icc ->Write(Icc, sizeof(icUInt32Number), &nDeviceCoords)) return FALSE;
-    if (!Icc ->Write(Icc, 32 , prefix)) return FALSE;
-    if (!Icc ->Write(Icc, 32 , suffix)) return FALSE;
-
-    for (i=0; i < NamedColorList ->nColors; i++) {
-
-          icUInt16Number  PCS[3];
-          icUInt16Number  Colorant[MAXCHANNELS];
-          char            root[32];
-          LPcmsNAMEDCOLOR Color;
-          int j;
-
-                    Color = NamedColorList ->List + i;
+    case cmsInfoModel:
+        sig = cmsSigDeviceModelDescTag;
+         break;
 
-                    strncpy(root, Color ->Name, 32);
-                    Color ->Name[32] = 0;
-
-                    if (!Icc ->Write(Icc, 32 , root)) return FALSE;
-
-                    for (j=0; j < 3; j++)
-                        PCS[j] = TransportValue16(Color ->PCS[j]);
+    case cmsInfoCopyright:
+        sig = cmsSigCopyrightTag;
+        break;
 
-                    if (!Icc ->Write(Icc, 3 * sizeof(icUInt16Number), PCS)) return FALSE;
-
-                    for (j=0; j < NamedColorList ->ColorantCount; j++)
-                        Colorant[j] = TransportValue16(Color ->DeviceColorant[j]);
-
-                    if (!Icc ->Write(Icc,
-                            NamedColorList ->ColorantCount * sizeof(icUInt16Number), Colorant)) return FALSE;
+    default: return NULL;
     }
 
 
-    return TRUE;
-}
-
-
-
-// Saves a colorant table. It is using the named color structure for simplicity sake
-
-static
-LCMSBOOL SaveColorantTable(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
-{
-     icUInt32Number count;  // Count of named colors
-     int i;
-
-     if (!SetupBase(icSigColorantTableType, Icc)) return FALSE;
-
-     count = TransportValue32(NamedColorList ->nColors);
-
-     if (!Icc ->Write(Icc, sizeof(icUInt32Number), &count)) return FALSE;
-
-     for (i=0; i < NamedColorList ->nColors; i++) {
-
-      icUInt16Number PCS[3];
-      icInt8Number root[33];
-      LPcmsNAMEDCOLOR Color;
-      int j;
-
-            Color = NamedColorList ->List + i;
-
-            strncpy((char*) root, Color ->Name, 32);
-            root[32] = 0;
-
-            if (!Icc ->Write(Icc, 32 , root)) return FALSE;
-
-            for (j=0; j < 3; j++)
-                PCS[j] = TransportValue16(Color ->PCS[j]);
-
-            if (!Icc ->Write(Icc, 3 * sizeof(icUInt16Number), PCS)) return FALSE;
-
-     }
-
-
-     return TRUE;
-}
-
-// Does serialization of LUT16 and writes it.
-
-static
-LCMSBOOL SaveLUT(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
-{
-       icLut16 LUT16;
-       unsigned int i;
-       size_t nTabSize;
-       WORD NullTbl[2] = { 0, 0xFFFFU};
-
-
-       if (!SetupBase(icSigLut16Type, Icc)) return FALSE;
-
-       LUT16.clutPoints = (icUInt8Number) NewLUT -> cLutPoints;
-       LUT16.inputChan  = (icUInt8Number) NewLUT -> InputChan;
-       LUT16.outputChan = (icUInt8Number) NewLUT -> OutputChan;
-
-       LUT16.inputEnt   = TransportValue16((WORD) ((NewLUT -> wFlags & LUT_HASTL1) ? NewLUT -> InputEntries  : 2));
-       LUT16.outputEnt  = TransportValue16((WORD) ((NewLUT -> wFlags & LUT_HASTL2) ? NewLUT -> OutputEntries : 2));
-
-       if (NewLUT -> wFlags & LUT_HASMATRIX) {
-
-           LUT16.e00 = TransportValue32(NewLUT -> Matrix.v[0].n[0]);
-           LUT16.e01 = TransportValue32(NewLUT -> Matrix.v[0].n[1]);
-           LUT16.e02 = TransportValue32(NewLUT -> Matrix.v[0].n[2]);
-           LUT16.e10 = TransportValue32(NewLUT -> Matrix.v[1].n[0]);
-           LUT16.e11 = TransportValue32(NewLUT -> Matrix.v[1].n[1]);
-           LUT16.e12 = TransportValue32(NewLUT -> Matrix.v[1].n[2]);
-           LUT16.e20 = TransportValue32(NewLUT -> Matrix.v[2].n[0]);
-           LUT16.e21 = TransportValue32(NewLUT -> Matrix.v[2].n[1]);
-           LUT16.e22 = TransportValue32(NewLUT -> Matrix.v[2].n[2]);
-           }
-       else {
-
-           LUT16.e00 = TransportValue32(DOUBLE_TO_FIXED(1));
-           LUT16.e01 = TransportValue32(DOUBLE_TO_FIXED(0));
-           LUT16.e02 = TransportValue32(DOUBLE_TO_FIXED(0));
-           LUT16.e10 = TransportValue32(DOUBLE_TO_FIXED(0));
-           LUT16.e11 = TransportValue32(DOUBLE_TO_FIXED(1));
-           LUT16.e12 = TransportValue32(DOUBLE_TO_FIXED(0));
-           LUT16.e20 = TransportValue32(DOUBLE_TO_FIXED(0));
-           LUT16.e21 = TransportValue32(DOUBLE_TO_FIXED(0));
-           LUT16.e22 = TransportValue32(DOUBLE_TO_FIXED(1));
-       }
-
-
-       // Save header
-
-       Icc -> Write(Icc,  sizeof(icLut16)- SIZEOF_UINT16_ALIGNED, &LUT16);
-
-       // The prelinearization table
-
-       for (i=0; i < NewLUT -> InputChan; i++) {
-
-        if (NewLUT -> wFlags & LUT_HASTL1) {
-
-               if (!SaveWordsTable(NewLUT -> InputEntries,
-                                   NewLUT -> L1[i], Icc)) return FALSE;
-
-        }
-        else Icc -> Write(Icc, sizeof(WORD)* 2, NullTbl);
-       }
-
-
-       nTabSize = (NewLUT -> OutputChan * uipow(NewLUT->cLutPoints,
-                                                 NewLUT->InputChan));
-       // The 3D CLUT.
-
-       if (nTabSize > 0) {
-
-             if (!SaveWordsTable((int) nTabSize, NewLUT -> T, Icc)) return FALSE;
-       }
-       // The postlinearization table
-
-       for (i=0; i < NewLUT -> OutputChan; i++) {
-
-        if (NewLUT -> wFlags & LUT_HASTL2) {
-
-                if (!SaveWordsTable(NewLUT -> OutputEntries,
-                                    NewLUT -> L2[i], Icc)) return FALSE;
-        }
-        else Icc -> Write(Icc, sizeof(WORD)* 2, NullTbl);
-
-       }
-
-        return TRUE;
+    return (cmsMLU*) cmsReadTag(hProfile, sig);
 }
 
 
 
-// Does serialization of LUT8 and writes it
-
-static
-LCMSBOOL SaveLUT8(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
+cmsUInt32Number CMSEXPORT cmsGetProfileInfo(cmsHPROFILE hProfile, cmsInfoType Info,
+                                            const char LanguageCode[3], const char CountryCode[3],
+                                            wchar_t* Buffer, cmsUInt32Number BufferSize)
 {
-       icLut8 LUT8;
-       unsigned int i, j;
-       size_t nTabSize;
-       BYTE val;
-
-       // Sanity check
-
-       if (NewLUT -> wFlags & LUT_HASTL1) {
-
-           if (NewLUT -> InputEntries != 256) {
-                cmsSignalError(LCMS_ERRC_ABORTED, "LUT8 needs 256 entries on prelinearization");
-                return FALSE;
-           }
-
-       }
-
-
-       if (NewLUT -> wFlags & LUT_HASTL2) {
-
-           if (NewLUT -> OutputEntries != 256) {
-                cmsSignalError(LCMS_ERRC_ABORTED, "LUT8 needs 256 entries on postlinearization");
-                return FALSE;
-           }
-       }
-
-
-
-       if (!SetupBase(icSigLut8Type, Icc)) return FALSE;
-
-       LUT8.clutPoints = (icUInt8Number) NewLUT -> cLutPoints;
-       LUT8.inputChan  = (icUInt8Number) NewLUT -> InputChan;
-       LUT8.outputChan = (icUInt8Number) NewLUT -> OutputChan;
-
-
-       if (NewLUT -> wFlags & LUT_HASMATRIX) {
-
-       LUT8.e00 = TransportValue32(NewLUT -> Matrix.v[0].n[0]);
-       LUT8.e01 = TransportValue32(NewLUT -> Matrix.v[0].n[1]);
-       LUT8.e02 = TransportValue32(NewLUT -> Matrix.v[0].n[2]);
-       LUT8.e10 = TransportValue32(NewLUT -> Matrix.v[1].n[0]);
-       LUT8.e11 = TransportValue32(NewLUT -> Matrix.v[1].n[1]);
-       LUT8.e12 = TransportValue32(NewLUT -> Matrix.v[1].n[2]);
-       LUT8.e20 = TransportValue32(NewLUT -> Matrix.v[2].n[0]);
-       LUT8.e21 = TransportValue32(NewLUT -> Matrix.v[2].n[1]);
-       LUT8.e22 = TransportValue32(NewLUT -> Matrix.v[2].n[2]);
-       }
-       else {
-
-       LUT8.e00 = TransportValue32(DOUBLE_TO_FIXED(1));
-       LUT8.e01 = TransportValue32(DOUBLE_TO_FIXED(0));
-       LUT8.e02 = TransportValue32(DOUBLE_TO_FIXED(0));
-       LUT8.e10 = TransportValue32(DOUBLE_TO_FIXED(0));
-       LUT8.e11 = TransportValue32(DOUBLE_TO_FIXED(1));
-       LUT8.e12 = TransportValue32(DOUBLE_TO_FIXED(0));
-       LUT8.e20 = TransportValue32(DOUBLE_TO_FIXED(0));
-       LUT8.e21 = TransportValue32(DOUBLE_TO_FIXED(0));
-       LUT8.e22 = TransportValue32(DOUBLE_TO_FIXED(1));
-       }
-
-
-       // Save header
-
-       Icc -> Write(Icc,  sizeof(icLut8)- SIZEOF_UINT8_ALIGNED, &LUT8);
-
-       // The prelinearization table
-
-       for (i=0; i < NewLUT -> InputChan; i++) {
-
-           for (j=0; j < 256; j++) {
-
-               if (NewLUT -> wFlags & LUT_HASTL1)
-                        val = (BYTE) floor(NewLUT ->L1[i][j] / 257.0 + .5);
-               else
-                        val = (BYTE) j;
+    const cmsMLU* mlu = GetInfo(hProfile, Info);
+    if (mlu == NULL) return 0;
 
-               Icc ->Write(Icc, 1, &val);
-           }
-
-       }
-
-
-       nTabSize = (NewLUT -> OutputChan * uipow(NewLUT->cLutPoints,
-                                                 NewLUT->InputChan));
-       // The 3D CLUT.
-
-       for (j=0; j < nTabSize; j++) {
-
-              val = (BYTE) floor(NewLUT ->T[j] / 257.0 + .5);
-              Icc ->Write(Icc, 1, &val);
-       }
-
-       // The postlinearization table
-
-       for (i=0; i < NewLUT -> OutputChan; i++) {
-
-           for (j=0; j < 256; j++) {
-
-               if (NewLUT -> wFlags & LUT_HASTL2)
-                    val = (BYTE) floor(NewLUT ->L2[i][j] / 257.0 + .5);
-               else
-                    val = (BYTE) j;
-
-               Icc ->Write(Icc, 1, &val);
-           }
-
-       }
-
-        return TRUE;
-}
-
-
-
-// Set the LUT bitdepth to be saved
-
-void LCMSEXPORT _cmsSetLUTdepth(cmsHPROFILE hProfile, int depth)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-
-    switch (depth) {
-
-    case 8:  Icc ->SaveAs8Bits = TRUE; break;
-    case 16: Icc ->SaveAs8Bits = FALSE; break;
-
-    default:
-        cmsSignalError(LCMS_ERRC_ABORTED, "%d is an unsupported as bitdepth, use 8 or 16 only.", depth);
-    }
-}
-
-
-// Saves Tag directory
-
-static
-LCMSBOOL SaveTagDirectory(LPLCMSICCPROFILE Icc)
-{
-       icInt32Number i;
-       icTag Tag;
-       icInt32Number Count = 0;
-
-       // Get true count
-       for (i=0;  i < Icc -> TagCount; i++) {
-            if (Icc ->TagNames[i] != 0)
-                    Count++;
-       }
-
-       Count = TransportValue32(Count);
-       if (!Icc ->Write(Icc, sizeof(icInt32Number) , &Count)) return FALSE;
-
-       for (i=0; i < Icc -> TagCount; i++) {
-
-          if (Icc ->TagNames[i] == 0) continue;
-
-          Tag.sig    = (icTagSignature)TransportValue32(Icc -> TagNames[i]);
-          Tag.offset = TransportValue32((icInt32Number) Icc -> TagOffsets[i]);
-          Tag.size   = TransportValue32((icInt32Number) Icc -> TagSizes[i]);
-
-          if (!Icc ->Write(Icc, sizeof(icTag), &Tag)) return FALSE;
-       }
-
-       return TRUE;
+    return cmsMLUgetWide(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
 }
 
 
-// Dump tag contents
-
-static
-LCMSBOOL SaveTags(LPLCMSICCPROFILE Icc, LPLCMSICCPROFILE FileOrig)
+cmsUInt32Number  CMSEXPORT cmsGetProfileInfoASCII(cmsHPROFILE hProfile, cmsInfoType Info,
+                                                          const char LanguageCode[3], const char CountryCode[3],
+                                                          char* Buffer, cmsUInt32Number BufferSize)
 {
-
-    LPBYTE Data;
-    icInt32Number i;
-    size_t Begin;
-    size_t AlignedSpace, FillerSize;
-
-
-    for (i=0; i < Icc -> TagCount; i++) {
-
-         if (Icc ->TagNames[i] == 0) continue;
-
-        // Align to DWORD boundary, following new spec.
-
-        AlignedSpace = ALIGNLONG(Icc ->UsedSpace);
-        FillerSize  = AlignedSpace - Icc ->UsedSpace;
-        if (FillerSize > 0)  {
-
-            BYTE Filler[20];
-
-            ZeroMemory(Filler, 16);
-            if (!Icc ->Write(Icc, FillerSize, Filler)) return FALSE;
-        }
-
-
-       Icc -> TagOffsets[i] = Begin = Icc ->UsedSpace;
-       Data = (LPBYTE) Icc -> TagPtrs[i];
-       if (!Data) {
-
-           // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user.
-           // In this case a blind copy of the block data is performed
-
-           if (Icc -> TagOffsets[i]) {
-
-                    size_t TagSize   = FileOrig -> TagSizes[i];
-                    size_t TagOffset = FileOrig -> TagOffsets[i];
-                    void* Mem;
-
-                    if (FileOrig ->Seek(FileOrig, TagOffset)) return FALSE;
-
-                    Mem = _cmsMalloc(TagSize);
-
-                    if (FileOrig ->Read(Mem, TagSize, 1, FileOrig) != 1) return FALSE;
-                    if (!Icc ->Write(Icc, TagSize, Mem)) return FALSE;
-
-                    Icc -> TagSizes[i] = (Icc ->UsedSpace - Begin);
-                    free(Mem);
-           }
-
-              continue;
-       }
-
-
-       switch (Icc -> TagNames[i]) {
-
-       case icSigProfileDescriptionTag:
-       case icSigDeviceMfgDescTag:
-       case icSigDeviceModelDescTag:
-              if (!SaveDescription((const char *) Data, Icc)) return FALSE;
-              break;
-
-       case icSigRedColorantTag:
-       case icSigGreenColorantTag:
-       case icSigBlueColorantTag:
-       case icSigMediaWhitePointTag:
-       case icSigMediaBlackPointTag:
-               if (!SaveXYZNumber((LPcmsCIEXYZ) Data, Icc)) return FALSE;
-               break;
-
-
-       case icSigRedTRCTag:
-       case icSigGreenTRCTag:
-       case icSigBlueTRCTag:
-       case icSigGrayTRCTag:
-               if (!SaveGamma((LPGAMMATABLE) Data, Icc)) return FALSE;
-               break;
-
-       case icSigCharTargetTag:
-       case icSigCopyrightTag:
-              if (!SaveText((const char *) Data, Icc)) return FALSE;
-              break;
-
-       case icSigChromaticityTag:
-              if (!SaveChromaticities((LPcmsCIExyYTRIPLE) Data, Icc)) return FALSE;
-              break;
-
-       // Save LUT
-
-       case icSigAToB0Tag:
-       case icSigAToB1Tag:
-       case icSigAToB2Tag:
-       case icSigBToA0Tag:
-       case icSigBToA1Tag:
-       case icSigBToA2Tag:
-       case icSigGamutTag:
-       case icSigPreview0Tag:
-       case icSigPreview1Tag:
-       case icSigPreview2Tag:
-
-                if (Icc ->SaveAs8Bits) {
-
-                        if (!SaveLUT8((LPLUT) Data, Icc)) return FALSE;
-                }
-                else {
-
-                        if (!SaveLUT((LPLUT) Data, Icc)) return FALSE;
-                }
-                break;
-
-       case icSigProfileSequenceDescTag:
-              if (!SaveSequenceDescriptionTag((LPcmsSEQ) Data, Icc)) return FALSE;
-              break;
-
-
-       case icSigNamedColor2Tag:
-             if (!SaveNamedColorList((LPcmsNAMEDCOLORLIST) Data, Icc)) return FALSE;
-             break;
-
-
-       case icSigCalibrationDateTimeTag:
-             if (!SaveDateTimeNumber((struct tm *) Data, Icc)) return FALSE;
-             break;
-
-
-       case icSigColorantTableTag:
-       case icSigColorantTableOutTag:
-             if (!SaveColorantTable((LPcmsNAMEDCOLORLIST) Data, Icc)) return FALSE;
-             break;
-
-
-       case icSigChromaticAdaptationTag:
-              if (!SaveXYZArray(3, (LPcmsCIEXYZ) Data, Icc)) return FALSE;
-              break;
-
-       default:
-              return FALSE;
-       }
-
-       Icc -> TagSizes[i] = (Icc ->UsedSpace - Begin);
-       }
-
-
-
-       return TRUE;
-}
-
-
-
-// Add tags to profile structure
-
-LCMSBOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hProfile, icTagSignature sig, const void* Tag)
-{
-   LCMSBOOL rc;
-
-   switch (sig) {
-
-       case icSigCharTargetTag:
-       case icSigCopyrightTag:
-       case icSigProfileDescriptionTag:
-       case icSigDeviceMfgDescTag:
-       case icSigDeviceModelDescTag:
-              rc = _cmsAddTextTag(hProfile, sig, (const char*) Tag);
-              break;
+    const cmsMLU* mlu = GetInfo(hProfile, Info);
+    if (mlu == NULL) return 0;
 
-       case icSigRedColorantTag:
-       case icSigGreenColorantTag:
-       case icSigBlueColorantTag:
-       case icSigMediaWhitePointTag:
-       case icSigMediaBlackPointTag:
-              rc = _cmsAddXYZTag(hProfile, sig, (const cmsCIEXYZ*) Tag);
-              break;
-
-       case icSigRedTRCTag:
-       case icSigGreenTRCTag:
-       case icSigBlueTRCTag:
-       case icSigGrayTRCTag:
-              rc =  _cmsAddGammaTag(hProfile, sig, (LPGAMMATABLE) Tag);
-              break;
-
-       case icSigAToB0Tag:
-       case icSigAToB1Tag:
-       case icSigAToB2Tag:
-       case icSigBToA0Tag:
-       case icSigBToA1Tag:
-       case icSigBToA2Tag:
-       case icSigGamutTag:
-       case icSigPreview0Tag:
-       case icSigPreview1Tag:
-       case icSigPreview2Tag:
-              rc =  _cmsAddLUTTag(hProfile, sig, Tag);
-              break;
-
-       case icSigChromaticityTag:
-              rc =  _cmsAddChromaticityTag(hProfile, sig, (LPcmsCIExyYTRIPLE) Tag);
-              break;
-
-       case icSigProfileSequenceDescTag:
-              rc = _cmsAddSequenceDescriptionTag(hProfile, sig, (LPcmsSEQ) Tag);
-              break;
-
-       case icSigNamedColor2Tag:
-              rc = _cmsAddNamedColorTag(hProfile, sig, (LPcmsNAMEDCOLORLIST) Tag);
-             break;
-
-       case icSigCalibrationDateTimeTag:
-              rc = _cmsAddDateTimeTag(hProfile, sig, (struct tm*) Tag);
-              break;
-
-       case icSigColorantTableTag:
-       case icSigColorantTableOutTag:
-              rc = _cmsAddColorantTableTag(hProfile, sig, (LPcmsNAMEDCOLORLIST) Tag);
-              break;
-
-
-       case icSigChromaticAdaptationTag:
-              rc = _cmsAddChromaticAdaptationTag(hProfile, sig, (const cmsCIEXYZ*) Tag);
-              break;
-
-       default:
-            cmsSignalError(LCMS_ERRC_ABORTED, "cmsAddTag: Tag '%x' is unsupported", sig);
-            return FALSE;
-   }
-
-   // Check for critical tags
-
-   switch (sig) {
-
-   case icSigMediaWhitePointTag:
-   case icSigMediaBlackPointTag:
-   case icSigChromaticAdaptationTag:
-
-        ReadCriticalTags((LPLCMSICCPROFILE) hProfile);
-        break;
-
-   default:;
-   }
-
-   return rc;
-
+    return cmsMLUgetASCII(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
 }
-
-// Low-level save to disk. It closes the profile on exit
-
-LCMSBOOL LCMSEXPORT _cmsSaveProfile(cmsHPROFILE hProfile, const char* FileName)
-{
-       LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-       LCMSICCPROFILE Keep;
-       LCMSBOOL rc;
-
-        CopyMemory(&Keep, Icc, sizeof(LCMSICCPROFILE));
-       _cmsSetSaveToDisk(Icc, NULL);
-
-       // Pass #1 does compute offsets
-
-       if (!SaveHeader(Icc)) return FALSE;
-       if (!SaveTagDirectory(Icc)) return FALSE;
-       if (!SaveTags(Icc, &Keep)) return FALSE;
-
-
-       _cmsSetSaveToDisk(Icc, FileName);
-
-
-       // Pass #2 does save to file
-
-       if (!SaveHeader(Icc)) goto CleanUp;
-       if (!SaveTagDirectory(Icc)) goto CleanUp;
-       if (!SaveTags(Icc, &Keep)) goto CleanUp;
-
-       rc = (Icc ->Close(Icc) == 0);
-       CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
-       return rc;
-
-
-   CleanUp:
-
-       Icc ->Close(Icc);
-       unlink(FileName);
-       CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
-       return FALSE;
-}
-
-
-// Low-level save from open stream
-LCMSBOOL LCMSEXPORT _cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr,
-                                                           size_t* BytesNeeded)
-{
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    LCMSICCPROFILE Keep;
-
-
-    CopyMemory(&Keep, Icc, sizeof(LCMSICCPROFILE));
-
-    _cmsSetSaveToMemory(Icc, NULL, 0);
-
-    // Pass #1 does compute offsets
-
-    if (!SaveHeader(Icc)) return FALSE;
-    if (!SaveTagDirectory(Icc)) return FALSE;
-    if (!SaveTags(Icc, &Keep)) return FALSE;
-
-    if (!MemPtr) {
-
-        // update BytesSaved so caller knows how many bytes are needed for MemPtr
-        *BytesNeeded = Icc ->UsedSpace;
-        CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
-        return TRUE;
-    }
-
-    if (*BytesNeeded < Icc ->UsedSpace) {
-
-        // need at least UsedSpace in MemPtr to continue
-        CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
-        return FALSE;
-    }
-
-    _cmsSetSaveToMemory(Icc, MemPtr, *BytesNeeded);
-
-
-    // Pass #2 does save to file into supplied stream
-    if (!SaveHeader(Icc)) goto CleanUp;
-    if (!SaveTagDirectory(Icc)) goto CleanUp;
-    if (!SaveTags(Icc, &Keep)) goto CleanUp;
-
-    // update BytesSaved so caller knows how many bytes put into stream
-    *BytesNeeded = Icc ->UsedSpace;
-
-    Icc ->Close(Icc);
-    CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
-    return TRUE;
-
-CleanUp:
-
-    Icc ->Close(Icc);
-    CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
-    return FALSE;
-}
-
--- a/src/share/native/sun/java2d/cmm/lcms/cmslut.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmslut.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,630 +49,1430 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-#include "lcms.h"
-
-//  Pipeline of LUT. Enclosed by {} are new revision 4.0 of ICC spec.
 //
-//  [Mat] -> [L1] -> { [Mat3] -> [Ofs3] -> [L3] ->} [CLUT] { -> [L4] -> [Mat4] -> [Ofs4] } -> [L2]
-//
-//  Some of these stages would be missing. This implements the totality of
-//  combinations of old and new LUT types as follows:
-//
-//  Lut8 & Lut16
-//  ============
-//     [Mat] -> [L1] -> [CLUT] -> [L2]
-//
-//  Mat2, Ofs2, L3, L3, Mat3, Ofs3 are missing
-//
-//  LutAToB
-//  ========
-//
-//  [L1] -> [CLUT] -> [L4] -> [Mat4] -> [Ofs4] -> [L2]
-//
-//  Mat, Mat3, Ofs3, L3 are missing
-//   L1 = A curves
-//   L4 = M curves
-//   L2 = B curves
-//
-//  LutBToA
-//  =======
-//
-//  [L1] -> [Mat3] -> [Ofs3] -> [L3] -> [CLUT] -> [L2]
+//---------------------------------------------------------------------------------
 //
-//  Mat, L4, Mat4, Ofs4 are missing
-//   L1 = B Curves
-//   L3 = M Curves
-//   L2 = A curves
-//
-//
-//  V2&3 emulation
-//  ===============
-//
-//  For output, Mat is multiplied by
-//
-//
-//  | 0xff00 / 0xffff      0                    0           |
-//  |        0          0xff00 / 0xffff         0           |
-//  |        0             0                0xff00 / 0xffff |
-//
-//
-//  For input, an additional matrix is needed at the very last end of the chain
-//
-//
-//  | 0xffff / 0xff00      0                     0        |
-//  |        0          0xffff / 0xff00          0        |
-//  |        0             0              0xffff / 0xff00 |
-//
-//
-//  Which reduces to (val * 257) >> 8
+
+#include "lcms2_internal.h"
+
+
+// Allocates an empty multi profile element
+cmsStage* CMSEXPORT _cmsStageAllocPlaceholder(cmsContext ContextID,
+                                cmsStageSignature Type,
+                                cmsUInt32Number InputChannels,
+                                cmsUInt32Number OutputChannels,
+                                _cmsStageEvalFn     EvalPtr,
+                                _cmsStageDupElemFn  DupElemPtr,
+                                _cmsStageFreeElemFn FreePtr,
+                                void*             Data)
+{
+    cmsStage* ph = (cmsStage*) _cmsMallocZero(ContextID, sizeof(cmsStage));
+
+    if (ph == NULL) return NULL;
+
+
+    ph ->ContextID = ContextID;
+
+    ph ->Type       = Type;
+    ph ->Implements = Type;   // By default, no clue on what is implementing
+
+    ph ->InputChannels  = InputChannels;
+    ph ->OutputChannels = OutputChannels;
+    ph ->EvalPtr        = EvalPtr;
+    ph ->DupElemPtr     = DupElemPtr;
+    ph ->FreePtr        = FreePtr;
+    ph ->Data           = Data;
+
+    return ph;
+}
+
 
-// A couple of macros to convert between revisions
+static
+void EvaluateIdentity(const cmsFloat32Number In[],
+                            cmsFloat32Number Out[],
+                      const cmsStage *mpe)
+{
+    memmove(Out, In, mpe ->InputChannels * sizeof(cmsFloat32Number));
+}
+
+
+cmsStage* CMSEXPORT cmsStageAllocIdentity(cmsContext ContextID, cmsUInt32Number nChannels)
+{
+    return _cmsStageAllocPlaceholder(ContextID,
+                                   cmsSigIdentityElemType,
+                                   nChannels, nChannels,
+                                   EvaluateIdentity,
+                                   NULL,
+                                   NULL,
+                                   NULL);
+ }
 
-#define FROM_V2_TO_V4(x) (((((x)<<8)+(x))+0x80)>>8)    // BY 65535 DIV 65280 ROUND
-#define FROM_V4_TO_V2(x) ((((x)<<8)+0x80)/257)         // BY 65280 DIV 65535 ROUND
+// Conversion functions. From floating point to 16 bits
+static
+void FromFloatTo16(const cmsFloat32Number In[], cmsUInt16Number Out[], cmsUInt32Number n)
+{
+    cmsUInt32Number i;
+
+    for (i=0; i < n; i++) {
+        Out[i] = _cmsQuickSaturateWord(In[i] * 65535.0);
+    }
+}
+
+// From 16 bits to floating point
+static
+void From16ToFloat(const cmsUInt16Number In[], cmsFloat32Number Out[], cmsUInt32Number n)
+{
+    cmsUInt32Number i;
+
+    for (i=0; i < n; i++) {
+        Out[i] = (cmsFloat32Number) In[i] / 65535.0F;
+    }
+}
 
 
-// Lut Creation & Destruction
+// This function is quite useful to analyze the structure of a LUT and retrieve the MPE elements
+// that conform the LUT. It should be called with the LUT, the number of expected elements and
+// then a list of expected types followed with a list of cmsFloat64Number pointers to MPE elements. If
+// the function founds a match with current pipeline, it fills the pointers and returns TRUE
+// if not, returns FALSE without touching anything. Setting pointers to NULL does bypass
+// the storage process.
+cmsBool  CMSEXPORT cmsPipelineCheckAndRetreiveStages(const cmsPipeline* Lut, cmsUInt32Number n, ...)
+{
+    va_list args;
+    cmsUInt32Number i;
+    cmsStage* mpe;
+    cmsStageSignature Type;
+    void** ElemPtr;
+
+    // Make sure same number of elements
+    if (cmsPipelineStageCount(Lut) != n) return FALSE;
+
+    va_start(args, n);
 
-LPLUT LCMSEXPORT cmsAllocLUT(void)
-{
-       LPLUT NewLUT;
+    // Iterate across asked types
+    mpe = Lut ->Elements;
+    for (i=0; i < n; i++) {
+
+        // Get asked type
+        Type  = va_arg(args, cmsStageSignature);
+        if (mpe ->Type != Type) {
+
+            va_end(args);       // Mismatch. We are done.
+            return FALSE;
+        }
+        mpe = mpe ->Next;
+    }
+
+    // Found a combination, fill pointers if not NULL
+    mpe = Lut ->Elements;
+    for (i=0; i < n; i++) {
+
+        ElemPtr = va_arg(args, void**);
+        if (ElemPtr != NULL)
+            *ElemPtr = mpe;
+
+        mpe = mpe ->Next;
+    }
 
-       NewLUT = (LPLUT) _cmsMalloc(sizeof(LUT));
-       if (NewLUT)
-              ZeroMemory(NewLUT, sizeof(LUT));
+    va_end(args);
+    return TRUE;
+}
+
+// Below there are implementations for several types of elements. Each type may be implemented by a
+// evaluation function, a duplication function, a function to free resources and a constructor.
+
+// *************************************************************************************************
+// Type cmsSigCurveSetElemType (curves)
+// *************************************************************************************************
+
+cmsToneCurve** _cmsStageGetPtrToCurveSet(const cmsStage* mpe)
+{
+    _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
+
+    return Data ->TheCurves;
+}
 
-       return NewLUT;
+static
+void EvaluateCurves(const cmsFloat32Number In[],
+                    cmsFloat32Number Out[],
+                    const cmsStage *mpe)
+{
+    _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
+    cmsUInt32Number i;
+
+    if (Data ->TheCurves == NULL) return;
+
+    for (i=0; i < Data ->nCurves; i++) {
+        Out[i] = cmsEvalToneCurveFloat(Data ->TheCurves[i], In[i]);
+    }
+}
+
+static
+void CurveSetElemTypeFree(cmsStage* mpe)
+{
+    _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
+    cmsUInt32Number i;
+
+    if (Data ->TheCurves != NULL) {
+        for (i=0; i < Data ->nCurves; i++) {
+            if (Data ->TheCurves[i] != NULL)
+                cmsFreeToneCurve(Data ->TheCurves[i]);
+        }
+    }
+    _cmsFree(mpe ->ContextID, Data ->TheCurves);
+    _cmsFree(mpe ->ContextID, Data);
 }
 
-void LCMSEXPORT cmsFreeLUT(LPLUT Lut)
+
+static
+void* CurveSetDup(cmsStage* mpe)
 {
-       unsigned int i;
+    _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
+    _cmsStageToneCurvesData* NewElem;
+    cmsUInt32Number i;
+
+    NewElem = (_cmsStageToneCurvesData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageToneCurvesData));
+    if (NewElem == NULL) return NULL;
 
-       if (!Lut) return;
+    NewElem ->nCurves   = Data ->nCurves;
+    NewElem ->TheCurves = (cmsToneCurve**) _cmsCalloc(mpe ->ContextID, NewElem ->nCurves, sizeof(cmsToneCurve*));
+
+    if (NewElem ->TheCurves == NULL) goto Error;
 
-       if (Lut -> T) free(Lut -> T);
+    for (i=0; i < NewElem ->nCurves; i++) {
+
+        // Duplicate each curve. It may fail.
+        NewElem ->TheCurves[i] = cmsDupToneCurve(Data ->TheCurves[i]);
+        if (NewElem ->TheCurves[i] == NULL) goto Error;
+
 
-       for (i=0; i < Lut -> OutputChan; i++)
-       {
-              if (Lut -> L2[i]) free(Lut -> L2[i]);
-       }
+    }
+    return (void*) NewElem;
+
+Error:
 
-       for (i=0; i < Lut -> InputChan; i++)
-       {
+    if (NewElem ->TheCurves != NULL) {
+        for (i=0; i < NewElem ->nCurves; i++) {
+            if (NewElem ->TheCurves[i])
+                cmsFreeToneCurve(Data ->TheCurves[i]);
+        }
+    }
+    _cmsFree(mpe ->ContextID, Data ->TheCurves);
+    _cmsFree(mpe ->ContextID, NewElem);
+    return NULL;
+}
 
-              if (Lut -> L1[i]) free(Lut -> L1[i]);
-       }
+
+// Curves == NULL forces identity curves
+cmsStage* CMSEXPORT cmsStageAllocToneCurves(cmsContext ContextID, cmsUInt32Number nChannels, cmsToneCurve* const Curves[])
+{
+    cmsUInt32Number i;
+    _cmsStageToneCurvesData* NewElem;
+    cmsStage* NewMPE;
 
 
-       if (Lut ->wFlags & LUT_HASTL3) {
+    NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCurveSetElemType, nChannels, nChannels,
+                                     EvaluateCurves, CurveSetDup, CurveSetElemTypeFree, NULL );
+    if (NewMPE == NULL) return NULL;
 
-            for (i=0; i < Lut -> InputChan; i++) {
+    NewElem = (_cmsStageToneCurvesData*) _cmsMalloc(ContextID, sizeof(_cmsStageToneCurvesData));
+    if (NewElem == NULL) {
+        cmsStageFree(NewMPE);
+        return NULL;
+    }
+
+    NewElem ->nCurves   = nChannels;
+    NewElem ->TheCurves = (cmsToneCurve**) _cmsCalloc(ContextID, nChannels, sizeof(cmsToneCurve*));
+    if (NewElem ->TheCurves == NULL) {
+        cmsStageFree(NewMPE);
+        return NULL;
+    }
+
+    for (i=0; i < nChannels; i++) {
 
-              if (Lut -> L3[i]) free(Lut -> L3[i]);
-            }
-       }
+        if (Curves == NULL) {
+            NewElem ->TheCurves[i] = cmsBuildGamma(ContextID, 1.0);
+        }
+        else {
+            NewElem ->TheCurves[i] = cmsDupToneCurve(Curves[i]);
+        }
+
+        if (NewElem ->TheCurves[i] == NULL) {
+            cmsStageFree(NewMPE);
+            return NULL;
+        }
+    }
+
+    NewMPE ->Data  = (void*) NewElem;
 
-       if (Lut ->wFlags & LUT_HASTL4) {
+    return NewMPE;
+}
+
+
+// Create a bunch of identity curves
+cmsStage* _cmsStageAllocIdentityCurves(cmsContext ContextID, int nChannels)
+{
+    cmsStage* mpe = cmsStageAllocToneCurves(ContextID, nChannels, NULL);
+
+    if (mpe == NULL) return NULL;
+    mpe ->Implements = cmsSigIdentityElemType;
+    return mpe;
+}
+
 
-            for (i=0; i < Lut -> OutputChan; i++) {
+// *************************************************************************************************
+// Type cmsSigMatrixElemType (Matrices)
+// *************************************************************************************************
+
+
+// Special care should be taken here because precision loss. A temporary cmsFloat64Number buffer is being used
+static
+void EvaluateMatrix(const cmsFloat32Number In[],
+                    cmsFloat32Number Out[],
+                    const cmsStage *mpe)
+{
+    cmsUInt32Number i, j;
+    _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
+    cmsFloat64Number Tmp;
+
+    // Input is already in 0..1.0 notation
+    for (i=0; i < mpe ->OutputChannels; i++) {
+
+        Tmp = 0;
+        for (j=0; j < mpe->InputChannels; j++) {
+            Tmp += In[j] * Data->Double[i*mpe->InputChannels + j];
+        }
+
+        if (Data ->Offset != NULL)
+            Tmp += Data->Offset[i];
 
-              if (Lut -> L4[i]) free(Lut -> L4[i]);
-            }
-       }
+        Out[i] = (cmsFloat32Number) Tmp;
+    }
+
+
+    // Output in 0..1.0 domain
+}
+
 
-       if (Lut ->CLut16params.p8)
-           free(Lut ->CLut16params.p8);
+// Duplicate a yet-existing matrix element
+static
+void* MatrixElemDup(cmsStage* mpe)
+{
+    _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
+    _cmsStageMatrixData* NewElem;
+    cmsUInt32Number sz;
 
-       free(Lut);
+    NewElem = (_cmsStageMatrixData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageMatrixData));
+    if (NewElem == NULL) return NULL;
+
+    sz = mpe ->InputChannels * mpe ->OutputChannels;
+
+    NewElem ->Double = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID, Data ->Double, sz * sizeof(cmsFloat64Number)) ;
+
+    if (Data ->Offset)
+        NewElem ->Offset = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID,
+                                                Data ->Offset, mpe -> OutputChannels * sizeof(cmsFloat64Number)) ;
+
+    return (void*) NewElem;
 }
 
 
 static
-LPVOID DupBlockTab(LPVOID Org, size_t size)
+void MatrixElemTypeFree(cmsStage* mpe)
+{
+    _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
+    if (Data ->Double)
+        _cmsFree(mpe ->ContextID, Data ->Double);
+
+    if (Data ->Offset)
+        _cmsFree(mpe ->ContextID, Data ->Offset);
+
+    _cmsFree(mpe ->ContextID, mpe ->Data);
+}
+
+
+
+cmsStage*  CMSEXPORT cmsStageAllocMatrix(cmsContext ContextID, cmsUInt32Number Rows, cmsUInt32Number Cols,
+                                     const cmsFloat64Number* Matrix, const cmsFloat64Number* Offset)
 {
-    LPVOID mem = _cmsMalloc(size);
-    if (mem != NULL)
-        CopyMemory(mem, Org, size);
+    cmsUInt32Number i, n;
+    _cmsStageMatrixData* NewElem;
+    cmsStage* NewMPE;
+
+    n = Rows * Cols;
+
+    // Check for overflow
+    if (n < Rows || n < Cols) return NULL;
+
+    NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigMatrixElemType, Cols, Rows,
+                                     EvaluateMatrix, MatrixElemDup, MatrixElemTypeFree, NULL );
+    if (NewMPE == NULL) return NULL;
+
+
+    NewElem = (_cmsStageMatrixData*) _cmsMallocZero(ContextID, sizeof(_cmsStageMatrixData));
+    if (NewElem == NULL) return NULL;
+
+
+    NewElem ->Double = (cmsFloat64Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat64Number));
 
-    return mem;
+    if (NewElem->Double == NULL) {
+        MatrixElemTypeFree(NewMPE);
+        return NULL;
+    }
+
+    for (i=0; i < n; i++) {
+        NewElem ->Double[i] = Matrix[i];
+    }
+
+
+    if (Offset != NULL) {
+
+        NewElem ->Offset = (cmsFloat64Number*) _cmsCalloc(ContextID, Cols, sizeof(cmsFloat64Number));
+        if (NewElem->Offset == NULL) {
+           MatrixElemTypeFree(NewMPE);
+           return NULL;
+        }
+
+        for (i=0; i < Cols; i++) {
+                NewElem ->Offset[i] = Offset[i];
+        }
+
+    }
+
+    NewMPE ->Data  = (void*) NewElem;
+    return NewMPE;
 }
 
 
-LPLUT LCMSEXPORT cmsDupLUT(LPLUT Orig)
+// *************************************************************************************************
+// Type cmsSigCLutElemType
+// *************************************************************************************************
+
+
+// Evaluate in true floating point
+static
+void EvaluateCLUTfloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
 {
-    LPLUT NewLUT = cmsAllocLUT();
-    unsigned int i;
+    _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
+
+    Data -> Params ->Interpolation.LerpFloat(In, Out, Data->Params);
+}
+
 
-       CopyMemory(NewLUT, Orig, sizeof(LUT));
+// Convert to 16 bits, evaluate, and back to floating point
+static
+void EvaluateCLUTfloatIn16(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
+{
+    _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
+    cmsUInt16Number In16[MAX_STAGE_CHANNELS], Out16[MAX_STAGE_CHANNELS];
+
+    _cmsAssert(mpe ->InputChannels  <= MAX_STAGE_CHANNELS);
+    _cmsAssert(mpe ->OutputChannels <= MAX_STAGE_CHANNELS);
+
+    FromFloatTo16(In, In16, mpe ->InputChannels);
+    Data -> Params ->Interpolation.Lerp16(In16, Out16, Data->Params);
+    From16ToFloat(Out16, Out,  mpe ->OutputChannels);
+}
+
 
-       for (i=0; i < Orig ->InputChan; i++)
-            NewLUT -> L1[i] = (LPWORD) DupBlockTab((LPVOID) Orig ->L1[i],
-                                        sizeof(WORD) * Orig ->In16params.nSamples);
+// Given an hypercube of b dimensions, with Dims[] number of nodes by dimension, calculate the total amount of nodes
+static
+cmsUInt32Number CubeSize(const cmsUInt32Number Dims[], cmsUInt32Number b)
+{
+    cmsUInt32Number rv;
+
+    for (rv = 1; b > 0; b--)
+        rv *= Dims[b-1];
+
+    return rv;
+}
+
+static
+void* CLUTElemDup(cmsStage* mpe)
+{
+    _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
+    _cmsStageCLutData* NewElem;
+
 
-       for (i=0; i < Orig ->OutputChan; i++)
-            NewLUT -> L2[i] = (LPWORD) DupBlockTab((LPVOID) Orig ->L2[i],
-                                        sizeof(WORD) * Orig ->Out16params.nSamples);
+    NewElem = (_cmsStageCLutData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageCLutData));
+    if (NewElem == NULL) return NULL;
+
+    NewElem ->nEntries       = Data ->nEntries;
+    NewElem ->HasFloatValues = Data ->HasFloatValues;
+
+    if (Data ->Tab.T) {
 
-       NewLUT -> T = (LPWORD) DupBlockTab((LPVOID) Orig ->T, Orig -> Tsize);
+        if (Data ->HasFloatValues)
+            NewElem ->Tab.TFloat = (cmsFloat32Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.TFloat, Data ->nEntries * sizeof (cmsFloat32Number));
+        else
+            NewElem ->Tab.T = (cmsUInt16Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.T, Data ->nEntries * sizeof (cmsUInt16Number));
+    }
 
-       return NewLUT;
+    NewElem ->Params   = _cmsComputeInterpParamsEx(mpe ->ContextID,
+                                                   Data ->Params ->nSamples,
+                                                   Data ->Params ->nInputs,
+                                                   Data ->Params ->nOutputs,
+                                                   NewElem ->Tab.T,
+                                                   Data ->Params ->dwFlags);
+
+    return (void*) NewElem;
 }
 
 
 static
-unsigned int UIpow(unsigned int a, unsigned int b)
+void CLutElemTypeFree(cmsStage* mpe)
 {
-        unsigned int rv = 1;
+
+    _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
+
+    // Already empty
+    if (Data == NULL) return;
+
+    // This works for both types
+    if (Data -> Tab.T)
+        _cmsFree(mpe ->ContextID, Data -> Tab.T);
+
+    _cmsFreeInterpParams(Data ->Params);
+    _cmsFree(mpe ->ContextID, mpe ->Data);
+}
+
+
+// Allocates a 16-bit multidimensional CLUT. This is evaluated at 16-bit precision. Table may have different
+// granularity on each dimension.
+cmsStage* CMSEXPORT cmsStageAllocCLut16bitGranular(cmsContext ContextID,
+                                         const cmsUInt32Number clutPoints[],
+                                         cmsUInt32Number inputChan,
+                                         cmsUInt32Number outputChan,
+                                         const cmsUInt16Number* Table)
+{
+    cmsUInt32Number i, n;
+    _cmsStageCLutData* NewElem;
+    cmsStage* NewMPE;
+
+    NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
+                                     EvaluateCLUTfloatIn16, CLUTElemDup, CLutElemTypeFree, NULL );
+
+    if (NewMPE == NULL) return NULL;
+
+    NewElem = (_cmsStageCLutData*) _cmsMalloc(ContextID, sizeof(_cmsStageCLutData));
+    if (NewElem == NULL) return NULL;
+
+    NewElem -> nEntries = n = outputChan * CubeSize(clutPoints, inputChan);
+    NewElem -> HasFloatValues = FALSE;
+
+    NewElem ->Tab.T  = (cmsUInt16Number*) _cmsCalloc(ContextID, n, sizeof(cmsUInt16Number));
+    if (NewElem ->Tab.T == NULL) {
+        cmsStageFree(NewMPE);
+        return NULL;
+    }
 
-        for (; b > 0; b--)
-                rv *= a;
+    if (Table != NULL) {
+        for (i=0; i < n; i++) {
+            NewElem ->Tab.T[i] = Table[i];
+        }
+    }
+
+    NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints, inputChan, outputChan, NewElem ->Tab.T, CMS_LERP_FLAGS_16BITS);
+    if (NewElem ->Params == NULL) {
+        cmsStageFree(NewMPE);
+        return NULL;
+    }
+
+    NewMPE ->Data  = (void*) NewElem;
+
+    return NewMPE;
+}
 
-        return rv;
+cmsStage* CMSEXPORT cmsStageAllocCLut16bit(cmsContext ContextID,
+                                    cmsUInt32Number nGridPoints,
+                                    cmsUInt32Number inputChan,
+                                    cmsUInt32Number outputChan,
+                                    const cmsUInt16Number* Table)
+{
+    cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
+    int i;
+
+   // Our resulting LUT would be same gridpoints on all dimensions
+    for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
+        Dimensions[i] = nGridPoints;
+
+
+    return cmsStageAllocCLut16bitGranular(ContextID, Dimensions, inputChan, outputChan, Table);
+}
+
+
+cmsStage* CMSEXPORT cmsStageAllocCLutFloat(cmsContext ContextID,
+                                       cmsUInt32Number nGridPoints,
+                                       cmsUInt32Number inputChan,
+                                       cmsUInt32Number outputChan,
+                                       const cmsFloat32Number* Table)
+{
+   cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
+   int i;
+
+    // Our resulting LUT would be same gridpoints on all dimensions
+    for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
+        Dimensions[i] = nGridPoints;
+
+    return cmsStageAllocCLutFloatGranular(ContextID, Dimensions, inputChan, outputChan, Table);
 }
 
 
-LCMSBOOL _cmsValidateLUT(LPLUT NewLUT)
+
+cmsStage* CMSEXPORT cmsStageAllocCLutFloatGranular(cmsContext ContextID, const cmsUInt32Number clutPoints[], cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsFloat32Number* Table)
 {
-    unsigned int calc = 1;
-    unsigned int oldCalc;
-    unsigned int power = NewLUT -> InputChan;
+    cmsUInt32Number i, n;
+    _cmsStageCLutData* NewElem;
+    cmsStage* NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
+                                             EvaluateCLUTfloat, CLUTElemDup, CLutElemTypeFree, NULL);
+
+    if (NewMPE == NULL) return NULL;
 
-    if (NewLUT -> cLutPoints > 100) return FALSE;
-    if (NewLUT -> InputChan > MAXCHANNELS)  return FALSE;
-    if (NewLUT -> OutputChan > MAXCHANNELS) return FALSE;
+
+    NewElem = (_cmsStageCLutData*) _cmsMalloc(ContextID, sizeof(_cmsStageCLutData));
+    if (NewElem == NULL) return NULL;
+
+    NewElem -> nEntries = n = outputChan * CubeSize( clutPoints, inputChan);
+    NewElem -> HasFloatValues = TRUE;
 
-    if (NewLUT -> cLutPoints == 0) return TRUE;
-
-    for (; power > 0; power--) {
+    NewElem ->Tab.TFloat  = (cmsFloat32Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat32Number));
+    if (NewElem ->Tab.TFloat == NULL) {
+        cmsStageFree(NewMPE);
+        return NULL;
+    }
 
-      oldCalc = calc;
-      calc *= NewLUT -> cLutPoints;
+    if (Table != NULL) {
+        for (i=0; i < n; i++) {
+            NewElem ->Tab.TFloat[i] = Table[i];
+        }
+    }
 
-      if (calc / NewLUT -> cLutPoints != oldCalc) {
-        return FALSE;
-      }
+    NewMPE ->Data  = (void*) NewElem;
+
+    NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints,  inputChan, outputChan, NewElem ->Tab.TFloat, CMS_LERP_FLAGS_FLOAT);
+    if (NewElem ->Params == NULL) {
+        cmsStageFree(NewMPE);
+        return NULL;
     }
 
-    oldCalc = calc;
-    calc *= NewLUT -> OutputChan;
-    if (NewLUT -> OutputChan && calc / NewLUT -> OutputChan != oldCalc) {
-      return FALSE;
+
+
+    return NewMPE;
+}
+
+
+static
+int IdentitySampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void * Cargo)
+{
+    int nChan = *(int*) Cargo;
+    int i;
+
+    for (i=0; i < nChan; i++)
+        Out[i] = In[i];
+
+    return 1;
+}
+
+// Creates an MPE that just copies input to output
+cmsStage* _cmsStageAllocIdentityCLut(cmsContext ContextID, int nChan)
+{
+    cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
+    cmsStage* mpe ;
+    int i;
+
+    for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
+        Dimensions[i] = 2;
+
+    mpe = cmsStageAllocCLut16bitGranular(ContextID, Dimensions, nChan, nChan, NULL);
+    if (mpe == NULL) return NULL;
+
+    if (!cmsStageSampleCLut16bit(mpe, IdentitySampler, &nChan, 0)) {
+        cmsStageFree(mpe);
+        return NULL;
+    }
+
+    mpe ->Implements = cmsSigIdentityElemType;
+    return mpe;
+}
+
+
+
+// Quantize a value 0 <= i < MaxSamples to 0..0xffff
+cmsUInt16Number _cmsQuantizeVal(cmsFloat64Number i, int MaxSamples)
+{
+    cmsFloat64Number x;
+
+    x = ((cmsFloat64Number) i * 65535.) / (cmsFloat64Number) (MaxSamples - 1);
+    return _cmsQuickSaturateWord(x);
+}
+
+
+// This routine does a sweep on whole input space, and calls its callback
+// function on knots. returns TRUE if all ok, FALSE otherwise.
+cmsBool CMSEXPORT cmsStageSampleCLut16bit(cmsStage* mpe, cmsSAMPLER16 Sampler, void * Cargo, cmsUInt32Number dwFlags)
+{
+    int i, t, nTotalPoints, index, rest;
+    int nInputs, nOutputs;
+    cmsUInt32Number* nSamples;
+    cmsUInt16Number In[cmsMAXCHANNELS], Out[MAX_STAGE_CHANNELS];
+    _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe->Data;
+
+
+    nSamples = clut->Params ->nSamples;
+    nInputs  = clut->Params ->nInputs;
+    nOutputs = clut->Params ->nOutputs;
+
+    if (nInputs >= cmsMAXCHANNELS) return FALSE;
+    if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
+
+    nTotalPoints = CubeSize(nSamples, nInputs);
+
+    index = 0;
+    for (i = 0; i < nTotalPoints; i++) {
+
+        rest = i;
+        for (t = nInputs-1; t >=0; --t) {
+
+            cmsUInt32Number  Colorant = rest % nSamples[t];
+
+            rest /= nSamples[t];
+
+            In[t] = _cmsQuantizeVal(Colorant, nSamples[t]);
+        }
+
+        if (clut ->Tab.T != NULL) {
+            for (t=0; t < nOutputs; t++)
+                Out[t] = clut->Tab.T[index + t];
+        }
+
+        if (!Sampler(In, Out, Cargo))
+            return FALSE;
+
+        if (!(dwFlags & SAMPLER_INSPECT)) {
+
+            if (clut ->Tab.T != NULL) {
+                for (t=0; t < nOutputs; t++)
+                    clut->Tab.T[index + t] = Out[t];
+            }
+        }
+
+        index += nOutputs;
     }
 
     return TRUE;
 }
 
-LPLUT LCMSEXPORT cmsAlloc3DGrid(LPLUT NewLUT, int clutPoints, int inputChan, int outputChan)
+// Same as anterior, but for floting point
+cmsBool CMSEXPORT cmsStageSampleCLutFloat(cmsStage* mpe, cmsSAMPLERFLOAT Sampler, void * Cargo, cmsUInt32Number dwFlags)
 {
-    DWORD nTabSize;
+    int i, t, nTotalPoints, index, rest;
+    int nInputs, nOutputs;
+    cmsUInt32Number* nSamples;
+    cmsFloat32Number In[cmsMAXCHANNELS], Out[MAX_STAGE_CHANNELS];
+    _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe->Data;
+
+    nSamples = clut->Params ->nSamples;
+    nInputs  = clut->Params ->nInputs;
+    nOutputs = clut->Params ->nOutputs;
+
+    if (nInputs >= cmsMAXCHANNELS) return FALSE;
+    if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
+
+    nTotalPoints = CubeSize(nSamples, nInputs);
+
+    index = 0;
+    for (i = 0; i < nTotalPoints; i++) {
+
+        rest = i;
+        for (t = nInputs-1; t >=0; --t) {
+
+            cmsUInt32Number  Colorant = rest % nSamples[t];
+
+            rest /= nSamples[t];
+
+            In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, nSamples[t]) / 65535.0);
+        }
+
+        if (clut ->Tab.TFloat != NULL) {
+            for (t=0; t < nOutputs; t++)
+                Out[t] = clut->Tab.TFloat[index + t];
+        }
 
-       NewLUT -> wFlags       |= LUT_HAS3DGRID;
-       NewLUT -> cLutPoints    = clutPoints;
-       NewLUT -> InputChan     = inputChan;
-       NewLUT -> OutputChan    = outputChan;
+        if (!Sampler(In, Out, Cargo))
+            return FALSE;
+
+        if (!(dwFlags & SAMPLER_INSPECT)) {
+
+            if (clut ->Tab.TFloat != NULL) {
+                for (t=0; t < nOutputs; t++)
+                    clut->Tab.TFloat[index + t] = Out[t];
+            }
+        }
+
+        index += nOutputs;
+    }
+
+    return TRUE;
+}
+
+
+
+// This routine does a sweep on whole input space, and calls its callback
+// function on knots. returns TRUE if all ok, FALSE otherwise.
+cmsBool CMSEXPORT cmsSliceSpace16(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
+                                         cmsSAMPLER16 Sampler, void * Cargo)
+{
+    int i, t, nTotalPoints, rest;
+    cmsUInt16Number In[cmsMAXCHANNELS];
+
+    if (nInputs >= cmsMAXCHANNELS) return FALSE;
+
+    nTotalPoints = CubeSize(clutPoints, nInputs);
+
+    for (i = 0; i < nTotalPoints; i++) {
+
+        rest = i;
+        for (t = nInputs-1; t >=0; --t) {
 
-       if (!_cmsValidateLUT(NewLUT)) {
-         return NULL;
-       }
+            cmsUInt32Number  Colorant = rest % clutPoints[t];
+
+            rest /= clutPoints[t];
+            In[t] = _cmsQuantizeVal(Colorant, clutPoints[t]);
+
+        }
+
+        if (!Sampler(In, NULL, Cargo))
+            return FALSE;
+    }
+
+    return TRUE;
+}
 
-       nTabSize = NewLUT -> OutputChan * UIpow(NewLUT->cLutPoints,
-                                               NewLUT->InputChan);
+cmsInt32Number CMSEXPORT cmsSliceSpaceFloat(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
+                                            cmsSAMPLERFLOAT Sampler, void * Cargo)
+{
+    int i, t, nTotalPoints, rest;
+    cmsFloat32Number In[cmsMAXCHANNELS];
+
+    if (nInputs >= cmsMAXCHANNELS) return FALSE;
+
+    nTotalPoints = CubeSize(clutPoints, nInputs);
+
+    for (i = 0; i < nTotalPoints; i++) {
+
+        rest = i;
+        for (t = nInputs-1; t >=0; --t) {
+
+            cmsUInt32Number  Colorant = rest % clutPoints[t];
+
+            rest /= clutPoints[t];
+            In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, clutPoints[t]) / 65535.0);
+
+        }
 
-       NewLUT -> T = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
-       nTabSize *= sizeof(WORD);
-       if (NewLUT -> T == NULL) return NULL;
+        if (!Sampler(In, NULL, Cargo))
+            return FALSE;
+    }
+
+    return TRUE;
+}
+
+// ********************************************************************************
+// Type cmsSigLab2XYZElemType
+// ********************************************************************************
+
 
-       ZeroMemory(NewLUT -> T, nTabSize);
-       NewLUT ->Tsize = nTabSize;
+static
+void EvaluateLab2XYZ(const cmsFloat32Number In[],
+                     cmsFloat32Number Out[],
+                     const cmsStage *mpe)
+{
+    cmsCIELab Lab;
+    cmsCIEXYZ XYZ;
+    const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
+
+    // V4 rules
+    Lab.L = In[0] * 100.0;
+    Lab.a = In[1] * 255.0 - 128.0;
+    Lab.b = In[2] * 255.0 - 128.0;
+
+    cmsLab2XYZ(NULL, &XYZ, &Lab);
+
+    // From XYZ, range 0..19997 to 0..1.0, note that 1.99997 comes from 0xffff
+    // encoded as 1.15 fixed point, so 1 + (32767.0 / 32768.0)
+
+    Out[0] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.X / XYZadj);
+    Out[1] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Y / XYZadj);
+    Out[2] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Z / XYZadj);
+    return;
+
+    cmsUNUSED_PARAMETER(mpe);
+}
 
 
-       cmsCalcCLUT16Params(NewLUT -> cLutPoints,  NewLUT -> InputChan,
-                                                  NewLUT -> OutputChan,
-                                                  &NewLUT -> CLut16params);
+// No dup or free routines needed, as the structure has no pointers in it.
+cmsStage* _cmsStageAllocLab2XYZ(cmsContext ContextID)
+{
+    return _cmsStageAllocPlaceholder(ContextID, cmsSigLab2XYZElemType, 3, 3, EvaluateLab2XYZ, NULL, NULL, NULL);
+}
+
+// ********************************************************************************
+
+// v2 L=100 is supposed to be placed on 0xFF00. There is no reasonable
+// number of gridpoints that would make exact match. However, a prelinearization
+// of 258 entries, would map 0xFF00 exactly on entry 257, and this is good to avoid scum dot.
+// Almost all what we need but unfortunately, the rest of entries should be scaled by
+// (255*257/256) and this is not exact.
+
+cmsStage* _cmsStageAllocLabV2ToV4curves(cmsContext ContextID)
+{
+    cmsStage* mpe;
+    cmsToneCurve* LabTable[3];
+    int i, j;
+
+    LabTable[0] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
+    LabTable[1] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
+    LabTable[2] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
+
+    for (j=0; j < 3; j++) {
+
+        if (LabTable[j] == NULL) {
+            cmsFreeToneCurveTriple(LabTable);
+            return NULL;
+        }
+
+        // We need to map * (0xffff / 0xff00), thats same as (257 / 256)
+        // So we can use 258-entry tables to do the trick (i / 257) * (255 * 257) * (257 / 256);
+        for (i=0; i < 257; i++)  {
+
+            LabTable[j]->Table16[i] = (cmsUInt16Number) ((i * 0xffff + 0x80) >> 8);
+        }
+
+        LabTable[j] ->Table16[257] = 0xffff;
+    }
+
+    mpe = cmsStageAllocToneCurves(ContextID, 3, LabTable);
+    cmsFreeToneCurveTriple(LabTable);
+
+    mpe ->Implements = cmsSigLabV2toV4;
+    return mpe;
+}
+
+// ********************************************************************************
+
+// Matrix-based conversion, which is more accurate, but slower and cannot properly be saved in devicelink profiles
+cmsStage* _cmsStageAllocLabV2ToV4(cmsContext ContextID)
+{
+    static const cmsFloat64Number V2ToV4[] = { 65535.0/65280.0, 0, 0,
+                                     0, 65535.0/65280.0, 0,
+                                     0, 0, 65535.0/65280.0
+                                     };
+
+    cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V2ToV4, NULL);
+
+    if (mpe == NULL) return mpe;
+    mpe ->Implements = cmsSigLabV2toV4;
+    return mpe;
+}
+
+
+// Reverse direction
+cmsStage* _cmsStageAllocLabV4ToV2(cmsContext ContextID)
+{
+    static const cmsFloat64Number V4ToV2[] = { 65280.0/65535.0, 0, 0,
+                                     0, 65280.0/65535.0, 0,
+                                     0, 0, 65280.0/65535.0
+                                     };
+
+     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V4ToV2, NULL);
+
+    if (mpe == NULL) return mpe;
+    mpe ->Implements = cmsSigLabV4toV2;
+    return mpe;
+}
+
+
+// ********************************************************************************
+// Type cmsSigXYZ2LabElemType
+// ********************************************************************************
+
+static
+void EvaluateXYZ2Lab(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
+{
+    cmsCIELab Lab;
+    cmsCIEXYZ XYZ;
+    const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
+
+    // From 0..1.0 to XYZ
+
+    XYZ.X = In[0] * XYZadj;
+    XYZ.Y = In[1] * XYZadj;
+    XYZ.Z = In[2] * XYZadj;
+
+    cmsXYZ2Lab(NULL, &Lab, &XYZ);
+
+    // From V4 Lab to 0..1.0
+
+    Out[0] = (cmsFloat32Number) (Lab.L / 100.0);
+    Out[1] = (cmsFloat32Number) ((Lab.a + 128.0) / 255.0);
+    Out[2] = (cmsFloat32Number) ((Lab.b + 128.0) / 255.0);
+    return;
+
+    cmsUNUSED_PARAMETER(mpe);
+}
+
+cmsStage* _cmsStageAllocXYZ2Lab(cmsContext ContextID)
+{
+    return _cmsStageAllocPlaceholder(ContextID, cmsSigXYZ2LabElemType, 3, 3, EvaluateXYZ2Lab, NULL, NULL, NULL);
+
+}
+
+// ********************************************************************************
+
+// For v4, S-Shaped curves are placed in a/b axis to increase resolution near gray
+
+cmsStage* _cmsStageAllocLabPrelin(cmsContext ContextID)
+{
+    cmsToneCurve* LabTable[3];
+    cmsFloat64Number Params[1] =  {2.4} ;
+
+    LabTable[0] = cmsBuildGamma(ContextID, 1.0);
+    LabTable[1] = cmsBuildParametricToneCurve(ContextID, 108, Params);
+    LabTable[2] = cmsBuildParametricToneCurve(ContextID, 108, Params);
+
+    return cmsStageAllocToneCurves(ContextID, 3, LabTable);
+}
 
-       return NewLUT;
+
+// Free a single MPE
+void CMSEXPORT cmsStageFree(cmsStage* mpe)
+{
+    if (mpe ->FreePtr)
+        mpe ->FreePtr(mpe);
+
+    _cmsFree(mpe ->ContextID, mpe);
+}
+
+
+cmsUInt32Number  CMSEXPORT cmsStageInputChannels(const cmsStage* mpe)
+{
+    return mpe ->InputChannels;
+}
+
+cmsUInt32Number  CMSEXPORT cmsStageOutputChannels(const cmsStage* mpe)
+{
+    return mpe ->OutputChannels;
+}
+
+cmsStageSignature CMSEXPORT cmsStageType(const cmsStage* mpe)
+{
+    return mpe -> Type;
+}
+
+void* CMSEXPORT cmsStageData(const cmsStage* mpe)
+{
+    return mpe -> Data;
+}
+
+cmsStage*  CMSEXPORT cmsStageNext(const cmsStage* mpe)
+{
+    return mpe -> Next;
+}
+
+
+// Duplicates an MPE
+cmsStage* CMSEXPORT cmsStageDup(cmsStage* mpe)
+{
+    cmsStage* NewMPE;
+
+    if (mpe == NULL) return NULL;
+    NewMPE = _cmsStageAllocPlaceholder(mpe ->ContextID,
+                                     mpe ->Type,
+                                     mpe ->InputChannels,
+                                     mpe ->OutputChannels,
+                                     mpe ->EvalPtr,
+                                     mpe ->DupElemPtr,
+                                     mpe ->FreePtr,
+                                     NULL);
+    if (NewMPE == NULL) return NULL;
+
+    NewMPE ->Implements     = mpe ->Implements;
+
+    if (mpe ->DupElemPtr)
+        NewMPE ->Data       = mpe ->DupElemPtr(mpe);
+    else
+        NewMPE ->Data       = NULL;
+
+    return NewMPE;
+}
+
+
+// ***********************************************************************************************************
+
+// This function sets up the channel count
+
+static
+void BlessLUT(cmsPipeline* lut)
+{
+    // We can set the input/ouput channels only if we have elements.
+    if (lut ->Elements != NULL) {
+
+        cmsStage *First, *Last;
+
+        First  = cmsPipelineGetPtrToFirstStage(lut);
+        Last   = cmsPipelineGetPtrToLastStage(lut);
+
+        if (First != NULL)lut ->InputChannels = First ->InputChannels;
+        if (Last != NULL) lut ->OutputChannels = Last ->OutputChannels;
+    }
+}
+
+
+// Default to evaluate the LUT on 16 bit-basis. Precision is retained.
+static
+void _LUTeval16(register const cmsUInt16Number In[], register cmsUInt16Number Out[],  register const void* D)
+{
+    cmsPipeline* lut = (cmsPipeline*) D;
+    cmsStage *mpe;
+    cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS];
+    int Phase = 0, NextPhase;
+
+    From16ToFloat(In, &Storage[Phase][0], lut ->InputChannels);
+
+    for (mpe = lut ->Elements;
+         mpe != NULL;
+         mpe = mpe ->Next) {
+
+             NextPhase = Phase ^ 1;
+             mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
+             Phase = NextPhase;
+    }
+
+
+    FromFloatTo16(&Storage[Phase][0], Out, lut ->OutputChannels);
+}
+
+
+
+// Does evaluate the LUT on cmsFloat32Number-basis.
+static
+void _LUTevalFloat(register const cmsFloat32Number In[], register cmsFloat32Number Out[], const void* D)
+{
+    cmsPipeline* lut = (cmsPipeline*) D;
+    cmsStage *mpe;
+    cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS];
+    int Phase = 0, NextPhase;
+
+    memmove(&Storage[Phase][0], In, lut ->InputChannels  * sizeof(cmsFloat32Number));
+
+    for (mpe = lut ->Elements;
+         mpe != NULL;
+         mpe = mpe ->Next) {
+
+              NextPhase = Phase ^ 1;
+              mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
+              Phase = NextPhase;
+    }
+
+    memmove(Out, &Storage[Phase][0], lut ->OutputChannels * sizeof(cmsFloat32Number));
 }
 
 
 
 
-LPLUT LCMSEXPORT cmsAllocLinearTable(LPLUT NewLUT, LPGAMMATABLE Tables[], int nTable)
+// LUT Creation & Destruction
+
+cmsPipeline* CMSEXPORT cmsPipelineAlloc(cmsContext ContextID, cmsUInt32Number InputChannels, cmsUInt32Number OutputChannels)
 {
-       unsigned int i;
-       LPWORD PtrW;
-
-       switch (nTable) {
-
+       cmsPipeline* NewLUT;
 
-       case 1: NewLUT -> wFlags |= LUT_HASTL1;
-               cmsCalcL16Params(Tables[0] -> nEntries, &NewLUT -> In16params);
-               NewLUT -> InputEntries = Tables[0] -> nEntries;
-
-               for (i=0; i < NewLUT -> InputChan; i++) {
+       if (InputChannels >= cmsMAXCHANNELS ||
+           OutputChannels >= cmsMAXCHANNELS) return NULL;
 
-                     PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> InputEntries);
-                     if (PtrW == NULL) return NULL;
-
-                     NewLUT -> L1[i] = PtrW;
-                     CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> InputEntries);
-                     CopyMemory(&NewLUT -> LCurvesSeed[0][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
-               }
+       NewLUT = (cmsPipeline*) _cmsMallocZero(ContextID, sizeof(cmsPipeline));
+       if (NewLUT == NULL) return NULL;
 
 
-               break;
-
-       case 2: NewLUT -> wFlags |= LUT_HASTL2;
-               cmsCalcL16Params(Tables[0] -> nEntries, &NewLUT -> Out16params);
-               NewLUT -> OutputEntries = Tables[0] -> nEntries;
-               for (i=0; i < NewLUT -> OutputChan; i++) {
-
-                     PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> OutputEntries);
-                     if (PtrW == NULL) return NULL;
-
-                     NewLUT -> L2[i] = PtrW;
-                     CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> OutputEntries);
-                     CopyMemory(&NewLUT -> LCurvesSeed[1][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
-               }
-               break;
-
-
-       // 3 & 4 according ICC 4.0 spec
-
-       case 3:
-               NewLUT -> wFlags |= LUT_HASTL3;
-               cmsCalcL16Params(Tables[0] -> nEntries, &NewLUT -> L3params);
-               NewLUT -> L3Entries = Tables[0] -> nEntries;
-
-               for (i=0; i < NewLUT -> InputChan; i++) {
+       NewLUT -> InputChannels  = InputChannels;
+       NewLUT -> OutputChannels = OutputChannels;
 
-                     PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> L3Entries);
-                     if (PtrW == NULL) return NULL;
-
-                     NewLUT -> L3[i] = PtrW;
-                     CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> L3Entries);
-                     CopyMemory(&NewLUT -> LCurvesSeed[2][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
-               }
-               break;
+       NewLUT ->Eval16Fn    = _LUTeval16;
+       NewLUT ->EvalFloatFn = _LUTevalFloat;
+       NewLUT ->DupDataFn   = NULL;
+       NewLUT ->FreeDataFn  = NULL;
+       NewLUT ->Data        = NewLUT;
 
-       case 4:
-               NewLUT -> wFlags |= LUT_HASTL4;
-               cmsCalcL16Params(Tables[0] -> nEntries, &NewLUT -> L4params);
-               NewLUT -> L4Entries = Tables[0] -> nEntries;
-               for (i=0; i < NewLUT -> OutputChan; i++) {
-
-                     PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> L4Entries);
-                     if (PtrW == NULL) return NULL;
+       NewLUT ->ContextID    = ContextID;
 
-                     NewLUT -> L4[i] = PtrW;
-                     CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> L4Entries);
-                     CopyMemory(&NewLUT -> LCurvesSeed[3][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
-               }
-               break;
-
-
-       default:;
-       }
+       BlessLUT(NewLUT);
 
        return NewLUT;
 }
 
 
-// Set the LUT matrix
+cmsUInt32Number CMSEXPORT cmsPipelineInputChannels(const cmsPipeline* lut)
+{
+    return lut ->InputChannels;
+}
 
-LPLUT LCMSEXPORT cmsSetMatrixLUT(LPLUT Lut, LPMAT3 M)
+cmsUInt32Number CMSEXPORT cmsPipelineOutputChannels(const cmsPipeline* lut)
+{
+    return lut ->OutputChannels;
+}
+
+// Free a profile elements LUT
+void CMSEXPORT cmsPipelineFree(cmsPipeline* lut)
 {
-        MAT3toFix(&Lut ->Matrix, M);
+    cmsStage *mpe, *Next;
+
+    if (lut == NULL) return;
+
+    for (mpe = lut ->Elements;
+        mpe != NULL;
+        mpe = Next) {
 
-        if (!MAT3isIdentity(&Lut->Matrix, 0.0001))
-            Lut ->wFlags |= LUT_HASMATRIX;
+            Next = mpe ->Next;
+            cmsStageFree(mpe);
+    }
 
-        return Lut;
+    if (lut ->FreeDataFn) lut ->FreeDataFn(lut ->ContextID, lut ->Data);
+
+    _cmsFree(lut ->ContextID, lut);
 }
 
 
-// Set matrix & offset, v4 compatible
-
-LPLUT LCMSEXPORT cmsSetMatrixLUT4(LPLUT Lut, LPMAT3 M, LPVEC3 off, DWORD dwFlags)
+// Default to evaluate the LUT on 16 bit-basis.
+void CMSEXPORT cmsPipelineEval16(const cmsUInt16Number In[], cmsUInt16Number Out[],  const cmsPipeline* lut)
 {
-    WMAT3 WMat;
-    WVEC3 Woff;
-    VEC3  Zero = {{0, 0, 0}};
-
-        MAT3toFix(&WMat, M);
-
-        if (off == NULL)
-                off = &Zero;
-
-        VEC3toFix(&Woff, off);
-
-        // Nop if identity
-        if (MAT3isIdentity(&WMat, 0.0001) &&
-            (Woff.n[VX] == 0 && Woff.n[VY] == 0 && Woff.n[VZ] == 0))
-            return Lut;
-
-        switch (dwFlags) {
-
-        case LUT_HASMATRIX:
-                Lut ->Matrix = WMat;
-                Lut ->wFlags |= LUT_HASMATRIX;
-                break;
-
-        case LUT_HASMATRIX3:
-                Lut ->Mat3 = WMat;
-                Lut ->Ofs3 = Woff;
-                Lut ->wFlags |= LUT_HASMATRIX3;
-                break;
-
-        case LUT_HASMATRIX4:
-                Lut ->Mat4 = WMat;
-                Lut ->Ofs4 = Woff;
-                Lut ->wFlags |= LUT_HASMATRIX4;
-                break;
+    lut ->Eval16Fn(In, Out, lut->Data);
+}
 
 
-        default:;
-        }
-
-        return Lut;
+// Does evaluate the LUT on cmsFloat32Number-basis.
+void CMSEXPORT cmsPipelineEvalFloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsPipeline* lut)
+{
+    lut ->EvalFloatFn(In, Out, lut);
 }
 
 
 
-// The full evaluator
-
-void LCMSEXPORT cmsEvalLUT(LPLUT Lut, WORD In[], WORD Out[])
+// Duplicates a LUT
+cmsPipeline* CMSEXPORT cmsPipelineDup(const cmsPipeline* lut)
 {
-       register unsigned int i;
-       WORD StageABC[MAXCHANNELS], StageLMN[MAXCHANNELS];
-
-
-       // Try to speedup things on plain devicelinks
-       if (Lut ->wFlags == LUT_HAS3DGRID) {
-
-            Lut ->CLut16params.Interp3D(In, Out, Lut -> T, &Lut -> CLut16params);
-            return;
-       }
-
-
-       // Nope, evaluate whole LUT
+    cmsPipeline* NewLUT;
+    cmsStage *NewMPE, *Anterior = NULL, *mpe;
+    cmsBool  First = TRUE;
 
-       for (i=0; i < Lut -> InputChan; i++)
-                            StageABC[i] = In[i];
-
-
-       if (Lut ->wFlags & LUT_V4_OUTPUT_EMULATE_V2) {
-
-           // Clamp Lab to avoid overflow
-           if (StageABC[0] > 0xFF00)
-               StageABC[0] = 0xFF00;
+    if (lut == NULL) return NULL;
 
-           StageABC[0] = (WORD) FROM_V2_TO_V4(StageABC[0]);
-           StageABC[1] = (WORD) FROM_V2_TO_V4(StageABC[1]);
-           StageABC[2] = (WORD) FROM_V2_TO_V4(StageABC[2]);
-
-       }
+    NewLUT = cmsPipelineAlloc(lut ->ContextID, lut ->InputChannels, lut ->OutputChannels);
+    for (mpe = lut ->Elements;
+         mpe != NULL;
+         mpe = mpe ->Next) {
 
-       if (Lut ->wFlags & LUT_V2_OUTPUT_EMULATE_V4) {
-
-           StageABC[0] = (WORD) FROM_V4_TO_V2(StageABC[0]);
-           StageABC[1] = (WORD) FROM_V4_TO_V2(StageABC[1]);
-           StageABC[2] = (WORD) FROM_V4_TO_V2(StageABC[2]);
-       }
+             NewMPE = cmsStageDup(mpe);
 
-
-       // Matrix handling.
-
-       if (Lut -> wFlags & LUT_HASMATRIX) {
-
-              WVEC3 InVect, OutVect;
-
-              // In LUT8 here comes the special gray axis fixup
-
-              if (Lut ->FixGrayAxes) {
-
-                  StageABC[1] = _cmsClampWord(StageABC[1] - 128);
-                  StageABC[2] = _cmsClampWord(StageABC[2] - 128);
-              }
-
-              // Matrix
-
-              InVect.n[VX] = ToFixedDomain(StageABC[0]);
-              InVect.n[VY] = ToFixedDomain(StageABC[1]);
-              InVect.n[VZ] = ToFixedDomain(StageABC[2]);
+             if (NewMPE == NULL) {
+                 cmsPipelineFree(NewLUT);
+                 return NULL;
+             }
 
-
-              MAT3evalW(&OutVect, &Lut -> Matrix, &InVect);
-
-              // PCS in 1Fixed15 format, adjusting
-
-              StageABC[0] = _cmsClampWord(FromFixedDomain(OutVect.n[VX]));
-              StageABC[1] = _cmsClampWord(FromFixedDomain(OutVect.n[VY]));
-              StageABC[2] = _cmsClampWord(FromFixedDomain(OutVect.n[VZ]));
-       }
+             if (First) {
+                 NewLUT ->Elements = NewMPE;
+                 First = FALSE;
+             }
+             else {
+                Anterior ->Next = NewMPE;
+             }
 
-
-       // First linearization
+            Anterior = NewMPE;
+    }
 
-       if (Lut -> wFlags & LUT_HASTL1)
-       {
-              for (i=0; i < Lut -> InputChan; i++)
-                     StageABC[i] = cmsLinearInterpLUT16(StageABC[i],
-                                                   Lut -> L1[i],
-                                                   &Lut -> In16params);
-       }
+    NewLUT ->DupDataFn  = lut ->DupDataFn;
+    NewLUT ->FreeDataFn = lut ->FreeDataFn;
+
+    if (NewLUT ->DupDataFn != NULL)
+        NewLUT ->Data = NewLUT ->DupDataFn(lut ->ContextID, lut->Data);
 
 
-       //  Mat3, Ofs3, L3 processing
-
-       if (Lut ->wFlags & LUT_HASMATRIX3) {
-
-              WVEC3 InVect, OutVect;
-
-              InVect.n[VX] = ToFixedDomain(StageABC[0]);
-              InVect.n[VY] = ToFixedDomain(StageABC[1]);
-              InVect.n[VZ] = ToFixedDomain(StageABC[2]);
-
-              MAT3evalW(&OutVect, &Lut -> Mat3, &InVect);
-
-              OutVect.n[VX] += Lut ->Ofs3.n[VX];
-              OutVect.n[VY] += Lut ->Ofs3.n[VY];
-              OutVect.n[VZ] += Lut ->Ofs3.n[VZ];
-
-              StageABC[0] = _cmsClampWord(FromFixedDomain(OutVect.n[VX]));
-              StageABC[1] = _cmsClampWord(FromFixedDomain(OutVect.n[VY]));
-              StageABC[2] = _cmsClampWord(FromFixedDomain(OutVect.n[VZ]));
-
-       }
-
-       if (Lut ->wFlags & LUT_HASTL3) {
-
-             for (i=0; i < Lut -> InputChan; i++)
-                     StageABC[i] = cmsLinearInterpLUT16(StageABC[i],
-                                                   Lut -> L3[i],
-                                                   &Lut -> L3params);
-
-       }
-
-
-
-       if (Lut -> wFlags & LUT_HAS3DGRID) {
-
-            Lut ->CLut16params.Interp3D(StageABC, StageLMN, Lut -> T, &Lut -> CLut16params);
-
-       }
-       else
-       {
-
-              for (i=0; i < Lut -> InputChan; i++)
-                            StageLMN[i] = StageABC[i];
-
-       }
-
-
-       // Mat4, Ofs4, L4 processing
-
-       if (Lut ->wFlags & LUT_HASTL4) {
+    NewLUT ->SaveAs8Bits    = lut ->SaveAs8Bits;
 
-            for (i=0; i < Lut -> OutputChan; i++)
-                     StageLMN[i] = cmsLinearInterpLUT16(StageLMN[i],
-                                                   Lut -> L4[i],
-                                                   &Lut -> L4params);
-       }
-
-       if (Lut ->wFlags & LUT_HASMATRIX4) {
-
-              WVEC3 InVect, OutVect;
-
-              InVect.n[VX] = ToFixedDomain(StageLMN[0]);
-              InVect.n[VY] = ToFixedDomain(StageLMN[1]);
-              InVect.n[VZ] = ToFixedDomain(StageLMN[2]);
-
-              MAT3evalW(&OutVect, &Lut -> Mat4, &InVect);
-
-              OutVect.n[VX] += Lut ->Ofs4.n[VX];
-              OutVect.n[VY] += Lut ->Ofs4.n[VY];
-              OutVect.n[VZ] += Lut ->Ofs4.n[VZ];
-
-              StageLMN[0] = _cmsClampWord(FromFixedDomain(OutVect.n[VX]));
-              StageLMN[1] = _cmsClampWord(FromFixedDomain(OutVect.n[VY]));
-              StageLMN[2] = _cmsClampWord(FromFixedDomain(OutVect.n[VZ]));
-
-       }
-
-       // Last linearitzation
-
-       if (Lut -> wFlags & LUT_HASTL2)
-       {
-              for (i=0; i < Lut -> OutputChan; i++)
-                     Out[i] = cmsLinearInterpLUT16(StageLMN[i],
-                                                   Lut -> L2[i],
-                                                   &Lut -> Out16params);
-       }
-       else
-       {
-       for (i=0; i < Lut -> OutputChan; i++)
-              Out[i] = StageLMN[i];
-       }
-
-
-
-       if (Lut ->wFlags & LUT_V4_INPUT_EMULATE_V2) {
-
-           Out[0] = (WORD) FROM_V4_TO_V2(Out[0]);
-           Out[1] = (WORD) FROM_V4_TO_V2(Out[1]);
-           Out[2] = (WORD) FROM_V4_TO_V2(Out[2]);
-
-       }
-
-       if (Lut ->wFlags & LUT_V2_INPUT_EMULATE_V4) {
-
-           Out[0] = (WORD) FROM_V2_TO_V4(Out[0]);
-           Out[1] = (WORD) FROM_V2_TO_V4(Out[1]);
-           Out[2] = (WORD) FROM_V2_TO_V4(Out[2]);
-       }
+    BlessLUT(NewLUT);
+    return NewLUT;
 }
 
 
-// Precomputes tables for 8-bit on input devicelink.
-//
-LPLUT _cmsBlessLUT8(LPLUT Lut)
+void CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe)
 {
-   int i, j;
-   WORD StageABC[3];
-   Fixed32 v1, v2, v3;
-   LPL8PARAMS p8;
-   LPL16PARAMS p = &Lut ->CLut16params;
+    cmsStage* Anterior = NULL, *pt;
+
+    switch (loc) {
+
+        case cmsAT_BEGIN:
+            mpe ->Next = lut ->Elements;
+            lut ->Elements = mpe;
+            break;
+
+        case cmsAT_END:
+
+            if (lut ->Elements == NULL)
+                lut ->Elements = mpe;
+            else {
+
+                for (pt = lut ->Elements;
+                     pt != NULL;
+                     pt = pt -> Next) Anterior = pt;
+
+                Anterior ->Next = mpe;
+                mpe ->Next = NULL;
+            }
+            break;
+        default:;
+    }
+
+    BlessLUT(lut);
+}
+
+// Unlink an element and return the pointer to it
+void CMSEXPORT cmsPipelineUnlinkStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage** mpe)
+{
+    cmsStage *Anterior, *pt, *Last;
+    cmsStage *Unlinked = NULL;
 
 
-   p8 = (LPL8PARAMS) _cmsMalloc(sizeof(L8PARAMS));
-   if (p8 == NULL) return NULL;
+    // If empty LUT, there is nothing to remove
+    if (lut ->Elements == NULL) {
+        if (mpe) *mpe = NULL;
+        return;
+    }
 
-  // values comes * 257, so we can safely take first byte (x << 8 + x)
-  // if there are prelinearization, is already smelted in tables
-
-   for (i=0; i < 256; i++) {
-
-           StageABC[0] = StageABC[1] = StageABC[2] = RGB_8_TO_16(i);
+    // On depending on the strategy...
+    switch (loc) {
 
-           if (Lut ->wFlags & LUT_HASTL1) {
+        case cmsAT_BEGIN:
+            {
+                cmsStage* elem = lut ->Elements;
 
-              for (j=0; j < 3; j++)
-                     StageABC[j] = cmsLinearInterpLUT16(StageABC[j],
-                                                        Lut -> L1[j],
-                                                       &Lut -> In16params);
-              Lut ->wFlags &= ~LUT_HASTL1;
-           }
+                lut ->Elements = elem -> Next;
+                elem ->Next = NULL;
+                Unlinked = elem;
 
+            }
+            break;
 
-           v1 = ToFixedDomain(StageABC[0] * p -> Domain);
-           v2 = ToFixedDomain(StageABC[1] * p -> Domain);
-           v3 = ToFixedDomain(StageABC[2] * p -> Domain);
+        case cmsAT_END:
+            Anterior = Last = NULL;
+            for (pt = lut ->Elements;
+                pt != NULL;
+                pt = pt -> Next) {
+                    Anterior = Last;
+                    Last = pt;
+            }
 
-           p8 ->X0[i] = p->opta3 * FIXED_TO_INT(v1);
-           p8 ->Y0[i] = p->opta2 * FIXED_TO_INT(v2);
-           p8 ->Z0[i] = p->opta1 * FIXED_TO_INT(v3);
+            Unlinked = Last;  // Next already points to NULL
 
-           p8 ->rx[i] = (WORD) FIXED_REST_TO_INT(v1);
-           p8 ->ry[i] = (WORD) FIXED_REST_TO_INT(v2);
-           p8 ->rz[i] = (WORD) FIXED_REST_TO_INT(v3);
-
-  }
+            // Truncate the chain
+            if (Anterior)
+                Anterior ->Next = NULL;
+            else
+                lut ->Elements = NULL;
+            break;
+        default:;
+    }
 
-   Lut -> CLut16params.p8 = p8;
-   Lut -> CLut16params.Interp3D = cmsTetrahedralInterp8;
+    if (mpe)
+        *mpe = Unlinked;
+    else
+        cmsStageFree(Unlinked);
 
-   return Lut;
-
+    BlessLUT(lut);
 }
 
 
+// Concatenate two LUT into a new single one
+cmsBool  CMSEXPORT cmsPipelineCat(cmsPipeline* l1, const cmsPipeline* l2)
+{
+    cmsStage* mpe, *NewMPE;
+
+    // If both LUTS does not have elements, we need to inherit
+    // the number of channels
+    if (l1 ->Elements == NULL && l2 ->Elements == NULL) {
+        l1 ->InputChannels  = l2 ->InputChannels;
+        l1 ->OutputChannels = l2 ->OutputChannels;
+    }
+
+    // Cat second
+    for (mpe = l2 ->Elements;
+         mpe != NULL;
+         mpe = mpe ->Next) {
+
+            // We have to dup each element
+             NewMPE = cmsStageDup(mpe);
+
+             if (NewMPE == NULL) {
+                 return FALSE;
+             }
+
+             cmsPipelineInsertStage(l1, cmsAT_END, NewMPE);
+    }
+
+  BlessLUT(l1);
+  return TRUE;
+}
+
+
+cmsBool CMSEXPORT cmsPipelineSetSaveAs8bitsFlag(cmsPipeline* lut, cmsBool On)
+{
+    cmsBool Anterior = lut ->SaveAs8Bits;
+
+    lut ->SaveAs8Bits = On;
+    return Anterior;
+}
+
+
+cmsStage* CMSEXPORT cmsPipelineGetPtrToFirstStage(const cmsPipeline* lut)
+{
+    return lut ->Elements;
+}
+
+cmsStage* CMSEXPORT cmsPipelineGetPtrToLastStage(const cmsPipeline* lut)
+{
+    cmsStage *mpe, *Anterior = NULL;
+
+    for (mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
+        Anterior = mpe;
+
+    return Anterior;
+}
+
+cmsUInt32Number CMSEXPORT cmsPipelineStageCount(const cmsPipeline* lut)
+{
+    cmsStage *mpe;
+    cmsUInt32Number n;
+
+    for (n=0, mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
+            n++;
+
+    return n;
+}
+
+// This function may be used to set the optional evalueator and a block of private data. If private data is being used, an optional
+// duplicator and free functions should also be specified in order to duplicate the LUT construct. Use NULL to inhibit such functionality.
+void CMSEXPORT _cmsPipelineSetOptimizationParameters(cmsPipeline* Lut,
+                                        _cmsOPTeval16Fn Eval16,
+                                        void* PrivateData,
+                                        _cmsOPTfreeDataFn FreePrivateDataFn,
+                                        _cmsOPTdupDataFn DupPrivateDataFn)
+{
+
+    Lut ->Eval16Fn = Eval16;
+    Lut ->DupDataFn = DupPrivateDataFn;
+    Lut ->FreeDataFn = FreePrivateDataFn;
+    Lut ->Data = PrivateData;
+}
 
 
 // ----------------------------------------------------------- Reverse interpolation
-
-
 // Here's how it goes. The derivative Df(x) of the function f is the linear
 // transformation that best approximates f near the point x. It can be represented
 // by a matrix A whose entries are the partial derivatives of the components of f
@@ -693,15 +1494,12 @@
 // if you have a "good enough" initial guess.
 
 
-#define JACOBIAN_EPSILON            0.001
+#define JACOBIAN_EPSILON            0.001f
 #define INVERSION_MAX_ITERATIONS    30
 
-
-
 // Increment with reflexion on boundary
-
 static
-void IncDelta(double *Val)
+void IncDelta(cmsFloat32Number *Val)
 {
     if (*Val < (1.0 - JACOBIAN_EPSILON))
 
@@ -714,159 +1512,131 @@
 
 
 
+// Euclidean distance between two vectors of n elements each one
 static
-void ToEncoded(WORD Encoded[3], LPVEC3 Float)
-{
-    Encoded[0] = (WORD) floor(Float->n[0] * 65535.0 + 0.5);
-    Encoded[1] = (WORD) floor(Float->n[1] * 65535.0 + 0.5);
-    Encoded[2] = (WORD) floor(Float->n[2] * 65535.0 + 0.5);
-}
-
-static
-void FromEncoded(LPVEC3 Float, WORD Encoded[3])
+cmsFloat32Number EuclideanDistance(cmsFloat32Number a[], cmsFloat32Number b[], int n)
 {
-    Float->n[0] = Encoded[0] / 65535.0;
-    Float->n[1] = Encoded[1] / 65535.0;
-    Float->n[2] = Encoded[2] / 65535.0;
-}
-
-// Evaluates the CLUT part of a LUT (4 -> 3 only)
-static
-void EvalLUTdoubleKLab(LPLUT Lut, const VEC3* In, WORD FixedK, LPcmsCIELab Out)
-{
-    WORD wIn[4], wOut[3];
-
-    wIn[0] = (WORD) floor(In ->n[0] * 65535.0 + 0.5);
-    wIn[1] = (WORD) floor(In ->n[1] * 65535.0 + 0.5);
-    wIn[2] = (WORD) floor(In ->n[2] * 65535.0 + 0.5);
-    wIn[3] = FixedK;
+    cmsFloat32Number sum = 0;
+    int i;
 
-    cmsEvalLUT(Lut, wIn, wOut);
-    cmsLabEncoded2Float(Out, wOut);
-}
-
-// Builds a Jacobian CMY->Lab
-
-static
-void ComputeJacobianLab(LPLUT Lut, LPMAT3 Jacobian, const VEC3* Colorant, WORD K)
-{
-    VEC3 ColorantD;
-    cmsCIELab Lab, LabD;
-    int  j;
-
-    EvalLUTdoubleKLab(Lut, Colorant, K, &Lab);
-
+    for (i=0; i < n; i++) {
+        cmsFloat32Number dif = b[i] - a[i];
+        sum +=  dif * dif;
+    }
 
-    for (j = 0; j < 3; j++) {
-
-        ColorantD.n[0] = Colorant ->n[0];
-        ColorantD.n[1] = Colorant ->n[1];
-        ColorantD.n[2] = Colorant ->n[2];
-
-        IncDelta(&ColorantD.n[j]);
-
-        EvalLUTdoubleKLab(Lut, &ColorantD, K, &LabD);
-
-        Jacobian->v[0].n[j] = ((LabD.L - Lab.L) / JACOBIAN_EPSILON);
-        Jacobian->v[1].n[j] = ((LabD.a - Lab.a) / JACOBIAN_EPSILON);
-        Jacobian->v[2].n[j] = ((LabD.b - Lab.b) / JACOBIAN_EPSILON);
-
-    }
+    return sqrtf(sum);
 }
 
 
-// Evaluate a LUT in reverse direction. It only searches on 3->3 LUT, but It
-// can be used on CMYK -> Lab LUT to obtain black preservation.
-// Target holds LabK in this case
-
+// Evaluate a LUT in reverse direction. It only searches on 3->3 LUT. Uses Newton method
+//
 // x1 <- x - [J(x)]^-1 * f(x)
-
+//
+// lut: The LUT on where to do the search
+// Target: LabK, 3 values of Lab plus destination K which is fixed
+// Result: The obtained CMYK
+// Hint:   Location where begin the search
 
-LCMSAPI double LCMSEXPORT cmsEvalLUTreverse(LPLUT Lut, WORD Target[], WORD Result[], LPWORD Hint)
+cmsBool CMSEXPORT cmsPipelineEvalReverseFloat(cmsFloat32Number Target[],
+                                              cmsFloat32Number Result[],
+                                              cmsFloat32Number Hint[],
+                                              const cmsPipeline* lut)
 {
-    int      i;
-    double     error, LastError = 1E20;
-    cmsCIELab  fx, Goal;
-    VEC3       tmp, tmp2, x;
-    MAT3       Jacobian;
-    WORD       FixedK;
-    WORD       LastResult[4];
+    cmsUInt32Number  i, j;
+    cmsFloat64Number  error, LastError = 1E20;
+    cmsFloat32Number  fx[4], x[4], xd[4], fxd[4];
+    cmsVEC3 tmp, tmp2;
+    cmsMAT3 Jacobian;
+    cmsFloat64Number LastResult[4];
 
 
-    // This is our Lab goal
-    cmsLabEncoded2Float(&Goal, Target);
-
-    // Special case for CMYK->Lab
+    // Only 3->3 and 4->3 are supported
+    if (lut ->InputChannels != 3 && lut ->InputChannels != 4) return FALSE;
+    if (lut ->OutputChannels != 3) return FALSE;
 
-    if (Lut ->InputChan == 4)
-            FixedK = Target[3];
-    else
-            FixedK = 0;
-
+    // Mark result of -1
+    LastResult[0] = LastResult[1] = LastResult[2] = -1.0f;
 
     // Take the hint as starting point if specified
-
     if (Hint == NULL) {
 
-        // Begin at any point, we choose 1/3 of neutral CMY gray
-
-        x.n[0] = x.n[1] = x.n[2] = 0.3;
-
+        // Begin at any point, we choose 1/3 of CMY axis
+        x[0] = x[1] = x[2] = 0.3f;
     }
     else {
 
-        FromEncoded(&x, Hint);
+        // Only copy 3 channels from hint...
+        for (j=0; j < 3; j++)
+            x[j] = Hint[j];
     }
 
+    // If Lut is 4-dimensions, then grab target[3], which is fixed
+    if (lut ->InputChannels == 4) {
+        x[3] = Target[3];
+    }
+    else x[3] = 0; // To keep lint happy
+
 
     // Iterate
-
     for (i = 0; i < INVERSION_MAX_ITERATIONS; i++) {
 
         // Get beginning fx
-        EvalLUTdoubleKLab(Lut, &x, FixedK, &fx);
+        cmsPipelineEvalFloat(x, fx, lut);
 
         // Compute error
-        error = cmsDeltaE(&fx, &Goal);
+        error = EuclideanDistance(fx, Target, 3);
 
         // If not convergent, return last safe value
         if (error >= LastError)
             break;
 
         // Keep latest values
-        LastError = error;
+        LastError     = error;
+        for (j=0; j < lut ->InputChannels; j++)
+                Result[j] = x[j];
+
+        // Found an exact match?
+        if (error <= 0)
+            break;
+
+        // Obtain slope (the Jacobian)
+        for (j = 0; j < 3; j++) {
 
-        ToEncoded(LastResult, &x);
-        LastResult[3] = FixedK;
+            xd[0] = x[0];
+            xd[1] = x[1];
+            xd[2] = x[2];
+            xd[3] = x[3];  // Keep fixed channel
+
+            IncDelta(&xd[j]);
 
-        // Obtain slope
-        ComputeJacobianLab(Lut, &Jacobian, &x, FixedK);
+            cmsPipelineEvalFloat(xd, fxd, lut);
+
+            Jacobian.v[0].n[j] = ((fxd[0] - fx[0]) / JACOBIAN_EPSILON);
+            Jacobian.v[1].n[j] = ((fxd[1] - fx[1]) / JACOBIAN_EPSILON);
+            Jacobian.v[2].n[j] = ((fxd[2] - fx[2]) / JACOBIAN_EPSILON);
+        }
 
         // Solve system
-        tmp2.n[0] = fx.L - Goal.L;
-        tmp2.n[1] = fx.a - Goal.a;
-        tmp2.n[2] = fx.b - Goal.b;
+        tmp2.n[0] = fx[0] - Target[0];
+        tmp2.n[1] = fx[1] - Target[1];
+        tmp2.n[2] = fx[2] - Target[2];
 
-        if (!MAT3solve(&tmp, &Jacobian, &tmp2))
-            break;
+        if (!_cmsMAT3solve(&tmp, &Jacobian, &tmp2))
+            return FALSE;
 
         // Move our guess
-        x.n[0] -= tmp.n[0];
-        x.n[1] -= tmp.n[1];
-        x.n[2] -= tmp.n[2];
+        x[0] -= (cmsFloat32Number) tmp.n[0];
+        x[1] -= (cmsFloat32Number) tmp.n[1];
+        x[2] -= (cmsFloat32Number) tmp.n[2];
 
         // Some clipping....
-        VEC3saturate(&x);
+        for (j=0; j < 3; j++) {
+            if (x[j] < 0) x[j] = 0;
+            else
+                if (x[j] > 1.0) x[j] = 1.0;
+        }
     }
 
-    Result[0] = LastResult[0];
-    Result[1] = LastResult[1];
-    Result[2] = LastResult[2];
-    Result[3] = LastResult[3];
-
-    return LastError;
-
+    return TRUE;
 }
 
-
-
--- a/src/share/native/sun/java2d/cmm/lcms/cmsmatsh.c	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,411 +0,0 @@
-/*
- * 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// This file is available under and governed by the GNU General Public
-// License version 2 only, as published by the Free Software Foundation.
-// However, the following notice accompanied the original version of this
-// file:
-//
-//
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the Software
-// is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
-// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-#include "lcms.h"
-
-
-// Shaper/Matrix handling
-// This routines handles the matrix-shaper method. A note about domain
-// is here required. If the shaper-matrix is invoked on INPUT profiles,
-// after the shaper process, we have a value between 0 and 0xFFFF. Thus,
-// for proper matrix handling, we must convert it to 15fix16, so
-// ToFixedDomain might be called. But cmsLinearInterpFixed() returns
-// data yet in fixed point, so no additional process is required.
-// Then, we obtain data on 15.16, so we need to shift >> by 1 to
-// obtain 1.15 PCS format.
-
-// On OUTPUT profiles, things are inverse, we must first expand 1 bit
-// by shifting left, and then convert result between 0 and 1.000 to
-// RGB, so FromFixedDomain() must be called before pass values to
-// shaper. Trickly, there is a situation where this shifts works
-// little different. Sometimes, lcms smelts input/output
-// matrices into a single, one shaper, process. In such cases, since
-// input is encoded from 0 to 0xffff, we must first use the shaper and
-// then the matrix, an additional FromFixedDomain() must be used to
-// accomodate output values.
-
-// For a sake of simplicity, I will handle this three behaviours
-// with different routines, so the flags MATSHAPER_INPUT and MATSHAPER_OUTPUT
-// can be conbined to signal smelted matrix-shapers
-
-
-
-static
-int ComputeTables(LPGAMMATABLE Table[3], LPWORD Out[3], LPL16PARAMS p16)
-{
-    int i, AllLinear;
-
-       cmsCalcL16Params(Table[0] -> nEntries, p16);
-
-       AllLinear = 0;
-       for (i=0; i < 3; i++)
-       {
-        LPWORD PtrW;
-
-        PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * p16 -> nSamples);
-
-        if (PtrW == NULL) return -1;  // Signal error
-
-        CopyMemory(PtrW, Table[i] -> GammaTable, sizeof(WORD) * Table[i] -> nEntries);
-
-        Out[i] = PtrW;      // Set table pointer
-
-        // Linear after all?
-
-        AllLinear   += cmsIsLinear(PtrW, p16 -> nSamples);
-       }
-
-       // If is all linear, then supress table interpolation (this
-       // will speed greately some trivial operations.
-       // Return 1 if present, 0 if all linear
-
-
-       if (AllLinear != 3) return 1;
-
-       return 0;
-
-}
-
-
-LPMATSHAPER cmsAllocMatShaper2(LPMAT3 Matrix, LPGAMMATABLE In[], LPGAMMATABLE Out[], DWORD Behaviour)
-{
-       LPMATSHAPER NewMatShaper;
-       int rc;
-
-       NewMatShaper = (LPMATSHAPER) _cmsMalloc(sizeof(MATSHAPER));
-       if (NewMatShaper)
-              ZeroMemory(NewMatShaper, sizeof(MATSHAPER));
-
-       NewMatShaper->dwFlags = Behaviour & (MATSHAPER_ALLSMELTED);
-
-       // Fill matrix part
-
-       MAT3toFix(&NewMatShaper -> Matrix, Matrix);
-
-       // Reality check
-
-       if (!MAT3isIdentity(&NewMatShaper -> Matrix, 0.00001))
-                     NewMatShaper -> dwFlags |= MATSHAPER_HASMATRIX;
-
-       // Now, on the table characteristics
-
-       if (Out) {
-
-            rc = ComputeTables(Out, NewMatShaper ->L, &NewMatShaper ->p16);
-            if (rc < 0) {
-                 cmsFreeMatShaper(NewMatShaper);
-                 return NULL;
-            }
-            if (rc == 1) NewMatShaper -> dwFlags |= MATSHAPER_HASSHAPER;
-       }
-
-
-       if (In) {
-
-            rc = ComputeTables(In, NewMatShaper ->L2, &NewMatShaper ->p2_16);
-            if (rc < 0) {
-                cmsFreeMatShaper(NewMatShaper);
-                return NULL;
-            }
-            if (rc == 1) NewMatShaper -> dwFlags |= MATSHAPER_HASINPSHAPER;
-       }
-
-
-       return NewMatShaper;
-
-}
-
-
-
-// Creation & Destruction
-
-LPMATSHAPER cmsAllocMatShaper(LPMAT3 Matrix, LPGAMMATABLE Tables[], DWORD Behaviour)
-{
-       LPMATSHAPER NewMatShaper;
-       int i, AllLinear;
-
-           if (Matrix == NULL) return NULL;
-           for (i=0; i < 3; i++) {
-
-                   if (Tables[i] == NULL) return NULL;
-           }
-
-       NewMatShaper = (LPMATSHAPER) _cmsMalloc(sizeof(MATSHAPER));
-       if (NewMatShaper)
-              ZeroMemory(NewMatShaper, sizeof(MATSHAPER));
-
-       NewMatShaper->dwFlags = Behaviour & (MATSHAPER_ALLSMELTED);
-
-       // Fill matrix part
-
-       MAT3toFix(&NewMatShaper -> Matrix, Matrix);
-
-       // Reality check
-
-       if (!MAT3isIdentity(&NewMatShaper -> Matrix, 0.00001))
-                     NewMatShaper -> dwFlags |= MATSHAPER_HASMATRIX;
-
-       // Now, on the table characteristics
-       cmsCalcL16Params(Tables[0] -> nEntries, &NewMatShaper -> p16);
-
-       // Copy tables
-
-       AllLinear = 0;
-       for (i=0; i < 3; i++) {
-
-        LPWORD PtrW;
-
-        PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewMatShaper -> p16.nSamples);
-
-        if (PtrW == NULL) {
-              cmsFreeMatShaper(NewMatShaper);
-              return NULL;
-        }
-
-        CopyMemory(PtrW, Tables[i] -> GammaTable,
-                            sizeof(WORD) * Tables[i] -> nEntries);
-
-        NewMatShaper -> L[i] = PtrW;      // Set table pointer
-
-        // Linear after all?
-
-        AllLinear   += cmsIsLinear(PtrW, NewMatShaper -> p16.nSamples);
-       }
-
-       // If is all linear, then supress table interpolation (this
-       // will speed greately some trivial operations
-
-       if (AllLinear != 3)
-              NewMatShaper -> dwFlags |= MATSHAPER_HASSHAPER;
-
-       return NewMatShaper;
-}
-
-
-
-// Free associated memory
-
-void cmsFreeMatShaper(LPMATSHAPER MatShaper)
-{
-       int i;
-
-       if (!MatShaper) return;
-
-       for (i=0; i < 3; i++)
-       {
-              if (MatShaper -> L[i]) _cmsFree(MatShaper ->L[i]);
-              if (MatShaper -> L2[i]) _cmsFree(MatShaper ->L2[i]);
-       }
-
-       _cmsFree(MatShaper);
-}
-
-
-// All smelted must postpose gamma to last stage.
-
-static
-void AllSmeltedBehaviour(LPMATSHAPER MatShaper, WORD In[], WORD Out[])
-{
-
-       WORD tmp[3];
-       WVEC3 InVect, OutVect;
-
-       if (MatShaper -> dwFlags & MATSHAPER_HASINPSHAPER)
-       {
-       InVect.n[VX] = cmsLinearInterpFixed(In[0], MatShaper -> L2[0], &MatShaper -> p2_16);
-       InVect.n[VY] = cmsLinearInterpFixed(In[1], MatShaper -> L2[1], &MatShaper -> p2_16);
-       InVect.n[VZ] = cmsLinearInterpFixed(In[2], MatShaper -> L2[2], &MatShaper -> p2_16);
-       }
-       else
-       {
-            InVect.n[VX] = ToFixedDomain(In[0]);
-            InVect.n[VY] = ToFixedDomain(In[1]);
-            InVect.n[VZ] = ToFixedDomain(In[2]);
-       }
-
-
-       if (MatShaper -> dwFlags & MATSHAPER_HASMATRIX)
-       {
-
-             MAT3evalW(&OutVect, &MatShaper -> Matrix, &InVect);
-       }
-       else {
-
-           OutVect.n[VX] = InVect.n[VX];
-           OutVect.n[VY] = InVect.n[VY];
-           OutVect.n[VZ] = InVect.n[VZ];
-       }
-
-
-       tmp[0] = _cmsClampWord(FromFixedDomain(OutVect.n[VX]));
-       tmp[1] = _cmsClampWord(FromFixedDomain(OutVect.n[VY]));
-       tmp[2] = _cmsClampWord(FromFixedDomain(OutVect.n[VZ]));
-
-
-
-       if (MatShaper -> dwFlags & MATSHAPER_HASSHAPER)
-       {
-       Out[0] = cmsLinearInterpLUT16(tmp[0], MatShaper -> L[0], &MatShaper -> p16);
-       Out[1] = cmsLinearInterpLUT16(tmp[1], MatShaper -> L[1], &MatShaper -> p16);
-       Out[2] = cmsLinearInterpLUT16(tmp[2], MatShaper -> L[2], &MatShaper -> p16);
-       }
-       else
-       {
-           Out[0] = tmp[0];
-           Out[1] = tmp[1];
-           Out[2] = tmp[2];
-       }
-
-}
-
-
-static
-void InputBehaviour(LPMATSHAPER MatShaper, WORD In[], WORD Out[])
-{
-       WVEC3 InVect, OutVect;
-
-
-       if (MatShaper -> dwFlags & MATSHAPER_HASSHAPER)
-       {
-       InVect.n[VX] = cmsLinearInterpFixed(In[0], MatShaper -> L[0], &MatShaper -> p16);
-       InVect.n[VY] = cmsLinearInterpFixed(In[1], MatShaper -> L[1], &MatShaper -> p16);
-       InVect.n[VZ] = cmsLinearInterpFixed(In[2], MatShaper -> L[2], &MatShaper -> p16);
-       }
-       else
-       {
-       InVect.n[VX] = ToFixedDomain(In[0]);
-       InVect.n[VY] = ToFixedDomain(In[1]);
-       InVect.n[VZ] = ToFixedDomain(In[2]);
-       }
-
-       if (MatShaper -> dwFlags & MATSHAPER_HASMATRIX)
-       {
-              MAT3evalW(&OutVect, &MatShaper -> Matrix, &InVect);
-       }
-       else
-       {
-       OutVect =  InVect;
-       }
-
-       // PCS in 1Fixed15 format, adjusting
-
-       Out[0] = _cmsClampWord((OutVect.n[VX]) >> 1);
-       Out[1] = _cmsClampWord((OutVect.n[VY]) >> 1);
-       Out[2] = _cmsClampWord((OutVect.n[VZ]) >> 1);
-
-}
-
-
-static
-void OutputBehaviour(LPMATSHAPER MatShaper, WORD In[], WORD Out[])
-{
-       WVEC3 InVect, OutVect;
-       int i;
-
-       // We need to convert from XYZ to RGB, here we must
-       // shift << 1 to pass between 1.15 to 15.16 formats
-
-       InVect.n[VX] = (Fixed32) In[0] << 1;
-       InVect.n[VY] = (Fixed32) In[1] << 1;
-       InVect.n[VZ] = (Fixed32) In[2] << 1;
-
-       if (MatShaper -> dwFlags & MATSHAPER_HASMATRIX)
-       {
-              MAT3evalW(&OutVect, &MatShaper -> Matrix, &InVect);
-       }
-       else
-       {
-       OutVect = InVect;
-       }
-
-
-       if (MatShaper -> dwFlags & MATSHAPER_HASSHAPER)
-       {
-              for (i=0; i < 3; i++)
-              {
-
-              Out[i] = cmsLinearInterpLUT16(
-                     _cmsClampWord(FromFixedDomain(OutVect.n[i])),
-                     MatShaper -> L[i],
-                     &MatShaper ->p16);
-              }
-       }
-       else
-       {
-       // Result from fixed domain to RGB
-
-       Out[0] = _cmsClampWord(FromFixedDomain(OutVect.n[VX]));
-       Out[1] = _cmsClampWord(FromFixedDomain(OutVect.n[VY]));
-       Out[2] = _cmsClampWord(FromFixedDomain(OutVect.n[VZ]));
-       }
-
-}
-
-
-// Master on evaluating shapers, 3 different behaviours
-
-void cmsEvalMatShaper(LPMATSHAPER MatShaper, WORD In[], WORD Out[])
-{
-
-       if ((MatShaper -> dwFlags & MATSHAPER_ALLSMELTED) == MATSHAPER_ALLSMELTED)
-       {
-              AllSmeltedBehaviour(MatShaper, In, Out);
-              return;
-       }
-       if (MatShaper -> dwFlags & MATSHAPER_INPUT)
-       {
-              InputBehaviour(MatShaper, In, Out);
-              return;
-       }
-
-       OutputBehaviour(MatShaper, In, Out);
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,346 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+
+
+#include "lcms2_internal.h"
+
+#ifdef CMS_USE_BIG_ENDIAN
+
+static
+void byteReverse(cmsUInt8Number * buf, cmsUInt32Number longs)
+{
+    do {
+
+        cmsUInt32Number t = _cmsAdjustEndianess32(*(cmsUInt32Number *) buf);
+        *(cmsUInt32Number *) buf = t;
+        buf += sizeof(cmsUInt32Number);
+
+    } while (--longs);
+
+}
+
+#else
+#define byteReverse(buf, len)
+#endif
+
+
+typedef struct {
+
+    cmsUInt32Number buf[4];
+    cmsUInt32Number bits[2];
+    cmsUInt8Number in[64];
+    cmsContext ContextID;
+
+} _cmsMD5;
+
+#define F1(x, y, z) (z ^ (x & (y ^ z)))
+#define F2(x, y, z) F1(z, x, y)
+#define F3(x, y, z) (x ^ y ^ z)
+#define F4(x, y, z) (y ^ (x | ~z))
+
+#define STEP(f, w, x, y, z, data, s) \
+    ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
+
+
+static
+void MD5_Transform(cmsUInt32Number buf[4], cmsUInt32Number in[16])
+
+{
+    register cmsUInt32Number a, b, c, d;
+
+    a = buf[0];
+    b = buf[1];
+    c = buf[2];
+    d = buf[3];
+
+    STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
+    STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
+    STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
+    STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
+    STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
+    STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
+    STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
+    STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
+    STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
+    STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
+    STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
+    STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
+    STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
+    STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
+    STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
+    STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
+
+    STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
+    STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
+    STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
+    STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
+    STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
+    STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
+    STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
+    STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
+    STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
+    STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
+    STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
+    STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
+    STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
+    STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
+    STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
+    STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
+
+    STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
+    STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
+    STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
+    STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
+    STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
+    STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
+    STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
+    STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
+    STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
+    STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
+    STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
+    STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
+    STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
+    STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
+    STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
+    STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
+
+    STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
+    STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
+    STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
+    STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
+    STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
+    STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
+    STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
+    STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
+    STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
+    STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
+    STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
+    STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
+    STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
+    STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
+    STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
+    STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
+
+    buf[0] += a;
+    buf[1] += b;
+    buf[2] += c;
+    buf[3] += d;
+}
+
+
+// Create a MD5 object
+static
+cmsHANDLE  MD5alloc(cmsContext ContextID)
+{
+    _cmsMD5* ctx = (_cmsMD5*) _cmsMallocZero(ContextID, sizeof(_cmsMD5));
+    if (ctx == NULL) return NULL;
+
+    ctx ->ContextID = ContextID;
+
+    ctx->buf[0] = 0x67452301;
+    ctx->buf[1] = 0xefcdab89;
+    ctx->buf[2] = 0x98badcfe;
+    ctx->buf[3] = 0x10325476;
+
+    ctx->bits[0] = 0;
+    ctx->bits[1] = 0;
+
+    return (cmsHANDLE) ctx;
+}
+
+
+static
+void MD5add(cmsHANDLE Handle, cmsUInt8Number* buf, cmsUInt32Number len)
+{
+    _cmsMD5* ctx = (_cmsMD5*) Handle;
+    cmsUInt32Number t;
+
+    t = ctx->bits[0];
+    if ((ctx->bits[0] = t + (len << 3)) < t)
+        ctx->bits[1]++;
+
+    ctx->bits[1] += len >> 29;
+
+    t = (t >> 3) & 0x3f;
+
+    if (t) {
+
+        cmsUInt8Number *p = (cmsUInt8Number *) ctx->in + t;
+
+        t = 64 - t;
+        if (len < t) {
+            memmove(p, buf, len);
+            return;
+        }
+
+        memmove(p, buf, t);
+        byteReverse(ctx->in, 16);
+
+        MD5_Transform(ctx->buf, (cmsUInt32Number *) ctx->in);
+        buf += t;
+        len -= t;
+    }
+
+    while (len >= 64) {
+        memmove(ctx->in, buf, 64);
+        byteReverse(ctx->in, 16);
+        MD5_Transform(ctx->buf, (cmsUInt32Number *) ctx->in);
+        buf += 64;
+        len -= 64;
+    }
+
+    memmove(ctx->in, buf, len);
+}
+
+// Destroy the object and return the checksum
+static
+void MD5finish(cmsProfileID* ProfileID,  cmsHANDLE Handle)
+{
+    _cmsMD5* ctx = (_cmsMD5*) Handle;
+    cmsUInt32Number count;
+    cmsUInt8Number *p;
+
+    count = (ctx->bits[0] >> 3) & 0x3F;
+
+    p = ctx->in + count;
+    *p++ = 0x80;
+
+    count = 64 - 1 - count;
+
+    if (count < 8) {
+
+        memset(p, 0, count);
+        byteReverse(ctx->in, 16);
+        MD5_Transform(ctx->buf, (cmsUInt32Number *) ctx->in);
+
+        memset(ctx->in, 0, 56);
+    } else {
+        memset(p, 0, count - 8);
+    }
+    byteReverse(ctx->in, 14);
+
+    ((cmsUInt32Number *) ctx->in)[14] = ctx->bits[0];
+    ((cmsUInt32Number *) ctx->in)[15] = ctx->bits[1];
+
+    MD5_Transform(ctx->buf, (cmsUInt32Number *) ctx->in);
+
+    byteReverse((cmsUInt8Number *) ctx->buf, 4);
+    memmove(ProfileID ->ID8, ctx->buf, 16);
+
+    _cmsFree(ctx ->ContextID, ctx);
+}
+
+
+
+// Assuming io points to an ICC profile, compute and store MD5 checksum
+// In the header, rendering intentent, attributes and ID should be set to zero
+// before computing MD5 checksum (per 6.1.13 in ICC spec)
+
+cmsBool CMSEXPORT cmsMD5computeID(cmsHPROFILE hProfile)
+{
+    cmsContext   ContextID;
+    cmsUInt32Number BytesNeeded;
+    cmsUInt8Number* Mem = NULL;
+    cmsHANDLE  MD5 = NULL;
+    _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+    _cmsICCPROFILE Keep;
+
+    _cmsAssert(hProfile != NULL);
+
+    ContextID = cmsGetProfileContextID(hProfile);
+
+    // Save a copy of the profile header
+    memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
+
+    // Set RI, attributes and ID
+    memset(&Icc ->attributes, 0, sizeof(Icc ->attributes));
+    Icc ->RenderingIntent = 0;
+    memset(&Icc ->ProfileID, 0, sizeof(Icc ->ProfileID));
+
+    // Compute needed storage
+    if (!cmsSaveProfileToMem(hProfile, NULL, &BytesNeeded)) goto Error;
+
+    // Allocate memory
+    Mem = (cmsUInt8Number*) _cmsMalloc(ContextID, BytesNeeded);
+    if (Mem == NULL) goto Error;
+
+    // Save to temporary storage
+    if (!cmsSaveProfileToMem(hProfile, Mem, &BytesNeeded)) goto Error;
+
+    // Create MD5 object
+    MD5 = MD5alloc(ContextID);
+    if (MD5 == NULL) goto Error;
+
+    // Add all bytes
+    MD5add(MD5, Mem, BytesNeeded);
+
+    // Temp storage is no longer needed
+    _cmsFree(ContextID, Mem);
+
+    // Restore header
+    memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
+
+    // And store the ID
+    MD5finish(&Icc ->ProfileID,  MD5);
+    return TRUE;
+
+Error:
+
+    // Free resources as something went wrong
+    if (MD5 != NULL) _cmsFree(ContextID, MD5);
+    if (Mem != NULL) _cmsFree(ContextID, Mem);
+    memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
+    return FALSE;
+}
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,447 +49,105 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// Vector & Matrix stuff
-
-#include "lcms.h"
-
-
-void cdecl VEC3init(LPVEC3 r, double x, double y, double z);
-void cdecl VEC3initF(LPWVEC3 r, double x, double y, double z);
-void cdecl VEC3toFix(LPWVEC3 r, LPVEC3 v);
-void cdecl VEC3scaleFix(LPWORD r, LPWVEC3 Scale);
-void cdecl VEC3swap(LPVEC3 a, LPVEC3 b);
-void cdecl VEC3divK(LPVEC3 r, LPVEC3 v, double d);
-void cdecl VEC3perK(LPVEC3 r, LPVEC3 v, double d);
-void cdecl VEC3perComp(LPVEC3 r, LPVEC3 a, LPVEC3 b);
-void cdecl VEC3minus(LPVEC3 r, LPVEC3 a, LPVEC3 b);
-void cdecl VEC3scaleAndCut(LPWVEC3 r, LPVEC3 v, double d);
-void cdecl VEC3cross(LPVEC3 r, LPVEC3 u, LPVEC3 v);
-void cdecl VEC3saturate(LPVEC3 v);
-
-double cdecl VEC3length(LPVEC3 a);
-double cdecl VEC3distance(LPVEC3 a, LPVEC3 b);
-
-
-void      cdecl MAT3identity(LPMAT3 a);
-void      cdecl MAT3per(LPMAT3 r, LPMAT3 a, LPMAT3 b);
-int       cdecl MAT3inverse(LPMAT3 a, LPMAT3 b);
-LCMSBOOL  cdecl MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b);
-double    cdecl MAT3det(LPMAT3 m);
-void      cdecl MAT3eval(LPVEC3 r, LPMAT3 a, LPVEC3 v);
-void      cdecl MAT3toFix(LPWMAT3 r, LPMAT3 v);
-void      cdecl MAT3evalW(LPWVEC3 r, LPWMAT3 a, LPWVEC3 v);
-void      cdecl MAT3perK(LPMAT3 r, LPMAT3 v, double d);
-void      cdecl MAT3scaleAndCut(LPWMAT3 r, LPMAT3 v, double d);
+//
+//---------------------------------------------------------------------------------
+//
 
-// --------------------- Implementation ----------------------------
-
-#define DSWAP(x, y)     {double tmp = (x); (x)=(y); (y)=tmp;}
-
-
-
-#ifdef USE_ASSEMBLER
-
-
-#ifdef _MSC_VER
-#pragma warning(disable : 4033)
-#pragma warning(disable : 4035)
-#endif
-
-
-
-Fixed32 FixedMul(Fixed32 a, Fixed32 b)
-{
-       ASM {
-
-              mov    eax, ss:a
-              mov    edx, ss:b
-              imul   edx
-              add    eax, 0x8000
-              adc    edx, 0
-              shrd   eax, edx, 16
-
-       }
-
-       RET(_EAX);
-}
-
-
+#include "lcms2_internal.h"
 
 
-Fixed32 FixedSquare(Fixed32 a)
-{
-       ASM {
-              pushf
-              push   edx
-              mov    eax, ss:a
-              imul   eax
-              add    eax, 0x8000
-              adc    edx, 0
-              shrd   eax, edx, 16
-              sar    eax, 16
-              pop    edx
-              popf
-       }
-
-       RET(_EAX);
-}
-
-
-
-
-// Linear intERPolation
-// a * (h - l) >> 16 + l
-
-Fixed32 FixedLERP(Fixed32 a, Fixed32 l, Fixed32 h)
-{
-       ASM {
-              mov    eax, dword ptr ss:h
-              mov    edx, dword ptr ss:l
-              push   edx
-              mov    ecx, dword ptr ss:a
-              sub    eax, edx
-              imul   ecx
-              add    eax, 0x8000
-              adc    edx, 0
-              shrd   eax, edx, 16
-              pop    edx
-              add    eax, edx
-       }
-
-       RET(_EAX);
-}
-
-
-// a as word is scaled by s as float
-
-WORD FixedScale(WORD a, Fixed32 s)
-{
-       ASM {
-
-              xor    eax,eax
-              mov    ax, ss:a        // This is faster that movzx  eax, ss:a
-              sal    eax, 16
-              mov    edx, ss:s
-              mul    edx
-              add    eax, 0x8000
-              adc    edx, 0
-              mov    eax, edx
-       }
-
-       RET(_EAX);
-}
-
-#ifdef _MSC_VER
-#pragma warning(default : 4033)
-#pragma warning(default : 4035)
-#endif
-
-#else
+#define DSWAP(x, y)     {cmsFloat64Number tmp = (x); (x)=(y); (y)=tmp;}
 
 
-// These are floating point versions for compilers that doesn't
-// support asm at all. Use with care, since this will slow down
-// all operations
-
-
-Fixed32 FixedMul(Fixed32 a, Fixed32 b)
-{
-#ifdef USE_INT64
-       LCMSULONGLONG l = (LCMSULONGLONG) (LCMSSLONGLONG) a * (LCMSULONGLONG) (LCMSSLONGLONG) b + (LCMSULONGLONG) 0x8000;
-       l >>= 16;
-       return (Fixed32) l;
-#else
-       return DOUBLE_TO_FIXED(FIXED_TO_DOUBLE(a) * FIXED_TO_DOUBLE(b));
-#endif
-}
-
-Fixed32 FixedSquare(Fixed32 a)
-{
-       return FixedMul(a, a);
-}
-
-
-Fixed32 FixedLERP(Fixed32 a, Fixed32 l, Fixed32 h)
+// Initiate a vector
+void CMSEXPORT _cmsVEC3init(cmsVEC3* r, cmsFloat64Number x, cmsFloat64Number y, cmsFloat64Number z)
 {
-#ifdef USE_INT64
-
-       LCMSULONGLONG dif = (LCMSULONGLONG) (h - l) * a + 0x8000;
-       dif = (dif >> 16) + l;
-       return (Fixed32) (dif);
-#else
-       double dif = h - l;
-
-       dif *= a;
-       dif /= 65536.0;
-       dif += l;
-
-       return (Fixed32) (dif + 0.5);
-#endif
-
-}
-
-
-WORD FixedScale(WORD a, Fixed32 s)
-{
-       return (WORD) (a * FIXED_TO_DOUBLE(s));
-}
-
-#endif
-
-
-#ifndef USE_INLINE
-
-Fixed32 ToFixedDomain(int a)
-{
-    return a + ((a + 0x7fff) / 0xffff);
-}
-
-
-int FromFixedDomain(Fixed32 a)
-{
-    return a - ((a + 0x7fff) >> 16);
+    r -> n[VX] = x;
+    r -> n[VY] = y;
+    r -> n[VZ] = z;
 }
 
-#endif
-
-
-
-// Initiate a vector (double version)
-
-
-void VEC3init(LPVEC3 r, double x, double y, double z)
-{
-       r -> n[VX] = x;
-       r -> n[VY] = y;
-       r -> n[VZ] = z;
-}
-
-// Init a vector (fixed version)
-
-void VEC3initF(LPWVEC3 r, double x, double y, double z)
-{
-       r -> n[VX] = DOUBLE_TO_FIXED(x);
-       r -> n[VY] = DOUBLE_TO_FIXED(y);
-       r -> n[VZ] = DOUBLE_TO_FIXED(z);
-}
-
-
-// Convert to fixed point encoding is 1.0 = 0xFFFF
-
-void VEC3toFix(LPWVEC3 r, LPVEC3 v)
-{
-       r -> n[VX] = DOUBLE_TO_FIXED(v -> n[VX]);
-       r -> n[VY] = DOUBLE_TO_FIXED(v -> n[VY]);
-       r -> n[VZ] = DOUBLE_TO_FIXED(v -> n[VZ]);
-}
-
-// Convert from fixed point
-
-void VEC3fromFix(LPVEC3 r, LPWVEC3 v)
-{
-       r -> n[VX] = FIXED_TO_DOUBLE(v -> n[VX]);
-       r -> n[VY] = FIXED_TO_DOUBLE(v -> n[VY]);
-       r -> n[VZ] = FIXED_TO_DOUBLE(v -> n[VZ]);
-}
-
-
-// Swap two double vectors
-
-void VEC3swap(LPVEC3 a, LPVEC3 b)
-{
-        DSWAP(a-> n[VX], b-> n[VX]);
-        DSWAP(a-> n[VY], b-> n[VY]);
-        DSWAP(a-> n[VZ], b-> n[VZ]);
-}
-
-// Divide a vector by a constant
-
-void VEC3divK(LPVEC3 r, LPVEC3 v, double d)
-{
-        double d_inv = 1./d;
-
-        r -> n[VX] = v -> n[VX] * d_inv;
-        r -> n[VY] = v -> n[VY] * d_inv;
-        r -> n[VZ] = v -> n[VZ] * d_inv;
-}
-
-// Multiply by a constant
-
-void VEC3perK(LPVEC3 r, LPVEC3 v, double d )
-{
-        r -> n[VX] = v -> n[VX] * d;
-        r -> n[VY] = v -> n[VY] * d;
-        r -> n[VZ] = v -> n[VZ] * d;
-}
-
-
-void VEC3perComp(LPVEC3 r, LPVEC3 a, LPVEC3 b)
-{
-       r -> n[VX] = a->n[VX]*b->n[VX];
-       r -> n[VY] = a->n[VY]*b->n[VY];
-       r -> n[VZ] = a->n[VZ]*b->n[VZ];
-}
-
-// Minus
-
-
-void VEC3minus(LPVEC3 r, LPVEC3 a, LPVEC3 b)
+// Vector substraction
+void CMSEXPORT _cmsVEC3minus(cmsVEC3* r, const cmsVEC3* a, const cmsVEC3* b)
 {
   r -> n[VX] = a -> n[VX] - b -> n[VX];
   r -> n[VY] = a -> n[VY] - b -> n[VY];
   r -> n[VZ] = a -> n[VZ] - b -> n[VZ];
 }
 
-
-// Check id two vectors are the same, allowing tolerance
-
-static
-LCMSBOOL RangeCheck(double l, double h, double v)
-{
-       return (v >= l && v <= h);
-}
-
-
-LCMSBOOL VEC3equal(LPWVEC3 a, LPWVEC3 b, double Tolerance)
-{
-       int i;
-       double c;
-
-       for (i=0; i < 3; i++)
-       {
-              c = FIXED_TO_DOUBLE(a -> n[i]);
-              if (!RangeCheck(c - Tolerance,
-                              c + Tolerance,
-                              FIXED_TO_DOUBLE(b->n[i]))) return FALSE;
-       }
-
-       return TRUE;
-}
-
-LCMSBOOL VEC3equalF(LPVEC3 a, LPVEC3 b, double Tolerance)
+// Vector cross product
+void CMSEXPORT _cmsVEC3cross(cmsVEC3* r, const cmsVEC3* u, const cmsVEC3* v)
 {
-       int i;
-       double c;
-
-       for (i=0; i < 3; i++)
-       {
-              c = a -> n[i];
-              if (!RangeCheck(c - Tolerance,
-                              c + Tolerance,
-                              b->n[i])) return FALSE;
-       }
-
-       return TRUE;
-}
-
-
-void VEC3scaleFix(LPWORD r, LPWVEC3 Scale)
-{
-       if (Scale -> n[VX] == 0x00010000L &&
-           Scale -> n[VY] == 0x00010000L &&
-           Scale -> n[VZ] == 0x00010000L) return;
-
-       r[0] = (WORD) FixedScale(r[0], Scale -> n[VX]);
-       r[1] = (WORD) FixedScale(r[1], Scale -> n[VY]);
-       r[2] = (WORD) FixedScale(r[2], Scale -> n[VZ]);
-
-}
-
-
-
-// Vector cross product
-
-void VEC3cross(LPVEC3 r, LPVEC3 u, LPVEC3 v)
-{
-
     r ->n[VX] = u->n[VY] * v->n[VZ] - v->n[VY] * u->n[VZ];
     r ->n[VY] = u->n[VZ] * v->n[VX] - v->n[VZ] * u->n[VX];
     r ->n[VZ] = u->n[VX] * v->n[VY] - v->n[VX] * u->n[VY];
 }
 
-
+// Vector dot product
+cmsFloat64Number CMSEXPORT _cmsVEC3dot(const cmsVEC3* u, const cmsVEC3* v)
+{
+    return u->n[VX] * v->n[VX] + u->n[VY] * v->n[VY] + u->n[VZ] * v->n[VZ];
+}
 
-// The vector size
-
-double VEC3length(LPVEC3 a)
+// Euclidean length
+cmsFloat64Number CMSEXPORT _cmsVEC3length(const cmsVEC3* a)
 {
     return sqrt(a ->n[VX] * a ->n[VX] +
                 a ->n[VY] * a ->n[VY] +
                 a ->n[VZ] * a ->n[VZ]);
 }
 
-
-// Saturate a vector into 0..1.0 range
-
-void VEC3saturate(LPVEC3 v)
+// Euclidean distance
+cmsFloat64Number CMSEXPORT _cmsVEC3distance(const cmsVEC3* a, const cmsVEC3* b)
 {
-    int i;
-    for (i=0; i < 3; i++) {
-        if (v ->n[i] < 0)
-                v ->n[i] = 0;
-        else
-        if (v ->n[i] > 1.0)
-                v ->n[i] = 1.0;
-    }
-}
-
-
-// Euclidean distance
-
-double VEC3distance(LPVEC3 a, LPVEC3 b)
-{
-    double d1 = a ->n[VX] - b ->n[VX];
-    double d2 = a ->n[VY] - b ->n[VY];
-    double d3 = a ->n[VZ] - b ->n[VZ];
+    cmsFloat64Number d1 = a ->n[VX] - b ->n[VX];
+    cmsFloat64Number d2 = a ->n[VY] - b ->n[VY];
+    cmsFloat64Number d3 = a ->n[VZ] - b ->n[VZ];
 
     return sqrt(d1*d1 + d2*d2 + d3*d3);
 }
 
 
-// Identity
-
 
-void MAT3identity(LPMAT3 a)
+// 3x3 Identity
+void CMSEXPORT _cmsMAT3identity(cmsMAT3* a)
 {
-        VEC3init(&a-> v[0], 1.0, 0.0, 0.0);
-        VEC3init(&a-> v[1], 0.0, 1.0, 0.0);
-        VEC3init(&a-> v[2], 0.0, 0.0, 1.0);
+    _cmsVEC3init(&a-> v[0], 1.0, 0.0, 0.0);
+    _cmsVEC3init(&a-> v[1], 0.0, 1.0, 0.0);
+    _cmsVEC3init(&a-> v[2], 0.0, 0.0, 1.0);
+}
+
+static
+cmsBool CloseEnough(cmsFloat64Number a, cmsFloat64Number b)
+{
+    return fabs(b - a) < (1.0 / 65535.0);
 }
 
 
+cmsBool CMSEXPORT _cmsMAT3isIdentity(const cmsMAT3* a)
+{
+    cmsMAT3 Identity;
+    int i, j;
+
+    _cmsMAT3identity(&Identity);
+
+    for (i=0; i < 3; i++)
+        for (j=0; j < 3; j++)
+            if (!CloseEnough(a ->v[i].n[j], Identity.v[i].n[j])) return FALSE;
+
+    return TRUE;
+}
 
 
-// Check if matrix is Identity. Allow a tolerance as %
-
-LCMSBOOL MAT3isIdentity(LPWMAT3 a, double Tolerance)
-{
-       int i;
-       MAT3 Idd;
-       WMAT3 Idf;
-
-       MAT3identity(&Idd);
-       MAT3toFix(&Idf, &Idd);
-
-       for (i=0; i < 3; i++)
-              if (!VEC3equal(&a -> v[i], &Idf.v[i], Tolerance)) return FALSE;
-
-       return TRUE;
-
-}
-
 // Multiply two matrices
-
-
-void MAT3per(LPMAT3 r, LPMAT3 a, LPMAT3 b)
+void CMSEXPORT _cmsMAT3per(cmsMAT3* r, const cmsMAT3* a, const cmsMAT3* b)
 {
 #define ROWCOL(i, j) \
     a->v[i].n[0]*b->v[0].n[j] + a->v[i].n[1]*b->v[1].n[j] + a->v[i].n[2]*b->v[2].n[j]
 
-    VEC3init(&r-> v[0], ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2));
-    VEC3init(&r-> v[1], ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2));
-    VEC3init(&r-> v[2], ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2));
+    _cmsVEC3init(&r-> v[0], ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2));
+    _cmsVEC3init(&r-> v[1], ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2));
+    _cmsVEC3init(&r-> v[2], ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2));
 
 #undef ROWCOL //(i, j)
 }
@@ -496,350 +155,50 @@
 
 
 // Inverse of a matrix b = a^(-1)
-// Gauss-Jordan elimination with partial pivoting
-
-int MAT3inverse(LPMAT3 a, LPMAT3 b)
+cmsBool  CMSEXPORT _cmsMAT3inverse(const cmsMAT3* a, cmsMAT3* b)
 {
-    register int  i, j, max;
-
-    MAT3identity(b);
+   cmsFloat64Number det, c0, c1, c2;
 
-    // Loop over cols of a from left to right, eliminating above and below diag
-    for (j=0; j<3; j++) {   // Find largest pivot in column j among rows j..2
+   c0 =  a -> v[1].n[1]*a -> v[2].n[2] - a -> v[1].n[2]*a -> v[2].n[1];
+   c1 = -a -> v[1].n[0]*a -> v[2].n[2] + a -> v[1].n[2]*a -> v[2].n[0];
+   c2 =  a -> v[1].n[0]*a -> v[2].n[1] - a -> v[1].n[1]*a -> v[2].n[0];
 
-    max = j;                 // Row with largest pivot candidate
-    for (i=j+1; i<3; i++)
-        if (fabs(a -> v[i].n[j]) > fabs(a -> v[max].n[j]))
-            max = i;
+   det = a -> v[0].n[0]*c0 + a -> v[0].n[1]*c1 + a -> v[0].n[2]*c2;
 
-    // Swap rows max and j in a and b to put pivot on diagonal
-
-    VEC3swap(&a -> v[max], &a -> v[j]);
-    VEC3swap(&b -> v[max], &b -> v[j]);
+   if (fabs(det) < MATRIX_DET_TOLERANCE) return FALSE;  // singular matrix; can't invert
 
-    // Scale row j to have a unit diagonal
-
-    if (a -> v[j].n[j]==0.)
-        return -1;                 // singular matrix; can't invert
-
-    VEC3divK(&b-> v[j], &b -> v[j], a->v[j].n[j]);
-    VEC3divK(&a-> v[j], &a -> v[j], a->v[j].n[j]);
-
-    // Eliminate off-diagonal elems in col j of a, doing identical ops to b
-    for (i=0; i<3; i++)
+   b -> v[0].n[0] = c0/det;
+   b -> v[0].n[1] = (a -> v[0].n[2]*a -> v[2].n[1] - a -> v[0].n[1]*a -> v[2].n[2])/det;
+   b -> v[0].n[2] = (a -> v[0].n[1]*a -> v[1].n[2] - a -> v[0].n[2]*a -> v[1].n[1])/det;
+   b -> v[1].n[0] = c1/det;
+   b -> v[1].n[1] = (a -> v[0].n[0]*a -> v[2].n[2] - a -> v[0].n[2]*a -> v[2].n[0])/det;
+   b -> v[1].n[2] = (a -> v[0].n[2]*a -> v[1].n[0] - a -> v[0].n[0]*a -> v[1].n[2])/det;
+   b -> v[2].n[0] = c2/det;
+   b -> v[2].n[1] = (a -> v[0].n[1]*a -> v[2].n[0] - a -> v[0].n[0]*a -> v[2].n[1])/det;
+   b -> v[2].n[2] = (a -> v[0].n[0]*a -> v[1].n[1] - a -> v[0].n[1]*a -> v[1].n[0])/det;
 
-        if (i !=j) {
-                  VEC3 temp;
-
-          VEC3perK(&temp, &b -> v[j], a -> v[i].n[j]);
-          VEC3minus(&b -> v[i], &b -> v[i], &temp);
-
-          VEC3perK(&temp, &a -> v[j], a -> v[i].n[j]);
-          VEC3minus(&a -> v[i], &a -> v[i], &temp);
-    }
-    }
-
-    return 1;
+   return TRUE;
 }
 
 
 // Solve a system in the form Ax = b
-
-LCMSBOOL MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b)
+cmsBool  CMSEXPORT _cmsMAT3solve(cmsVEC3* x, cmsMAT3* a, cmsVEC3* b)
 {
-    MAT3 m, a_1;
+    cmsMAT3 m, a_1;
 
-    CopyMemory(&m, a, sizeof(MAT3));
+    memmove(&m, a, sizeof(cmsMAT3));
 
-    if (!MAT3inverse(&m, &a_1)) return FALSE;  // Singular matrix
+    if (!_cmsMAT3inverse(&m, &a_1)) return FALSE;  // Singular matrix
 
-    MAT3eval(x, &a_1, b);
+    _cmsMAT3eval(x, &a_1, b);
     return TRUE;
 }
 
-
-// The determinant
-
-double MAT3det(LPMAT3 m)
-{
-
-    double a1 = m ->v[VX].n[VX];
-    double a2 = m ->v[VX].n[VY];
-    double a3 = m ->v[VX].n[VZ];
-    double b1 = m ->v[VY].n[VX];
-    double b2 = m ->v[VY].n[VY];
-    double b3 = m ->v[VY].n[VZ];
-    double c1 = m ->v[VZ].n[VX];
-    double c2 = m ->v[VZ].n[VY];
-    double c3 = m ->v[VZ].n[VZ];
-
-
-    return a1*b2*c3 - a1*b3*c2 + a2*b3*c1 - a2*b1*c3 - a3*b1*c2 - a3*b2*c1;
-}
-
-
-// linear transform
-
-
-void MAT3eval(LPVEC3 r, LPMAT3 a, LPVEC3 v)
+// Evaluate a vector across a matrix
+void CMSEXPORT _cmsMAT3eval(cmsVEC3* r, const cmsMAT3* a, const cmsVEC3* v)
 {
     r->n[VX] = a->v[0].n[VX]*v->n[VX] + a->v[0].n[VY]*v->n[VY] + a->v[0].n[VZ]*v->n[VZ];
     r->n[VY] = a->v[1].n[VX]*v->n[VX] + a->v[1].n[VY]*v->n[VY] + a->v[1].n[VZ]*v->n[VZ];
     r->n[VZ] = a->v[2].n[VX]*v->n[VX] + a->v[2].n[VY]*v->n[VY] + a->v[2].n[VZ]*v->n[VZ];
 }
 
-
-// Ok, this is another bottleneck of performance.
-
-
-#ifdef USE_ASSEMBLER
-
-// ecx:ebx is result in 64 bits format
-// edi points to matrix, esi points to input vector
-// since only 3 accesses are in output, this is a stack variable
-
-
-void MAT3evalW(LPWVEC3 r_, LPWMAT3 a_, LPWVEC3 v_)
-{
-
-       ASM {
-
-
-       mov    esi, dword ptr ss:v_
-       mov    edi, dword ptr ss:a_
-
-   //     r->n[VX] = FixedMul(a->v[0].n[0], v->n[0]) +
-
-       mov       eax,dword ptr [esi]
-       mov       edx,dword ptr [edi]
-       imul      edx
-       mov       ecx, eax
-       mov       ebx, edx
-
-   //          FixedMul(a->v[0].n[1], v->n[1]) +
-
-       mov       eax,dword ptr [esi+4]
-       mov       edx,dword ptr [edi+4]
-       imul      edx
-       add       ecx, eax
-       adc       ebx, edx
-
-   //         FixedMul(a->v[0].n[2], v->n[2]);
-
-       mov       eax,dword ptr [esi+8]
-       mov       edx,dword ptr [edi+8]
-       imul      edx
-       add       ecx, eax
-       adc       ebx, edx
-
-   //  Back to Fixed 15.16
-
-       add       ecx, 0x8000
-       adc       ebx, 0
-       shrd      ecx, ebx, 16
-
-       push      edi
-       mov       edi, dword ptr ss:r_
-       mov       dword ptr [edi], ecx      //  r -> n[VX]
-       pop       edi
-
-
-
-   //   2nd row ***************************
-
-   //        FixedMul(a->v[1].n[0], v->n[0])
-
-       mov       eax,dword ptr [esi]
-       mov       edx,dword ptr [edi+12]
-       imul      edx
-       mov       ecx, eax
-       mov       ebx, edx
-
-   //         FixedMul(a->v[1].n[1], v->n[1]) +
-
-       mov       eax,dword ptr [esi+4]
-       mov       edx,dword ptr [edi+16]
-       imul      edx
-       add       ecx, eax
-       adc       ebx, edx
-
-       //     FixedMul(a->v[1].n[2], v->n[2]);
-
-       mov       eax,dword ptr [esi+8]
-       mov       edx,dword ptr [edi+20]
-       imul      edx
-       add       ecx, eax
-       adc       ebx, edx
-
-       add       ecx, 0x8000
-       adc       ebx, 0
-       shrd      ecx, ebx, 16
-
-       push      edi
-       mov       edi, dword ptr ss:r_
-       mov       dword ptr [edi+4], ecx      // r -> n[VY]
-       pop       edi
-
-//     3d row **************************
-
-   //       r->n[VZ] = FixedMul(a->v[2].n[0], v->n[0]) +
-
-       mov       eax,dword ptr [esi]
-       mov       edx,dword ptr [edi+24]
-       imul      edx
-       mov       ecx, eax
-       mov       ebx, edx
-
-   //    FixedMul(a->v[2].n[1], v->n[1]) +
-
-       mov       eax,dword ptr [esi+4]
-       mov       edx,dword ptr [edi+28]
-       imul      edx
-       add       ecx, eax
-       adc       ebx, edx
-
-   //   FixedMul(a->v[2].n[2], v->n[2]);
-
-       mov       eax,dword ptr [esi+8]
-       mov       edx,dword ptr [edi+32]
-       imul      edx
-       add       ecx, eax
-       adc       ebx, edx
-
-       add       ecx, 0x8000
-       adc       ebx, 0
-       shrd      ecx, ebx, 16
-
-       mov       edi, dword ptr ss:r_
-       mov       dword ptr [edi+8], ecx      // r -> n[VZ]
-       }
-}
-
-
-#else
-
-
-#ifdef USE_FLOAT
-
-void MAT3evalW(LPWVEC3 r, LPWMAT3 a, LPWVEC3 v)
-{
-    r->n[VX] = DOUBLE_TO_FIXED(
-                 FIXED_TO_DOUBLE(a->v[0].n[0]) * FIXED_TO_DOUBLE(v->n[0]) +
-                 FIXED_TO_DOUBLE(a->v[0].n[1]) * FIXED_TO_DOUBLE(v->n[1]) +
-                 FIXED_TO_DOUBLE(a->v[0].n[2]) * FIXED_TO_DOUBLE(v->n[2])
-                );
-
-    r->n[VY] = DOUBLE_TO_FIXED(
-                 FIXED_TO_DOUBLE(a->v[1].n[0]) * FIXED_TO_DOUBLE(v->n[0]) +
-                 FIXED_TO_DOUBLE(a->v[1].n[1]) * FIXED_TO_DOUBLE(v->n[1]) +
-                 FIXED_TO_DOUBLE(a->v[1].n[2]) * FIXED_TO_DOUBLE(v->n[2])
-               );
-
-    r->n[VZ] = DOUBLE_TO_FIXED(
-                FIXED_TO_DOUBLE(a->v[2].n[0]) * FIXED_TO_DOUBLE(v->n[0]) +
-                FIXED_TO_DOUBLE(a->v[2].n[1]) * FIXED_TO_DOUBLE(v->n[1]) +
-                FIXED_TO_DOUBLE(a->v[2].n[2]) * FIXED_TO_DOUBLE(v->n[2])
-               );
-}
-
-
-#else
-
-void MAT3evalW(LPWVEC3 r, LPWMAT3 a, LPWVEC3 v)
-{
-
-#ifdef USE_INT64
-
-    LCMSULONGLONG l1 = (LCMSULONGLONG) (LCMSSLONGLONG) a->v[0].n[0] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[0] +
-                       (LCMSULONGLONG) (LCMSSLONGLONG) a->v[0].n[1] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[1] +
-                       (LCMSULONGLONG) (LCMSSLONGLONG) a->v[0].n[2] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[2] + (LCMSULONGLONG) 0x8000;
-
-    LCMSULONGLONG l2 = (LCMSULONGLONG) (LCMSSLONGLONG) a->v[1].n[0] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[0] +
-                       (LCMSULONGLONG) (LCMSSLONGLONG) a->v[1].n[1] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[1] +
-                       (LCMSULONGLONG) (LCMSSLONGLONG) a->v[1].n[2] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[2] + (LCMSULONGLONG) 0x8000;
-
-    LCMSULONGLONG l3 = (LCMSULONGLONG) (LCMSSLONGLONG) a->v[2].n[0] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[0] +
-                       (LCMSULONGLONG) (LCMSSLONGLONG) a->v[2].n[1] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[1] +
-                       (LCMSULONGLONG) (LCMSSLONGLONG) a->v[2].n[2] *
-                       (LCMSULONGLONG) (LCMSSLONGLONG) v->n[2] + (LCMSULONGLONG) 0x8000;
-    l1 >>= 16;
-    l2 >>= 16;
-    l3 >>= 16;
-
-    r->n[VX] = (Fixed32) l1;
-    r->n[VY] = (Fixed32) l2;
-    r->n[VZ] = (Fixed32) l3;
-
-#else
-
-    // FIXME: Rounding should be done at very last stage. There is 1-Contone rounding error!
-
-    r->n[VX] = FixedMul(a->v[0].n[0], v->n[0]) +
-               FixedMul(a->v[0].n[1], v->n[1]) +
-               FixedMul(a->v[0].n[2], v->n[2]);
-
-    r->n[VY] = FixedMul(a->v[1].n[0], v->n[0]) +
-               FixedMul(a->v[1].n[1], v->n[1]) +
-               FixedMul(a->v[1].n[2], v->n[2]);
-
-    r->n[VZ] = FixedMul(a->v[2].n[0], v->n[0]) +
-               FixedMul(a->v[2].n[1], v->n[1]) +
-               FixedMul(a->v[2].n[2], v->n[2]);
-#endif
-}
-
-#endif
-#endif
-
-
-void MAT3perK(LPMAT3 r, LPMAT3 v, double d)
-{
-       VEC3perK(&r -> v[0], &v -> v[0], d);
-       VEC3perK(&r -> v[1], &v -> v[1], d);
-       VEC3perK(&r -> v[2], &v -> v[2], d);
-}
-
-
-void MAT3toFix(LPWMAT3 r, LPMAT3 v)
-{
-       VEC3toFix(&r -> v[0], &v -> v[0]);
-       VEC3toFix(&r -> v[1], &v -> v[1]);
-       VEC3toFix(&r -> v[2], &v -> v[2]);
-}
-
-void MAT3fromFix(LPMAT3 r, LPWMAT3 v)
-{
-       VEC3fromFix(&r -> v[0], &v -> v[0]);
-       VEC3fromFix(&r -> v[1], &v -> v[1]);
-       VEC3fromFix(&r -> v[2], &v -> v[2]);
-}
-
-
-
-// Scale v by d and store it in r giving INTEGER
-
-void VEC3scaleAndCut(LPWVEC3 r, LPVEC3 v, double d)
-{
-        r -> n[VX] = (int) floor(v -> n[VX] * d + .5);
-        r -> n[VY] = (int) floor(v -> n[VY] * d + .5);
-        r -> n[VZ] = (int) floor(v -> n[VZ] * d + .5);
-}
-
-void MAT3scaleAndCut(LPWMAT3 r, LPMAT3 v, double d)
-{
-       VEC3scaleAndCut(&r -> v[0], &v -> v[0], d);
-       VEC3scaleAndCut(&r -> v[1], &v -> v[1], d);
-       VEC3scaleAndCut(&r -> v[2], &v -> v[2], d);
-}
-
-
-
-
--- a/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,153 +49,725 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
+
+// Multilocalized unicode objects. That is an attempt to encapsulate i18n.
+
+
+// Allocates an empty multi localizad unicode object
+cmsMLU* CMSEXPORT cmsMLUalloc(cmsContext ContextID, cmsUInt32Number nItems)
+{
+    cmsMLU* mlu;
+
+    // nItems should be positive if given
+    if (nItems <= 0) nItems = 2;
+
+    // Create the container
+    mlu = (cmsMLU*) _cmsMallocZero(ContextID, sizeof(cmsMLU));
+    if (mlu == NULL) return NULL;
+
+    mlu ->ContextID = ContextID;
+
+    // Create entry array
+    mlu ->Entries = (_cmsMLUentry*) _cmsCalloc(ContextID, nItems, sizeof(_cmsMLUentry));
+    if (mlu ->Entries == NULL) {
+        _cmsFree(ContextID, mlu);
+        return NULL;
+    }
+
+    // Ok, keep indexes up to date
+    mlu ->AllocatedEntries    = nItems;
+    mlu ->UsedEntries         = 0;
+
+    return mlu;
+}
 
 
-// Named color support
+// Grows a mempool table for a MLU. Each time this function is called, mempool size is multiplied times two.
+static
+cmsBool GrowMLUpool(cmsMLU* mlu)
+{
+    cmsUInt32Number size;
+    void *NewPtr;
+
+    // Sanity check
+    if (mlu == NULL) return FALSE;
+
+    if (mlu ->PoolSize == 0)
+        size = 256;
+    else
+        size = mlu ->PoolSize * 2;
+
+    // Check for overflow
+    if (size < mlu ->PoolSize) return FALSE;
+
+    // Reallocate the pool
+    NewPtr = _cmsRealloc(mlu ->ContextID, mlu ->MemPool, size);
+    if (NewPtr == NULL) return FALSE;
+
+
+    mlu ->MemPool  = NewPtr;
+    mlu ->PoolSize = size;
 
-#include "lcms.h"
+    return TRUE;
+}
+
+
+// Grows a ntry table for a MLU. Each time this function is called, table size is multiplied times two.
+static
+cmsBool GrowMLUtable(cmsMLU* mlu)
+{
+    int AllocatedEntries;
+    _cmsMLUentry *NewPtr;
+
+    // Sanity check
+    if (mlu == NULL) return FALSE;
 
+    AllocatedEntries = mlu ->AllocatedEntries * 2;
+
+    // Check for overflow
+    if (AllocatedEntries < mlu ->AllocatedEntries) return FALSE;
+
+    // Reallocate the memory
+    NewPtr = (_cmsMLUentry*)_cmsRealloc(mlu ->ContextID, mlu ->Entries, AllocatedEntries*sizeof(_cmsMLUentry));
+    if (NewPtr == NULL) return FALSE;
+
+    mlu ->Entries          = NewPtr;
+    mlu ->AllocatedEntries = AllocatedEntries;
+
+    return TRUE;
+}
 
 
+// Search for a specific entry in the structure. Language and Country are used.
 static
-LPcmsNAMEDCOLORLIST GrowNamedColorList(LPcmsNAMEDCOLORLIST v, int ByElements)
+int SearchMLUEntry(cmsMLU* mlu, cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode)
 {
-    if (ByElements > v ->Allocated) {
+    int i;
+
+    // Sanity check
+    if (mlu == NULL) return -1;
+
+    // Iterate whole table
+    for (i=0; i < mlu ->UsedEntries; i++) {
+
+        if (mlu ->Entries[i].Country  == CountryCode &&
+            mlu ->Entries[i].Language == LanguageCode) return i;
+    }
+
+    // Not found
+    return -1;
+}
 
-        LPcmsNAMEDCOLORLIST TheNewList;
-        int NewElements;
-        size_t size;
+// Add a block of characters to the intended MLU. Language and country are specified.
+// Only one entry for Language/country pair is allowed.
+static
+cmsBool AddMLUBlock(cmsMLU* mlu, cmsUInt32Number size, const wchar_t *Block,
+                     cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode)
+{
+    cmsUInt32Number Offset;
+    cmsUInt8Number* Ptr;
+
+    // Sanity check
+    if (mlu == NULL) return FALSE;
+
+    // Is there any room available?
+    if (mlu ->UsedEntries >= mlu ->AllocatedEntries) {
+        if (!GrowMLUtable(mlu)) return FALSE;
+    }
+
+    // Only one ASCII string
+    if (SearchMLUEntry(mlu, LanguageCode, CountryCode) >= 0) return FALSE;  // Only one  is allowed!
+
+    // Check for size
+    while ((mlu ->PoolSize - mlu ->PoolUsed) < size) {
+
+            if (!GrowMLUpool(mlu)) return FALSE;
+    }
+
+    Offset = mlu ->PoolUsed;
+
+    Ptr = (cmsUInt8Number*) mlu ->MemPool;
+    if (Ptr == NULL) return FALSE;
 
-        if (v ->Allocated == 0)
-            NewElements = 64;   // Initial guess
-        else
-            NewElements = v ->Allocated;
+    // Set the entry
+    memmove(Ptr + Offset, Block, size);
+    mlu ->PoolUsed += size;
+
+    mlu ->Entries[mlu ->UsedEntries].StrW     = Offset;
+    mlu ->Entries[mlu ->UsedEntries].Len      = size;
+    mlu ->Entries[mlu ->UsedEntries].Country  = CountryCode;
+    mlu ->Entries[mlu ->UsedEntries].Language = LanguageCode;
+    mlu ->UsedEntries++;
+
+    return TRUE;
+}
+
+
+// Add an ASCII entry.
+cmsBool CMSEXPORT cmsMLUsetASCII(cmsMLU* mlu, const char LanguageCode[3], const char CountryCode[3], const char* ASCIIString)
+{
+    cmsUInt32Number i, len = (cmsUInt32Number) strlen(ASCIIString)+1;
+    wchar_t* WStr;
+    cmsBool  rc;
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
+
+    if (mlu == NULL) return FALSE;
 
-        while (ByElements > NewElements)
-                NewElements *= 2;
+    WStr = (wchar_t*) _cmsCalloc(mlu ->ContextID, len,  sizeof(wchar_t));
+    if (WStr == NULL) return FALSE;
+
+    for (i=0; i < len; i++)
+        WStr[i] = (wchar_t) ASCIIString[i];
+
+    rc = AddMLUBlock(mlu, len  * sizeof(wchar_t), WStr, Lang, Cntry);
+
+    _cmsFree(mlu ->ContextID, WStr);
+    return rc;
+
+}
 
-        size = sizeof(cmsNAMEDCOLORLIST) + (sizeof(cmsNAMEDCOLOR) * NewElements);
-        TheNewList = (LPcmsNAMEDCOLORLIST) _cmsMalloc(size);
+// We don't need any wcs support library
+static
+cmsUInt32Number mywcslen(const wchar_t *s)
+{
+    const wchar_t *p;
+
+    p = s;
+    while (*p)
+        p++;
+
+    return (cmsUInt32Number)(p - s);
+}
 
 
-        if (TheNewList == NULL) {
-            cmsSignalError(LCMS_ERRC_ABORTED, "Out of memory reallocating named color list");
-            return NULL;
-        }
-        else {
-              ZeroMemory(TheNewList, size);
-              CopyMemory(TheNewList, v, sizeof(cmsNAMEDCOLORLIST) + (v ->nColors - 1) * sizeof(cmsNAMEDCOLOR));
-              TheNewList -> Allocated = NewElements;
+// Add a wide entry
+cmsBool  CMSEXPORT cmsMLUsetWide(cmsMLU* mlu, const char Language[3], const char Country[3], const wchar_t* WideString)
+{
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) Language);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) Country);
+    cmsUInt32Number len;
+
+    if (mlu == NULL) return FALSE;
+    if (WideString == NULL) return FALSE;
+
+    len = (cmsUInt32Number) (mywcslen(WideString) + 1) * sizeof(wchar_t);
+    return AddMLUBlock(mlu, len, WideString, Lang, Cntry);
+}
+
+// Duplicating a MLU is as easy as copying all members
+cmsMLU* CMSEXPORT cmsMLUdup(const cmsMLU* mlu)
+{
+    cmsMLU* NewMlu = NULL;
+
+    // Duplicating a NULL obtains a NULL
+    if (mlu == NULL) return NULL;
+
+    NewMlu = cmsMLUalloc(mlu ->ContextID, mlu ->UsedEntries);
+    if (NewMlu == NULL) return NULL;
+
+    // Should never happen
+    if (NewMlu ->AllocatedEntries < mlu ->UsedEntries)
+        goto Error;
+
+    // Sanitize...
+    if (NewMlu ->Entries == NULL || mlu ->Entries == NULL)  goto Error;
+
+    memmove(NewMlu ->Entries, mlu ->Entries, mlu ->UsedEntries * sizeof(_cmsMLUentry));
+    NewMlu ->UsedEntries = mlu ->UsedEntries;
+
+    // The MLU may be empty
+    if (mlu ->PoolUsed == 0) {
+        NewMlu ->MemPool = NULL;
+    }
+    else {
+        // It is not empty
+        NewMlu ->MemPool = _cmsMalloc(mlu ->ContextID, mlu ->PoolUsed);
+        if (NewMlu ->MemPool == NULL) goto Error;
+    }
+
+    NewMlu ->PoolSize = mlu ->PoolUsed;
+
+    if (NewMlu ->MemPool == NULL || mlu ->MemPool == NULL) goto Error;
+
+    memmove(NewMlu ->MemPool, mlu->MemPool, mlu ->PoolUsed);
+    NewMlu ->PoolUsed = mlu ->PoolUsed;
 
-              _cmsFree(v);
-              return TheNewList;
+    return NewMlu;
+
+Error:
+
+    if (NewMlu != NULL) cmsMLUfree(NewMlu);
+    return NULL;
+}
+
+// Free any used memory
+void CMSEXPORT cmsMLUfree(cmsMLU* mlu)
+{
+    if (mlu) {
+
+        if (mlu -> Entries) _cmsFree(mlu ->ContextID, mlu->Entries);
+        if (mlu -> MemPool) _cmsFree(mlu ->ContextID, mlu->MemPool);
+
+        _cmsFree(mlu ->ContextID, mlu);
+    }
+}
+
+
+// The algorithm first searches for an exact match of country and language, if not found it uses
+// the Language. If none is found, first entry is used instead.
+static
+const wchar_t* _cmsMLUgetWide(const cmsMLU* mlu,
+                              cmsUInt32Number *len,
+                              cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode,
+                              cmsUInt16Number* UsedLanguageCode, cmsUInt16Number* UsedCountryCode)
+{
+    int i;
+    int Best = -1;
+    _cmsMLUentry* v;
+
+    if (mlu == NULL) return NULL;
+
+    if (mlu -> AllocatedEntries <= 0) return NULL;
+
+    for (i=0; i < mlu ->UsedEntries; i++) {
+
+        v = mlu ->Entries + i;
+
+        if (v -> Language == LanguageCode) {
+
+            if (Best == -1) Best = i;
+
+            if (v -> Country == CountryCode) {
+
+                if (UsedLanguageCode != NULL) *UsedLanguageCode = v ->Language;
+                if (UsedCountryCode  != NULL) *UsedCountryCode = v ->Country;
+
+                if (len != NULL) *len = v ->Len;
+
+                return (wchar_t*) ((cmsUInt8Number*) mlu ->MemPool + v -> StrW);        // Found exact match
+            }
         }
     }
 
-    return v;
+    // No string found. Return First one
+    if (Best == -1)
+        Best = 0;
+
+    v = mlu ->Entries + Best;
+
+    if (UsedLanguageCode != NULL) *UsedLanguageCode = v ->Language;
+    if (UsedCountryCode  != NULL) *UsedCountryCode = v ->Country;
+
+    if (len != NULL) *len   = v ->Len;
+
+    return(wchar_t*) ((cmsUInt8Number*) mlu ->MemPool + v ->StrW);
 }
 
 
-LPcmsNAMEDCOLORLIST cmsAllocNamedColorList(int n)
+// Obtain an ASCII representation of the wide string. Setting buffer to NULL returns the len
+cmsUInt32Number CMSEXPORT cmsMLUgetASCII(const cmsMLU* mlu,
+                                         const char LanguageCode[3], const char CountryCode[3],
+                                         char* Buffer, cmsUInt32Number BufferSize)
 {
-    size_t size = sizeof(cmsNAMEDCOLORLIST) + (n - 1) * sizeof(cmsNAMEDCOLOR);
+    const wchar_t *Wide;
+    cmsUInt32Number  StrLen = 0;
+    cmsUInt32Number ASCIIlen, i;
+
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
+
+    // Sanitize
+    if (mlu == NULL) return 0;
+
+    // Get WideChar
+    Wide = _cmsMLUgetWide(mlu, &StrLen, Lang, Cntry, NULL, NULL);
+    if (Wide == NULL) return 0;
+
+    ASCIIlen = StrLen / sizeof(wchar_t);
+
+    // Maybe we want only to know the len?
+    if (Buffer == NULL) return ASCIIlen + 1; // Note the zero at the end
+
+    // No buffer size means no data
+    if (BufferSize <= 0) return 0;
+
+    // Some clipping may be required
+    if (BufferSize < ASCIIlen + 1)
+        ASCIIlen = BufferSize - 1;
+
+    // Precess each character
+    for (i=0; i < ASCIIlen; i++) {
+
+        if (Wide[i] == 0)
+            Buffer[i] = 0;
+        else
+            Buffer[i] = (char) Wide[i];
+    }
 
-    LPcmsNAMEDCOLORLIST v = (LPcmsNAMEDCOLORLIST) _cmsMalloc(size);
+    // We put a termination "\0"
+    Buffer[ASCIIlen] = 0;
+    return ASCIIlen + 1;
+}
+
+// Obtain a wide representation of the MLU, on depending on current locale settings
+cmsUInt32Number CMSEXPORT cmsMLUgetWide(const cmsMLU* mlu,
+                                        const char LanguageCode[3], const char CountryCode[3],
+                                        wchar_t* Buffer, cmsUInt32Number BufferSize)
+{
+    const wchar_t *Wide;
+    cmsUInt32Number  StrLen = 0;
+
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
+
+    // Sanitize
+    if (mlu == NULL) return 0;
+
+    Wide = _cmsMLUgetWide(mlu, &StrLen, Lang, Cntry, NULL, NULL);
+    if (Wide == NULL) return 0;
+
+    // Maybe we want only to know the len?
+    if (Buffer == NULL) return StrLen + sizeof(wchar_t);
+
+  // No buffer size means no data
+    if (BufferSize <= 0) return 0;
+
+    // Some clipping may be required
+    if (BufferSize < StrLen + sizeof(wchar_t))
+        StrLen = BufferSize - + sizeof(wchar_t);
+
+    memmove(Buffer, Wide, StrLen);
+    Buffer[StrLen / sizeof(wchar_t)] = 0;
+
+    return StrLen + sizeof(wchar_t);
+}
 
 
-    if (v == NULL) {
-        cmsSignalError(LCMS_ERRC_ABORTED, "Out of memory creating named color list");
-        return NULL;
-    }
+// Get also the language and country
+CMSAPI cmsBool CMSEXPORT cmsMLUgetTranslation(const cmsMLU* mlu,
+                                              const char LanguageCode[3], const char CountryCode[3],
+                                              char ObtainedLanguage[3], char ObtainedCountry[3])
+{
+    const wchar_t *Wide;
+
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
+    cmsUInt16Number ObtLang, ObtCode;
+
+    // Sanitize
+    if (mlu == NULL) return FALSE;
+
+    Wide = _cmsMLUgetWide(mlu, NULL, Lang, Cntry, &ObtLang, &ObtCode);
+    if (Wide == NULL) return FALSE;
+
+    // Get used language and code
+    *(cmsUInt16Number *)ObtainedLanguage = _cmsAdjustEndianess16(ObtLang);
+    *(cmsUInt16Number *)ObtainedCountry  = _cmsAdjustEndianess16(ObtCode);
+
+    ObtainedLanguage[2] = ObtainedCountry[2] = 0;
+    return TRUE;
+}
+
+
+// Named color lists --------------------------------------------------------------------------------------------
 
-    ZeroMemory(v, size);
+// Grow the list to keep at least NumElements
+static
+cmsBool  GrowNamedColorList(cmsNAMEDCOLORLIST* v)
+{
+    cmsUInt32Number size;
+    _cmsNAMEDCOLOR * NewPtr;
+
+    if (v == NULL) return FALSE;
+
+    if (v ->Allocated == 0)
+        size = 64;   // Initial guess
+    else
+        size = v ->Allocated * 2;
+
+    NewPtr = (_cmsNAMEDCOLOR*) _cmsRealloc(v ->ContextID, v ->List, size * sizeof(_cmsNAMEDCOLOR));
+    if (NewPtr == NULL)
+        return FALSE;
 
-    v ->nColors   = n;
-    v ->Allocated = n;
-    v ->Prefix[0] = 0;
-    v ->Suffix[0] = 0;
+    v ->List      = NewPtr;
+    v ->Allocated = size;
+    return TRUE;
+}
+
+// Allocate a list for n elements
+cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID, cmsUInt32Number n, cmsUInt32Number ColorantCount, const char* Prefix, const char* Suffix)
+{
+    cmsNAMEDCOLORLIST* v = (cmsNAMEDCOLORLIST*) _cmsMallocZero(ContextID, sizeof(cmsNAMEDCOLORLIST));
+
+    if (v == NULL) return NULL;
+
+    v ->List      = NULL;
+    v ->nColors   = 0;
+    v ->ContextID  = ContextID;
+
+    while (v -> Allocated < n)
+        GrowNamedColorList(v);
+
+    strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix));
+    strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix));
+    v -> ColorantCount = ColorantCount;
 
     return v;
 }
 
-void cmsFreeNamedColorList(LPcmsNAMEDCOLORLIST v)
+// Free a list
+void CMSEXPORT cmsFreeNamedColorList(cmsNAMEDCOLORLIST* v)
 {
-    if (v == NULL) {
-        cmsSignalError(LCMS_ERRC_RECOVERABLE, "Couldn't free a NULL named color list");
-        return;
-    }
-
-    _cmsFree(v);
+    if (v ->List) _cmsFree(v ->ContextID, v ->List);
+    if (v) _cmsFree(v ->ContextID, v);
 }
 
-LCMSBOOL cmsAppendNamedColor(cmsHTRANSFORM xform, const char* Name, WORD PCS[3], WORD Colorant[MAXCHANNELS])
+cmsNAMEDCOLORLIST* CMSEXPORT cmsDupNamedColorList(const cmsNAMEDCOLORLIST* v)
 {
-    _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
-    LPcmsNAMEDCOLORLIST List;
-    int i;
+    cmsNAMEDCOLORLIST* NewNC;
 
-    if (v ->NamedColorList == NULL) return FALSE;
+    if (v == NULL) return NULL;
 
-    v ->NamedColorList = GrowNamedColorList(v ->NamedColorList, v->NamedColorList ->nColors + 1);
-
-    List = v ->NamedColorList;
+    NewNC= cmsAllocNamedColorList(v ->ContextID, v -> nColors, v ->ColorantCount, v ->Prefix, v ->Suffix);
+    if (NewNC == NULL) return NULL;
 
-    for (i=0; i < MAXCHANNELS; i++)
-        List ->List[List ->nColors].DeviceColorant[i] = Colorant[i];
-
-    for (i=0; i < 3; i++)
-        List ->List[List ->nColors].PCS[i] = PCS[i];
+    // For really large tables we need this
+    while (NewNC ->Allocated < v ->Allocated)
+        GrowNamedColorList(NewNC);
 
-    strncpy(List ->List[List ->nColors].Name, Name, MAX_PATH-1);
-    List ->List[List ->nColors].Name[MAX_PATH-1] = 0;
-
-    List ->nColors++;
-    return TRUE;
+    memmove(NewNC ->Prefix, v ->Prefix, sizeof(v ->Prefix));
+    memmove(NewNC ->Suffix, v ->Suffix, sizeof(v ->Suffix));
+    NewNC ->ColorantCount = v ->ColorantCount;
+    memmove(NewNC->List, v ->List, v->nColors * sizeof(_cmsNAMEDCOLOR));
+    NewNC ->nColors = v ->nColors;
+    return NewNC;
 }
 
 
+// Append a color to a list. List pointer may change if reallocated
+cmsBool  CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* NamedColorList,
+                                       const char* Name,
+                                       cmsUInt16Number PCS[3], cmsUInt16Number Colorant[cmsMAXCHANNELS])
+{
+    cmsUInt32Number i;
 
-// Returns named color count
+    if (NamedColorList == NULL) return FALSE;
+
+    if (NamedColorList ->nColors + 1 > NamedColorList ->Allocated) {
+        if (!GrowNamedColorList(NamedColorList)) return FALSE;
+    }
+
+    for (i=0; i < NamedColorList ->ColorantCount; i++)
+        NamedColorList ->List[NamedColorList ->nColors].DeviceColorant[i] = Colorant == NULL? 0 : Colorant[i];
+
+    for (i=0; i < 3; i++)
+        NamedColorList ->List[NamedColorList ->nColors].PCS[i] = PCS == NULL ? 0 : PCS[i];
+
+    if (Name != NULL)
+        strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name,
+                    sizeof(NamedColorList ->List[NamedColorList ->nColors].Name));
+    else
+        NamedColorList ->List[NamedColorList ->nColors].Name[0] = 0;
+
 
-int LCMSEXPORT cmsNamedColorCount(cmsHTRANSFORM xform)
+    NamedColorList ->nColors++;
+    return TRUE;
+}
+
+// Returns number of elements
+cmsUInt32Number CMSEXPORT cmsNamedColorCount(const cmsNAMEDCOLORLIST* NamedColorList)
+{
+     if (NamedColorList == NULL) return 0;
+     return NamedColorList ->nColors;
+}
+
+// Info aboout a given color
+cmsBool  CMSEXPORT cmsNamedColorInfo(const cmsNAMEDCOLORLIST* NamedColorList, cmsUInt32Number nColor,
+                                     char* Name,
+                                     char* Prefix,
+                                     char* Suffix,
+                                     cmsUInt16Number* PCS,
+                                     cmsUInt16Number* Colorant)
 {
-     _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
+    if (NamedColorList == NULL) return FALSE;
+
+    if (nColor >= cmsNamedColorCount(NamedColorList)) return FALSE;
+
+    if (Name) strcpy(Name, NamedColorList->List[nColor].Name);
+    if (Prefix) strcpy(Prefix, NamedColorList->Prefix);
+    if (Suffix) strcpy(Suffix, NamedColorList->Suffix);
+    if (PCS)
+        memmove(PCS, NamedColorList ->List[nColor].PCS, 3*sizeof(cmsUInt16Number));
+
+    if (Colorant)
+        memmove(Colorant, NamedColorList ->List[nColor].DeviceColorant,
+                                sizeof(cmsUInt16Number) * NamedColorList ->ColorantCount);
+
+
+    return TRUE;
+}
+
+// Search for a given color name (no prefix or suffix)
+cmsInt32Number CMSEXPORT cmsNamedColorIndex(const cmsNAMEDCOLORLIST* NamedColorList, const char* Name)
+{
+    int i, n;
+
+    if (NamedColorList == NULL) return -1;
+    n = cmsNamedColorCount(NamedColorList);
+    for (i=0; i < n; i++) {
+        if (cmsstrcasecmp(Name,  NamedColorList->List[i].Name) == 0)
+            return i;
+    }
 
-     if (v ->NamedColorList == NULL) return 0;
-     return v ->NamedColorList ->nColors;
+    return -1;
+}
+
+// MPE support -----------------------------------------------------------------------------------------------------------------
+
+static
+void FreeNamedColorList(cmsStage* mpe)
+{
+    cmsNAMEDCOLORLIST* List = (cmsNAMEDCOLORLIST*) mpe ->Data;
+    cmsFreeNamedColorList(List);
+}
+
+static
+void* DupNamedColorList(cmsStage* mpe)
+{
+    cmsNAMEDCOLORLIST* List = (cmsNAMEDCOLORLIST*) mpe ->Data;
+    return cmsDupNamedColorList(List);
+}
+
+static
+void EvalNamedColor(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
+{
+    cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) mpe ->Data;
+    cmsUInt16Number index = (cmsUInt16Number) _cmsQuickSaturateWord(In[0] * 65535.0);
+    cmsUInt32Number j;
+
+    if (index >= NamedColorList-> nColors) {
+        cmsSignalError(NamedColorList ->ContextID, cmsERROR_RANGE, "Color %d out of range; ignored", index);
+    }
+    else {
+        for (j=0; j < NamedColorList ->ColorantCount; j++)
+            Out[j] = (cmsFloat32Number) (NamedColorList->List[index].DeviceColorant[j] / 65535.0);
+    }
 }
 
 
-LCMSBOOL LCMSEXPORT cmsNamedColorInfo(cmsHTRANSFORM xform, int nColor, char* Name, char* Prefix, char* Suffix)
+// Named color lookup element
+cmsStage* _cmsStageAllocNamedColor(cmsNAMEDCOLORLIST* NamedColorList)
 {
-    _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
-
-     if (v ->NamedColorList == NULL) return FALSE;
+    return _cmsStageAllocPlaceholder(NamedColorList ->ContextID,
+                                     cmsSigNamedColorElemType,
+                                     1, 3,
+                                     EvalNamedColor,
+                                     DupNamedColorList,
+                                     FreeNamedColorList,
+                                     cmsDupNamedColorList(NamedColorList));
 
-     if (nColor < 0 || nColor >= cmsNamedColorCount(xform)) return FALSE;
+}
+
 
-         if (Name)   { strncpy(Name, v ->NamedColorList->List[nColor].Name, 31); Name[31] = 0; }
-         if (Prefix) { strncpy(Prefix, v ->NamedColorList->Prefix, 31); Prefix[31] = 0; }
-         if (Suffix) { strncpy(Suffix, v ->NamedColorList->Suffix, 31); Suffix[31] = 0; }
+// Retrieve the named color list from a transform. Should be first element in the LUT
+cmsNAMEDCOLORLIST* CMSEXPORT cmsGetNamedColorList(cmsHTRANSFORM xform)
+{
+    _cmsTRANSFORM* v = (_cmsTRANSFORM*) xform;
+    cmsStage* mpe  = v ->Lut->Elements;
 
-     return TRUE;
+    if (mpe ->Type != cmsSigNamedColorElemType) return NULL;
+    return (cmsNAMEDCOLORLIST*) mpe ->Data;
 }
 
 
-int  LCMSEXPORT cmsNamedColorIndex(cmsHTRANSFORM xform, const char* Name)
+// Profile sequence description routines -------------------------------------------------------------------------------------
+
+cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n)
 {
-    _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
-    int i, n;
+    cmsSEQ* Seq;
+    cmsUInt32Number i;
 
-         if (v ->NamedColorList == NULL) return -1;
+    if (n == 0) return NULL;
+
+    // In a absolutely arbitrary way, I hereby decide to allow a maxim of 255 profiles linked
+    // in a devicelink. It makes not sense anyway and may be used for exploits, so let's close the door!
+    if (n > 255) return NULL;
 
-        n = cmsNamedColorCount(xform);
-        for (i=0; i < n; i++) {
-            if (stricmp(Name,  v ->NamedColorList->List[i].Name) == 0)
-                    return i;
-        }
+    Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ));
+    if (Seq == NULL) return NULL;
+
+    Seq -> ContextID = ContextID;
+    Seq -> seq      = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC));
+    Seq -> n        = n;
+
 
-        return -1;
+    for (i=0; i < n; i++) {
+        Seq -> seq[i].Manufacturer = NULL;
+        Seq -> seq[i].Model        = NULL;
+        Seq -> seq[i].Description  = NULL;
+    }
+
+    return Seq;
 }
 
+void CMSEXPORT cmsFreeProfileSequenceDescription(cmsSEQ* pseq)
+{
+    cmsUInt32Number i;
 
+    for (i=0; i < pseq ->n; i++) {
+        if (pseq ->seq[i].Manufacturer != NULL) cmsMLUfree(pseq ->seq[i].Manufacturer);
+        if (pseq ->seq[i].Model != NULL) cmsMLUfree(pseq ->seq[i].Model);
+        if (pseq ->seq[i].Description != NULL) cmsMLUfree(pseq ->seq[i].Description);
+    }
+
+    if (pseq ->seq != NULL) _cmsFree(pseq ->ContextID, pseq ->seq);
+    _cmsFree(pseq -> ContextID, pseq);
+}
+
+cmsSEQ* CMSEXPORT cmsDupProfileSequenceDescription(const cmsSEQ* pseq)
+{
+    cmsSEQ *NewSeq;
+    cmsUInt32Number i;
+
+    if (pseq == NULL)
+        return NULL;
+
+    NewSeq = (cmsSEQ*) _cmsMalloc(pseq -> ContextID, sizeof(cmsSEQ));
+    if (NewSeq == NULL) return NULL;
+
+
+    NewSeq -> seq      = (cmsPSEQDESC*) _cmsCalloc(pseq ->ContextID, pseq ->n, sizeof(cmsPSEQDESC));
+    if (NewSeq ->seq == NULL) goto Error;
+
+    NewSeq -> ContextID = pseq ->ContextID;
+    NewSeq -> n        = pseq ->n;
+
+    for (i=0; i < pseq->n; i++) {
+
+        memmove(&NewSeq ->seq[i].attributes, &pseq ->seq[i].attributes, sizeof(cmsUInt64Number));
+
+        NewSeq ->seq[i].deviceMfg   = pseq ->seq[i].deviceMfg;
+        NewSeq ->seq[i].deviceModel = pseq ->seq[i].deviceModel;
+        memmove(&NewSeq ->seq[i].ProfileID, &pseq ->seq[i].ProfileID, sizeof(cmsProfileID));
+        NewSeq ->seq[i].technology  = pseq ->seq[i].technology;
+
+        NewSeq ->seq[i].Manufacturer = cmsMLUdup(pseq ->seq[i].Manufacturer);
+        NewSeq ->seq[i].Model        = cmsMLUdup(pseq ->seq[i].Model);
+        NewSeq ->seq[i].Description  = cmsMLUdup(pseq ->seq[i].Description);
+
+    }
+
+    return NewSeq;
+
+Error:
+
+    cmsFreeProfileSequenceDescription(NewSeq);
+    return NULL;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsopt.c	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,1657 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
+
+
+//----------------------------------------------------------------------------------
+
+// Optimization for 8 bits, Shaper-CLUT (3 inputs only)
+typedef struct {
+
+    cmsContext ContextID;
+
+    const cmsInterpParams* p;   // Tetrahedrical interpolation parameters. This is a not-owned pointer.
+
+    cmsUInt16Number rx[256], ry[256], rz[256];
+    cmsUInt32Number X0[256], Y0[256], Z0[256];  // Precomputed nodes and offsets for 8-bit input data
+
+
+} Prelin8Data;
+
+
+// Generic optimization for 16 bits Shaper-CLUT-Shaper (any inputs)
+typedef struct {
+
+    cmsContext ContextID;
+
+    // Number of channels
+    int nInputs;
+    int nOutputs;
+
+    // Since there is no limitation of the output number of channels, this buffer holding the connexion CLUT-shaper
+    // has to be dynamically allocated. This is not the case of first step shaper-CLUT, which is limited to max inputs
+    cmsUInt16Number* StageDEF;
+
+    _cmsInterpFn16 EvalCurveIn16[MAX_INPUT_DIMENSIONS];       // The maximum number of input channels is known in advance
+    cmsInterpParams*  ParamsCurveIn16[MAX_INPUT_DIMENSIONS];
+
+    _cmsInterpFn16 EvalCLUT;            // The evaluator for 3D grid
+    const cmsInterpParams* CLUTparams;  // (not-owned pointer)
+
+
+    _cmsInterpFn16* EvalCurveOut16;       // Points to an array of curve evaluators in 16 bits (not-owned pointer)
+    cmsInterpParams**  ParamsCurveOut16;  // Points to an array of references to interpolation params (not-owned pointer)
+
+
+} Prelin16Data;
+
+
+// Optimization for matrix-shaper in 8 bits. Numbers are operated in n.14 signed, tables are stored in 1.14 fixed
+
+typedef cmsInt32Number cmsS1Fixed14Number;   // Note that this may hold more than 16 bits!
+
+#define DOUBLE_TO_1FIXED14(x) ((cmsS1Fixed14Number) floor((x) * 16384.0 + 0.5))
+
+typedef struct {
+
+    cmsContext ContextID;
+
+    cmsS1Fixed14Number Shaper1R[256];  // from 0..255 to 1.14  (0.0...1.0)
+    cmsS1Fixed14Number Shaper1G[256];
+    cmsS1Fixed14Number Shaper1B[256];
+
+    cmsS1Fixed14Number Mat[3][3];     // n.14 to n.14 (needs a saturation after that)
+    cmsS1Fixed14Number Off[3];
+
+    cmsUInt16Number Shaper2R[16385];    // 1.14 to 0..255
+    cmsUInt16Number Shaper2G[16385];
+    cmsUInt16Number Shaper2B[16385];
+
+} MatShaper8Data;
+
+// Curves, optimization is shared between 8 and 16 bits
+typedef struct {
+
+    cmsContext ContextID;
+
+    int nCurves;                  // Number of curves
+    int nElements;                // Elements in curves
+    cmsUInt16Number** Curves;     // Points to a dynamically  allocated array
+
+} Curves16Data;
+
+
+// Simple optimizations ----------------------------------------------------------------------------------------------------------
+
+
+// Remove an element in linked chain
+static
+void _RemoveElement(cmsStage** head)
+{
+    cmsStage* mpe = *head;
+    cmsStage* next = mpe ->Next;
+    *head = next;
+    cmsStageFree(mpe);
+}
+
+// Remove all identities in chain. Note that pt actually is a double pointer to the element that holds the pointer.
+static
+cmsBool _Remove1Op(cmsPipeline* Lut, cmsStageSignature UnaryOp)
+{
+    cmsStage** pt = &Lut ->Elements;
+    cmsBool AnyOpt = FALSE;
+
+    while (*pt != NULL) {
+
+        if ((*pt) ->Implements == UnaryOp) {
+            _RemoveElement(pt);
+            AnyOpt = TRUE;
+        }
+        else
+            pt = &((*pt) -> Next);
+    }
+
+    return AnyOpt;
+}
+
+// Same, but only if two adjacent elements are found
+static
+cmsBool _Remove2Op(cmsPipeline* Lut, cmsStageSignature Op1, cmsStageSignature Op2)
+{
+    cmsStage** pt1;
+    cmsStage** pt2;
+    cmsBool AnyOpt = FALSE;
+
+    pt1 = &Lut ->Elements;
+    if (*pt1 == NULL) return AnyOpt;
+
+    while (*pt1 != NULL) {
+
+        pt2 = &((*pt1) -> Next);
+        if (*pt2 == NULL) return AnyOpt;
+
+        if ((*pt1) ->Implements == Op1 && (*pt2) ->Implements == Op2) {
+            _RemoveElement(pt2);
+            _RemoveElement(pt1);
+            AnyOpt = TRUE;
+        }
+        else
+            pt1 = &((*pt1) -> Next);
+    }
+
+    return AnyOpt;
+}
+
+// Preoptimize just gets rif of no-ops coming paired. Conversion from v2 to v4 followed
+// by a v4 to v2 and vice-versa. The elements are then discarded.
+static
+cmsBool PreOptimize(cmsPipeline* Lut)
+{
+    cmsBool AnyOpt = FALSE, Opt;
+
+    AnyOpt = FALSE;
+
+    do {
+
+        Opt = FALSE;
+
+        // Remove all identities
+        Opt |= _Remove1Op(Lut, cmsSigIdentityElemType);
+
+        // Remove XYZ2Lab followed by Lab2XYZ
+        Opt |= _Remove2Op(Lut, cmsSigXYZ2LabElemType, cmsSigLab2XYZElemType);
+
+        // Remove Lab2XYZ followed by XYZ2Lab
+        Opt |= _Remove2Op(Lut, cmsSigLab2XYZElemType, cmsSigXYZ2LabElemType);
+
+        // Remove V4 to V2 followed by V2 to V4
+        Opt |= _Remove2Op(Lut, cmsSigLabV4toV2, cmsSigLabV2toV4);
+
+        // Remove V2 to V4 followed by V4 to V2
+        Opt |= _Remove2Op(Lut, cmsSigLabV2toV4, cmsSigLabV4toV2);
+
+        if (Opt) AnyOpt = TRUE;
+
+    } while (Opt);
+
+    return AnyOpt;
+}
+
+static
+void Eval16nop1D(register const cmsUInt16Number Input[],
+                 register cmsUInt16Number Output[],
+                 register const struct _cms_interp_struc* p)
+{
+    Output[0] = Input[0];
+
+    cmsUNUSED_PARAMETER(p);
+}
+
+static
+void PrelinEval16(register const cmsUInt16Number Input[],
+                  register cmsUInt16Number Output[],
+                  register const void* D)
+{
+    Prelin16Data* p16 = (Prelin16Data*) D;
+    cmsUInt16Number  StageABC[MAX_INPUT_DIMENSIONS];
+    int i;
+
+    for (i=0; i < p16 ->nInputs; i++) {
+
+        p16 ->EvalCurveIn16[i](&Input[i], &StageABC[i], p16 ->ParamsCurveIn16[i]);
+    }
+
+    p16 ->EvalCLUT(StageABC, p16 ->StageDEF, p16 ->CLUTparams);
+
+    for (i=0; i < p16 ->nOutputs; i++) {
+
+        p16 ->EvalCurveOut16[i](&p16->StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]);
+    }
+}
+
+
+static
+void PrelinOpt16free(cmsContext ContextID, void* ptr)
+{
+    Prelin16Data* p16 = (Prelin16Data*) ptr;
+
+    _cmsFree(ContextID, p16 ->StageDEF);
+    _cmsFree(ContextID, p16 ->EvalCurveOut16);
+    _cmsFree(ContextID, p16 ->ParamsCurveOut16);
+
+    _cmsFree(ContextID, p16);
+}
+
+static
+void* Prelin16dup(cmsContext ContextID, const void* ptr)
+{
+    Prelin16Data* p16 = (Prelin16Data*) ptr;
+    Prelin16Data* Duped = _cmsDupMem(ContextID, p16, sizeof(Prelin16Data));
+
+    if (Duped == NULL) return NULL;
+
+    Duped ->StageDEF         = _cmsCalloc(ContextID, p16 ->nOutputs, sizeof(cmsUInt16Number));
+    Duped ->EvalCurveOut16   = _cmsDupMem(ContextID, p16 ->EvalCurveOut16, p16 ->nOutputs * sizeof(_cmsInterpFn16));
+    Duped ->ParamsCurveOut16 = _cmsDupMem(ContextID, p16 ->ParamsCurveOut16, p16 ->nOutputs * sizeof(cmsInterpParams* ));
+
+    return Duped;
+}
+
+
+static
+Prelin16Data* PrelinOpt16alloc(cmsContext ContextID,
+                               const cmsInterpParams* ColorMap,
+                               int nInputs, cmsToneCurve** In,
+                               int nOutputs, cmsToneCurve** Out )
+{
+    int i;
+    Prelin16Data* p16 = (Prelin16Data*) _cmsMallocZero(ContextID, sizeof(Prelin16Data));
+    if (p16 == NULL) return NULL;
+
+    p16 ->nInputs = nInputs;
+    p16 -> nOutputs = nOutputs;
+
+
+    for (i=0; i < nInputs; i++) {
+
+        if (In == NULL) {
+            p16 -> ParamsCurveIn16[i] = NULL;
+            p16 -> EvalCurveIn16[i] = Eval16nop1D;
+
+        }
+        else {
+            p16 -> ParamsCurveIn16[i] = In[i] ->InterpParams;
+            p16 -> EvalCurveIn16[i] = p16 ->ParamsCurveIn16[i]->Interpolation.Lerp16;
+        }
+    }
+
+    p16 ->CLUTparams = ColorMap;
+    p16 ->EvalCLUT   = ColorMap ->Interpolation.Lerp16;
+
+
+    p16 -> StageDEF = _cmsCalloc(ContextID, p16 ->nOutputs, sizeof(cmsUInt16Number));
+    p16 -> EvalCurveOut16 = (_cmsInterpFn16*) _cmsCalloc(ContextID, nOutputs, sizeof(_cmsInterpFn16));
+    p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* ));
+
+    for (i=0; i < nOutputs; i++) {
+
+        if (Out == NULL) {
+            p16 ->ParamsCurveOut16[i] = NULL;
+            p16 -> EvalCurveOut16[i] = Eval16nop1D;
+        }
+        else {
+
+            p16 ->ParamsCurveOut16[i] = Out[i] ->InterpParams;
+            p16 -> EvalCurveOut16[i] = p16 ->ParamsCurveOut16[i]->Interpolation.Lerp16;
+        }
+    }
+
+    return p16;
+}
+
+
+
+// Resampling ---------------------------------------------------------------------------------
+
+#define PRELINEARIZATION_POINTS 4096
+
+// Sampler implemented by another LUT. This is a clean way to precalculate the devicelink 3D CLUT for
+// almost any transform. We use floating point precision and then convert from floating point to 16 bits.
+static
+int XFormSampler16(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
+{
+    cmsPipeline* Lut = (cmsPipeline*) Cargo;
+    cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
+    cmsUInt32Number i;
+
+    _cmsAssert(Lut -> InputChannels < cmsMAXCHANNELS);
+    _cmsAssert(Lut -> OutputChannels < cmsMAXCHANNELS);
+
+    // From 16 bit to floating point
+    for (i=0; i < Lut ->InputChannels; i++)
+        InFloat[i] = (cmsFloat32Number) (In[i] / 65535.0);
+
+    // Evaluate in floating point
+    cmsPipelineEvalFloat(InFloat, OutFloat, Lut);
+
+    // Back to 16 bits representation
+    for (i=0; i < Lut ->OutputChannels; i++)
+        Out[i] = _cmsQuickSaturateWord(OutFloat[i] * 65535.0);
+
+    // Always succeed
+    return TRUE;
+}
+
+// Try to see if the curves of a given MPE are linear
+static
+cmsBool AllCurvesAreLinear(cmsStage* mpe)
+{
+    cmsToneCurve** Curves;
+    cmsUInt32Number i, n;
+
+    Curves = _cmsStageGetPtrToCurveSet(mpe);
+    if (Curves == NULL) return FALSE;
+
+    n = cmsStageOutputChannels(mpe);
+
+    for (i=0; i < n; i++) {
+        if (!cmsIsToneCurveLinear(Curves[i])) return FALSE;
+    }
+
+    return TRUE;
+}
+
+// This function replaces a specific node placed in "At" by the "Value" numbers. Its purpose
+// is to fix scum dot on broken profiles/transforms. Works on 1, 3 and 4 channels
+static
+cmsBool  PatchLUT(cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[],
+                  int nChannelsOut, int nChannelsIn)
+{
+    _cmsStageCLutData* Grid = (_cmsStageCLutData*) CLUT ->Data;
+    cmsInterpParams* p16  = Grid ->Params;
+    cmsFloat64Number px, py, pz, pw;
+    int        x0, y0, z0, w0;
+    int        i, index;
+
+    if (CLUT -> Type != cmsSigCLutElemType) {
+        cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut MPE");
+        return FALSE;
+    }
+
+    px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
+    py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;
+    pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;
+    pw = ((cmsFloat64Number) At[3] * (p16->Domain[3])) / 65535.0;
+
+    x0 = (int) floor(px);
+    y0 = (int) floor(py);
+    z0 = (int) floor(pz);
+    w0 = (int) floor(pw);
+
+    if (nChannelsIn == 4) {
+
+        if (((px - x0) != 0) ||
+            ((py - y0) != 0) ||
+            ((pz - z0) != 0) ||
+            ((pw - w0) != 0)) return FALSE; // Not on exact node
+
+        index = p16 -> opta[3] * x0 +
+            p16 -> opta[2] * y0 +
+            p16 -> opta[1] * z0 +
+            p16 -> opta[0] * w0;
+    }
+    else
+        if (nChannelsIn == 3) {
+
+            if (((px - x0) != 0) ||
+                ((py - y0) != 0) ||
+                ((pz - z0) != 0)) return FALSE;  // Not on exact node
+
+            index = p16 -> opta[2] * x0 +
+                p16 -> opta[1] * y0 +
+                p16 -> opta[0] * z0;
+        }
+        else
+            if (nChannelsIn == 1) {
+
+                if (((px - x0) != 0)) return FALSE; // Not on exact node
+
+                index = p16 -> opta[0] * x0;
+            }
+            else {
+                cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);
+                return FALSE;
+            }
+
+            for (i=0; i < nChannelsOut; i++)
+                Grid -> Tab.T[index + i] = Value[i];
+
+            return TRUE;
+}
+
+// Auxiliar, to see if two values are equal.
+static
+cmsBool WhitesAreEqual(int n, cmsUInt16Number White1[], cmsUInt16Number White2[] )
+{
+    int i;
+
+    for (i=0; i < n; i++) {
+        if (White1[i] != White2[i]) return FALSE;
+    }
+    return TRUE;
+}
+
+
+// Locate the node for the white point and fix it to pure white in order to avoid scum dot.
+static
+cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColorSpace, cmsColorSpaceSignature ExitColorSpace)
+{
+    cmsUInt16Number *WhitePointIn, *WhitePointOut;
+    cmsUInt16Number  WhiteIn[cmsMAXCHANNELS], WhiteOut[cmsMAXCHANNELS], ObtainedOut[cmsMAXCHANNELS];
+    cmsUInt32Number i, nOuts, nIns;
+    cmsStage *PreLin = NULL, *CLUT = NULL, *PostLin = NULL;
+
+    if (!_cmsEndPointsBySpace(EntryColorSpace,
+        &WhitePointIn, NULL, &nIns)) return FALSE;
+
+    if (!_cmsEndPointsBySpace(ExitColorSpace,
+        &WhitePointOut, NULL, &nOuts)) return FALSE;
+
+    // It needs to be fixed?
+
+    cmsPipelineEval16(WhitePointIn, ObtainedOut, Lut);
+
+    if (WhitesAreEqual(nOuts, WhitePointOut, ObtainedOut)) return TRUE; // whites already match
+
+    // Check if the LUT comes as Prelin, CLUT or Postlin. We allow all combinations
+    if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &PreLin, &CLUT, &PostLin))
+        if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCurveSetElemType, cmsSigCLutElemType, &PreLin, &CLUT))
+            if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCLutElemType, cmsSigCurveSetElemType, &CLUT, &PostLin))
+                if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCLutElemType, &CLUT))
+                    return FALSE;
+
+    // We need to interpolate white points of both, pre and post curves
+    if (PreLin) {
+
+        cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PreLin);
+
+        for (i=0; i < nIns; i++) {
+            WhiteIn[i] = cmsEvalToneCurve16(Curves[i], WhitePointIn[i]);
+        }
+    }
+    else {
+        for (i=0; i < nIns; i++)
+            WhiteIn[i] = WhitePointIn[i];
+    }
+
+    // If any post-linearization, we need to find how is represented white before the curve, do
+    // a reverse interpolation in this case.
+    if (PostLin) {
+
+        cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PostLin);
+
+        for (i=0; i < nOuts; i++) {
+
+            cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);
+            WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);
+            cmsFreeToneCurve(InversePostLin);
+        }
+    }
+    else {
+        for (i=0; i < nOuts; i++)
+            WhiteOut[i] = WhitePointOut[i];
+    }
+
+    // Ok, proceed with patching. May fail and we don't care if it fails
+    PatchLUT(CLUT, WhiteIn, WhiteOut, nOuts, nIns);
+
+    return TRUE;
+}
+
+// -----------------------------------------------------------------------------------------------------------------------------------------------
+// This function creates simple LUT from complex ones. The generated LUT has an optional set of
+// prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables.
+// These curves have to exist in the original LUT in order to be used in the simplified output.
+// Caller may also use the flags to allow this feature.
+// LUTS with all curves will be simplified to a single curve. Parametric curves are lost.
+// This function should be used on 16-bits LUTS only, as floating point losses precision when simplified
+// -----------------------------------------------------------------------------------------------------------------------------------------------
+
+static
+cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
+{
+    cmsPipeline* Src;
+    cmsPipeline* Dest;
+    cmsStage* CLUT;
+    cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL;
+    int nGridPoints;
+    cmsColorSpaceSignature ColorSpace, OutputColorSpace;
+    cmsStage *NewPreLin = NULL;
+    cmsStage *NewPostLin = NULL;
+    _cmsStageCLutData* DataCLUT;
+    cmsToneCurve** DataSetIn;
+    cmsToneCurve** DataSetOut;
+    Prelin16Data* p16;
+
+
+    // This is a loosy optimization! does not apply in floating-point cases
+    if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
+
+    ColorSpace       = _cmsICCcolorSpace(T_COLORSPACE(*InputFormat));
+    OutputColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*OutputFormat));
+    nGridPoints      = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);
+
+    // For empty LUTs, 2 points are enough
+    if (cmsPipelineStageCount(*Lut) == 0)
+        nGridPoints = 2;
+
+    Src = *Lut;
+
+    // Allocate an empty LUT
+    Dest =  cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
+    if (!Dest) return FALSE;
+
+    // Prelinearization tables are kept unless indicated by flags
+    if (*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION) {
+
+        // Get a pointer to the prelinearization element
+        cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src);
+
+        // Check if suitable
+        if (PreLin ->Type == cmsSigCurveSetElemType) {
+
+            // Maybe this is a linear tram, so we can avoid the whole stuff
+            if (!AllCurvesAreLinear(PreLin)) {
+
+                // All seems ok, proceed.
+                NewPreLin = cmsStageDup(PreLin);
+                cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin);
+
+                // Remove prelinearization. Since we have duplicated the curve
+                // in destination LUT, the sampling shoud be applied after this stage.
+                cmsPipelineUnlinkStage(Src, cmsAT_BEGIN, &KeepPreLin);
+            }
+        }
+    }
+
+    // Allocate the CLUT
+    CLUT = cmsStageAllocCLut16bit(Src ->ContextID, nGridPoints, Src ->InputChannels, Src->OutputChannels, NULL);
+    if (CLUT == NULL) return FALSE;
+
+    // Add the CLUT to the destination LUT
+    cmsPipelineInsertStage(Dest, cmsAT_END, CLUT);
+
+    // Postlinearization tables are kept unless indicated by flags
+    if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) {
+
+        // Get a pointer to the postlinearization if present
+        cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src);
+
+        // Check if suitable
+        if (cmsStageType(PostLin) == cmsSigCurveSetElemType) {
+
+            // Maybe this is a linear tram, so we can avoid the whole stuff
+            if (!AllCurvesAreLinear(PostLin)) {
+
+                // All seems ok, proceed.
+                NewPostLin = cmsStageDup(PostLin);
+                cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin);
+
+                // In destination LUT, the sampling shoud be applied after this stage.
+                cmsPipelineUnlinkStage(Src, cmsAT_END, &KeepPostLin);
+            }
+        }
+    }
+
+    // Now its time to do the sampling. We have to ignore pre/post linearization
+    // The source LUT whithout pre/post curves is passed as parameter.
+    if (!cmsStageSampleCLut16bit(CLUT, XFormSampler16, (void*) Src, 0)) {
+
+        // Ops, something went wrong, Restore stages
+        if (KeepPreLin != NULL)  cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin);
+        if (KeepPostLin != NULL) cmsPipelineInsertStage(Src, cmsAT_END,   KeepPostLin);
+        cmsPipelineFree(Dest);
+        return FALSE;
+    }
+
+    // Done.
+
+    if (KeepPreLin != NULL) cmsStageFree(KeepPreLin);
+    if (KeepPostLin != NULL) cmsStageFree(KeepPostLin);
+    cmsPipelineFree(Src);
+
+    DataCLUT = (_cmsStageCLutData*) CLUT ->Data;
+
+    if (NewPreLin == NULL) DataSetIn = NULL;
+    else DataSetIn = ((_cmsStageToneCurvesData*) NewPreLin ->Data) ->TheCurves;
+
+    if (NewPostLin == NULL) DataSetOut = NULL;
+    else  DataSetOut = ((_cmsStageToneCurvesData*) NewPostLin ->Data) ->TheCurves;
+
+
+    if (DataSetIn == NULL && DataSetOut == NULL) {
+
+        _cmsPipelineSetOptimizationParameters(Dest, (_cmsOPTeval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL);
+    }
+    else {
+
+        p16 = PrelinOpt16alloc(Dest ->ContextID,
+                               DataCLUT ->Params,
+                               Dest ->InputChannels,
+                               DataSetIn,
+                               Dest ->OutputChannels,
+                               DataSetOut);
+
+
+        _cmsPipelineSetOptimizationParameters(Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
+    }
+
+
+    // Don't fix white on absolute colorimetric
+    if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
+        *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
+
+    if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
+
+        FixWhiteMisalignment(Dest, ColorSpace, OutputColorSpace);
+    }
+
+    *Lut = Dest;
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(Intent);
+}
+
+
+// -----------------------------------------------------------------------------------------------------------------------------------------------
+// Fixes the gamma balancing of transform. This is described in my paper "Prelinearization Stages on
+// Color-Management Application-Specific Integrated Circuits (ASICs)" presented at NIP24. It only works
+// for RGB transforms. See the paper for more details
+// -----------------------------------------------------------------------------------------------------------------------------------------------
+
+
+// Normalize endpoints by slope limiting max and min. This assures endpoints as well.
+// Descending curves are handled as well.
+static
+void SlopeLimiting(cmsToneCurve* g)
+{
+    int BeginVal, EndVal;
+    int AtBegin = (int) floor((cmsFloat64Number) g ->nEntries * 0.02 + 0.5);   // Cutoff at 2%
+    int AtEnd   = g ->nEntries - AtBegin - 1;                                  // And 98%
+    cmsFloat64Number Val, Slope, beta;
+    int i;
+
+    if (cmsIsToneCurveDescending(g)) {
+        BeginVal = 0xffff; EndVal = 0;
+    }
+    else {
+        BeginVal = 0; EndVal = 0xffff;
+    }
+
+    // Compute slope and offset for begin of curve
+    Val   = g ->Table16[AtBegin];
+    Slope = (Val - BeginVal) / AtBegin;
+    beta  = Val - Slope * AtBegin;
+
+    for (i=0; i < AtBegin; i++)
+        g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
+
+    // Compute slope and offset for the end
+    Val   = g ->Table16[AtEnd];
+    Slope = (EndVal - Val) / AtBegin;   // AtBegin holds the X interval, which is same in both cases
+    beta  = Val - Slope * AtEnd;
+
+    for (i = AtEnd; i < (int) g ->nEntries; i++)
+        g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
+}
+
+
+// Precomputes tables for 8-bit on input devicelink.
+static
+Prelin8Data* PrelinOpt8alloc(cmsContext ContextID, const cmsInterpParams* p, cmsToneCurve* G[3])
+{
+    int i;
+    cmsUInt16Number Input[3];
+    cmsS15Fixed16Number v1, v2, v3;
+    Prelin8Data* p8;
+
+    p8 = _cmsMallocZero(ContextID, sizeof(Prelin8Data));
+    if (p8 == NULL) return NULL;
+
+    // Since this only works for 8 bit input, values comes always as x * 257,
+    // we can safely take msb byte (x << 8 + x)
+
+    for (i=0; i < 256; i++) {
+
+        if (G != NULL) {
+
+            // Get 16-bit representation
+            Input[0] = cmsEvalToneCurve16(G[0], FROM_8_TO_16(i));
+            Input[1] = cmsEvalToneCurve16(G[1], FROM_8_TO_16(i));
+            Input[2] = cmsEvalToneCurve16(G[2], FROM_8_TO_16(i));
+        }
+        else {
+            Input[0] = FROM_8_TO_16(i);
+            Input[1] = FROM_8_TO_16(i);
+            Input[2] = FROM_8_TO_16(i);
+        }
+
+
+        // Move to 0..1.0 in fixed domain
+        v1 = _cmsToFixedDomain(Input[0] * p -> Domain[0]);
+        v2 = _cmsToFixedDomain(Input[1] * p -> Domain[1]);
+        v3 = _cmsToFixedDomain(Input[2] * p -> Domain[2]);
+
+        // Store the precalculated table of nodes
+        p8 ->X0[i] = (p->opta[2] * FIXED_TO_INT(v1));
+        p8 ->Y0[i] = (p->opta[1] * FIXED_TO_INT(v2));
+        p8 ->Z0[i] = (p->opta[0] * FIXED_TO_INT(v3));
+
+        // Store the precalculated table of offsets
+        p8 ->rx[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v1);
+        p8 ->ry[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v2);
+        p8 ->rz[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v3);
+    }
+
+    p8 ->ContextID = ContextID;
+    p8 ->p = p;
+
+    return p8;
+}
+
+static
+void Prelin8free(cmsContext ContextID, void* ptr)
+{
+    _cmsFree(ContextID, ptr);
+}
+
+static
+void* Prelin8dup(cmsContext ContextID, const void* ptr)
+{
+    return _cmsDupMem(ContextID, ptr, sizeof(Prelin8Data));
+}
+
+
+
+// A optimized interpolation for 8-bit input.
+#define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
+static
+void PrelinEval8(register const cmsUInt16Number Input[],
+                  register cmsUInt16Number Output[],
+                  register const void* D)
+{
+
+    cmsUInt8Number         r, g, b;
+    cmsS15Fixed16Number    rx, ry, rz;
+    cmsS15Fixed16Number    c0, c1, c2, c3, Rest;
+    int        OutChan;
+    register   cmsS15Fixed16Number    X0, X1, Y0, Y1, Z0, Z1;
+    Prelin8Data* p8 = (Prelin8Data*) D;
+    register const cmsInterpParams* p = p8 ->p;
+    int                    TotalOut = p -> nOutputs;
+    const cmsUInt16Number* LutTable = p -> Table;
+
+    r = Input[0] >> 8;
+    g = Input[1] >> 8;
+    b = Input[2] >> 8;
+
+    X0 = X1 = p8->X0[r];
+    Y0 = Y1 = p8->Y0[g];
+    Z0 = Z1 = p8->Z0[b];
+
+    rx = p8 ->rx[r];
+    ry = p8 ->ry[g];
+    rz = p8 ->rz[b];
+
+    X1 = X0 + ((rx == 0) ? 0 : p ->opta[2]);
+    Y1 = Y0 + ((ry == 0) ? 0 : p ->opta[1]);
+    Z1 = Z0 + ((rz == 0) ? 0 : p ->opta[0]);
+
+
+    // These are the 6 Tetrahedral
+    for (OutChan=0; OutChan < TotalOut; OutChan++) {
+
+        c0 = DENS(X0, Y0, Z0);
+
+        if (rx >= ry && ry >= rz)
+        {
+            c1 = DENS(X1, Y0, Z0) - c0;
+            c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
+            c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+        }
+        else
+            if (rx >= rz && rz >= ry)
+            {
+                c1 = DENS(X1, Y0, Z0) - c0;
+                c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
+            }
+            else
+                if (rz >= rx && rx >= ry)
+                {
+                    c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
+                    c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
+                    c3 = DENS(X0, Y0, Z1) - c0;
+                }
+                else
+                    if (ry >= rx && rx >= rz)
+                    {
+                        c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
+                        c2 = DENS(X0, Y1, Z0) - c0;
+                        c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
+                    }
+                    else
+                        if (ry >= rz && rz >= rx)
+                        {
+                            c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                            c2 = DENS(X0, Y1, Z0) - c0;
+                            c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
+                        }
+                        else
+                            if (rz >= ry && ry >= rx)
+                            {
+                                c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
+                                c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
+                                c3 = DENS(X0, Y0, Z1) - c0;
+                            }
+                            else  {
+                                c1 = c2 = c3 = 0;
+                            }
+
+
+                            Rest = c1 * rx + c2 * ry + c3 * rz;
+
+                            Output[OutChan] = (cmsUInt16Number)c0 + ROUND_FIXED_TO_INT(_cmsToFixedDomain(Rest));
+
+    }
+}
+
+#undef DENS
+
+// --------------------------------------------------------------------------------------------------------------
+// We need xput over here
+
+static
+cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
+{
+    cmsPipeline* OriginalLut;
+    int nGridPoints;
+    cmsToneCurve *Trans[cmsMAXCHANNELS], *TransReverse[cmsMAXCHANNELS];
+    cmsUInt32Number t, i;
+    cmsFloat32Number v, In[cmsMAXCHANNELS], Out[cmsMAXCHANNELS];
+    cmsBool lIsSuitable, lIsLinear;
+    cmsPipeline* OptimizedLUT = NULL, *LutPlusCurves = NULL;
+    cmsStage* OptimizedCLUTmpe;
+    cmsColorSpaceSignature ColorSpace, OutputColorSpace;
+    cmsStage* OptimizedPrelinMpe;
+    cmsToneCurve**   OptimizedPrelinCurves;
+    _cmsStageCLutData*     OptimizedPrelinCLUT;
+
+
+    // This is a loosy optimization! does not apply in floating-point cases
+    if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
+
+    // Only on RGB
+    if (T_COLORSPACE(*InputFormat)  != PT_RGB) return FALSE;
+    if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;
+
+
+    // On 16 bits, user has to specify the feature
+    if (!_cmsFormatterIs8bit(*InputFormat)) {
+        if (!(*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION)) return FALSE;
+    }
+
+    OriginalLut = *Lut;
+    ColorSpace       = _cmsICCcolorSpace(T_COLORSPACE(*InputFormat));
+    OutputColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*OutputFormat));
+    nGridPoints      = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);
+
+    // Empty gamma containers
+    memset(Trans, 0, sizeof(Trans));
+    memset(TransReverse, 0, sizeof(TransReverse));
+
+    for (t = 0; t < OriginalLut ->InputChannels; t++) {
+        Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL);
+        if (Trans[t] == NULL) goto Error;
+    }
+
+    // Populate the curves
+    for (i=0; i < PRELINEARIZATION_POINTS; i++) {
+
+        v = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
+
+        // Feed input with a gray ramp
+        for (t=0; t < OriginalLut ->InputChannels; t++)
+            In[t] = v;
+
+        // Evaluate the gray value
+        cmsPipelineEvalFloat(In, Out, OriginalLut);
+
+        // Store result in curve
+        for (t=0; t < OriginalLut ->InputChannels; t++)
+            Trans[t] ->Table16[i] = _cmsQuickSaturateWord(Out[t] * 65535.0);
+    }
+
+    // Slope-limit the obtained curves
+    for (t = 0; t < OriginalLut ->InputChannels; t++)
+        SlopeLimiting(Trans[t]);
+
+    // Check for validity
+    lIsSuitable = TRUE;
+    lIsLinear   = TRUE;
+    for (t=0; (lIsSuitable && (t < OriginalLut ->InputChannels)); t++) {
+
+        // Exclude if already linear
+        if (!cmsIsToneCurveLinear(Trans[t]))
+            lIsLinear = FALSE;
+
+        // Exclude if non-monotonic
+        if (!cmsIsToneCurveMonotonic(Trans[t]))
+            lIsSuitable = FALSE;
+    }
+
+    // If it is not suitable, just quit
+    if (!lIsSuitable) goto Error;
+
+    // Invert curves if possible
+    for (t = 0; t < OriginalLut ->InputChannels; t++) {
+        TransReverse[t] = cmsReverseToneCurveEx(PRELINEARIZATION_POINTS, Trans[t]);
+        if (TransReverse[t] == NULL) goto Error;
+    }
+
+    // Now inset the reversed curves at the begin of transform
+    LutPlusCurves = cmsPipelineDup(OriginalLut);
+    if (LutPlusCurves == NULL) goto Error;
+
+    cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse));
+
+    // Create the result LUT
+    OptimizedLUT = cmsPipelineAlloc(OriginalLut ->ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels);
+    if (OptimizedLUT == NULL) goto Error;
+
+    OptimizedPrelinMpe = cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, Trans);
+
+    // Create and insert the curves at the beginning
+    cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe);
+
+    // Allocate the CLUT for result
+    OptimizedCLUTmpe = cmsStageAllocCLut16bit(OriginalLut ->ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL);
+
+    // Add the CLUT to the destination LUT
+    cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe);
+
+    // Resample the LUT
+    if (!cmsStageSampleCLut16bit(OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error;
+
+    // Free resources
+    for (t = 0; t < OriginalLut ->InputChannels; t++) {
+
+        if (Trans[t]) cmsFreeToneCurve(Trans[t]);
+        if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);
+    }
+
+    cmsPipelineFree(LutPlusCurves);
+
+
+    OptimizedPrelinCurves = _cmsStageGetPtrToCurveSet(OptimizedPrelinMpe);
+    OptimizedPrelinCLUT   = (_cmsStageCLutData*) OptimizedCLUTmpe ->Data;
+
+    // Set the evaluator if 8-bit
+    if (_cmsFormatterIs8bit(*InputFormat)) {
+
+        Prelin8Data* p8 = PrelinOpt8alloc(OptimizedLUT ->ContextID,
+                                                OptimizedPrelinCLUT ->Params,
+                                                OptimizedPrelinCurves);
+        if (p8 == NULL) return FALSE;
+
+        _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval8, (void*) p8, Prelin8free, Prelin8dup);
+
+    }
+    else
+    {
+        Prelin16Data* p16 = PrelinOpt16alloc(OptimizedLUT ->ContextID,
+            OptimizedPrelinCLUT ->Params,
+            3, OptimizedPrelinCurves, 3, NULL);
+        if (p16 == NULL) return FALSE;
+
+        _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
+
+    }
+
+    // Don't fix white on absolute colorimetric
+    if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
+        *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
+
+    if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
+
+        if (!FixWhiteMisalignment(OptimizedLUT, ColorSpace, OutputColorSpace)) {
+
+            return FALSE;
+        }
+    }
+
+    // And return the obtained LUT
+
+    cmsPipelineFree(OriginalLut);
+    *Lut = OptimizedLUT;
+    return TRUE;
+
+Error:
+
+    for (t = 0; t < OriginalLut ->InputChannels; t++) {
+
+        if (Trans[t]) cmsFreeToneCurve(Trans[t]);
+        if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);
+    }
+
+    if (LutPlusCurves != NULL) cmsPipelineFree(LutPlusCurves);
+    if (OptimizedLUT != NULL) cmsPipelineFree(OptimizedLUT);
+
+    return FALSE;
+
+    cmsUNUSED_PARAMETER(Intent);
+}
+
+
+// Curves optimizer ------------------------------------------------------------------------------------------------------------------
+
+static
+void CurvesFree(cmsContext ContextID, void* ptr)
+{
+     Curves16Data* Data = (Curves16Data*) ptr;
+     int i;
+
+     for (i=0; i < Data -> nCurves; i++) {
+
+         _cmsFree(ContextID, Data ->Curves[i]);
+     }
+
+     _cmsFree(ContextID, Data ->Curves);
+     _cmsFree(ContextID, ptr);
+}
+
+static
+void* CurvesDup(cmsContext ContextID, const void* ptr)
+{
+    Curves16Data* Data = _cmsDupMem(ContextID, ptr, sizeof(Curves16Data));
+    int i;
+
+    if (Data == NULL) return NULL;
+
+    Data ->Curves = _cmsDupMem(ContextID, Data ->Curves, Data ->nCurves * sizeof(cmsUInt16Number*));
+
+    for (i=0; i < Data -> nCurves; i++) {
+        Data ->Curves[i] = _cmsDupMem(ContextID, Data ->Curves[i], Data -> nElements * sizeof(cmsUInt16Number));
+    }
+
+    return (void*) Data;
+}
+
+// Precomputes tables for 8-bit on input devicelink.
+static
+Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G)
+{
+    int i, j;
+    Curves16Data* c16;
+
+    c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data));
+    if (c16 == NULL) return NULL;
+
+    c16 ->nCurves = nCurves;
+    c16 ->nElements = nElements;
+
+    c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));
+    if (c16 ->Curves == NULL) return NULL;
+
+    for (i=0; i < nCurves; i++) {
+
+        c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
+
+        if (nElements == 256) {
+
+            for (j=0; j < nElements; j++) {
+
+                c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));
+            }
+        }
+        else {
+
+            for (j=0; j < nElements; j++) {
+                c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);
+            }
+        }
+    }
+
+    return c16;
+}
+
+static
+void FastEvaluateCurves8(register const cmsUInt16Number In[],
+                          register cmsUInt16Number Out[],
+                          register const void* D)
+{
+    Curves16Data* Data = (Curves16Data*) D;
+    cmsUInt8Number x;
+    int i;
+
+    for (i=0; i < Data ->nCurves; i++) {
+
+         x = (In[i] >> 8);
+         Out[i] = Data -> Curves[i][x];
+    }
+}
+
+
+static
+void FastEvaluateCurves16(register const cmsUInt16Number In[],
+                          register cmsUInt16Number Out[],
+                          register const void* D)
+{
+    Curves16Data* Data = (Curves16Data*) D;
+    int i;
+
+    for (i=0; i < Data ->nCurves; i++) {
+         Out[i] = Data -> Curves[i][In[i]];
+    }
+}
+
+
+static
+void FastIdentity16(register const cmsUInt16Number In[],
+                    register cmsUInt16Number Out[],
+                    register const void* D)
+{
+    cmsPipeline* Lut = (cmsPipeline*) D;
+    cmsUInt32Number i;
+
+    for (i=0; i < Lut ->InputChannels; i++) {
+         Out[i] = In[i];
+    }
+}
+
+
+// If the target LUT holds only curves, the optimization procedure is to join all those
+// curves together. That only works on curves and does not work on matrices.
+static
+cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
+{
+    cmsToneCurve** GammaTables = NULL;
+    cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
+    cmsUInt32Number i, j;
+    cmsPipeline* Src = *Lut;
+    cmsPipeline* Dest = NULL;
+    cmsStage* mpe;
+    cmsStage* ObtainedCurves = NULL;
+
+
+    // This is a loosy optimization! does not apply in floating-point cases
+    if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
+
+    //  Only curves in this LUT?
+    for (mpe = cmsPipelineGetPtrToFirstStage(Src);
+         mpe != NULL;
+         mpe = cmsStageNext(mpe)) {
+            if (cmsStageType(mpe) != cmsSigCurveSetElemType) return FALSE;
+    }
+
+    // Allocate an empty LUT
+    Dest =  cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
+    if (Dest == NULL) return FALSE;
+
+    // Create target curves
+    GammaTables = (cmsToneCurve**) _cmsCalloc(Src ->ContextID, Src ->InputChannels, sizeof(cmsToneCurve*));
+    if (GammaTables == NULL) goto Error;
+
+    for (i=0; i < Src ->InputChannels; i++) {
+        GammaTables[i] = cmsBuildTabulatedToneCurve16(Src ->ContextID, PRELINEARIZATION_POINTS, NULL);
+        if (GammaTables[i] == NULL) goto Error;
+    }
+
+    // Compute 16 bit result by using floating point
+    for (i=0; i < PRELINEARIZATION_POINTS; i++) {
+
+        for (j=0; j < Src ->InputChannels; j++)
+            InFloat[j] = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
+
+        cmsPipelineEvalFloat(InFloat, OutFloat, Src);
+
+        for (j=0; j < Src ->InputChannels; j++)
+            GammaTables[j] -> Table16[i] = _cmsQuickSaturateWord(OutFloat[j] * 65535.0);
+    }
+
+    ObtainedCurves = cmsStageAllocToneCurves(Src ->ContextID, Src ->InputChannels, GammaTables);
+    if (ObtainedCurves == NULL) goto Error;
+
+    for (i=0; i < Src ->InputChannels; i++) {
+        cmsFreeToneCurve(GammaTables[i]);
+        GammaTables[i] = NULL;
+    }
+
+    if (GammaTables != NULL) _cmsFree(Src ->ContextID, GammaTables);
+
+    // Maybe the curves are linear at the end
+    if (!AllCurvesAreLinear(ObtainedCurves)) {
+
+        cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves);
+
+        // If the curves are to be applied in 8 bits, we can save memory
+        if (_cmsFormatterIs8bit(*InputFormat)) {
+
+            _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) ObtainedCurves ->Data;
+             Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 256, Data ->TheCurves);
+
+             *dwFlags |= cmsFLAGS_NOCACHE;
+            _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup);
+
+        }
+        else {
+
+            _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) cmsStageData(ObtainedCurves);
+             Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 65536, Data ->TheCurves);
+
+             *dwFlags |= cmsFLAGS_NOCACHE;
+            _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup);
+        }
+    }
+    else {
+
+        // LUT optimizes to nothing. Set the identity LUT
+        cmsStageFree(ObtainedCurves);
+
+        cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels));
+
+        *dwFlags |= cmsFLAGS_NOCACHE;
+        _cmsPipelineSetOptimizationParameters(Dest, FastIdentity16, (void*) Dest, NULL, NULL);
+    }
+
+    // We are done.
+    cmsPipelineFree(Src);
+    *Lut = Dest;
+    return TRUE;
+
+Error:
+
+    if (ObtainedCurves != NULL) cmsStageFree(ObtainedCurves);
+    if (GammaTables != NULL) {
+        for (i=0; i < Src ->InputChannels; i++) {
+            if (GammaTables[i] != NULL) cmsFreeToneCurve(GammaTables[i]);
+        }
+
+        _cmsFree(Src ->ContextID, GammaTables);
+    }
+
+    if (Dest != NULL) cmsPipelineFree(Dest);
+    return FALSE;
+
+    cmsUNUSED_PARAMETER(Intent);
+    cmsUNUSED_PARAMETER(InputFormat);
+    cmsUNUSED_PARAMETER(OutputFormat);
+    cmsUNUSED_PARAMETER(dwFlags);
+}
+
+// -------------------------------------------------------------------------------------------------------------------------------------
+// LUT is Shaper - Matrix - Matrix - Shaper, which is very frequent when combining two matrix-shaper profiles
+
+
+static
+void  FreeMatShaper(cmsContext ContextID, void* Data)
+{
+    if (Data != NULL) _cmsFree(ContextID, Data);
+}
+
+static
+void* DupMatShaper(cmsContext ContextID, const void* Data)
+{
+    return _cmsDupMem(ContextID, Data, sizeof(MatShaper8Data));
+}
+
+
+// A fast matrix-shaper evaluator for 8 bits. This is a bit ticky since I'm using 1.14 signed fixed point
+// to accomplish some performance. Actually it takes 256x3 16 bits tables and 16385 x 3 tables of 8 bits,
+// in total about 50K, and the performance boost is huge!
+static
+void MatShaperEval16(register const cmsUInt16Number In[],
+                     register cmsUInt16Number Out[],
+                     register const void* D)
+{
+    MatShaper8Data* p = (MatShaper8Data*) D;
+    cmsS1Fixed14Number l1, l2, l3, r, g, b;
+    cmsUInt32Number ri, gi, bi;
+
+    // In this case (and only in this case!) we can use this simplification since
+    // In[] is assured to come from a 8 bit number. (a << 8 | a)
+    ri = In[0] & 0xFF;
+    gi = In[1] & 0xFF;
+    bi = In[2] & 0xFF;
+
+    // Across first shaper, which also converts to 1.14 fixed point
+    r = p->Shaper1R[ri];
+    g = p->Shaper1G[gi];
+    b = p->Shaper1B[bi];
+
+    // Evaluate the matrix in 1.14 fixed point
+    l1 =  (p->Mat[0][0] * r + p->Mat[0][1] * g + p->Mat[0][2] * b + p->Off[0] + 0x2000) >> 14;
+    l2 =  (p->Mat[1][0] * r + p->Mat[1][1] * g + p->Mat[1][2] * b + p->Off[1] + 0x2000) >> 14;
+    l3 =  (p->Mat[2][0] * r + p->Mat[2][1] * g + p->Mat[2][2] * b + p->Off[2] + 0x2000) >> 14;
+
+    // Now we have to clip to 0..1.0 range
+    ri = (l1 < 0) ? 0 : ((l1 > 16384) ? 16384 : l1);
+    gi = (l2 < 0) ? 0 : ((l2 > 16384) ? 16384 : l2);
+    bi = (l3 < 0) ? 0 : ((l3 > 16384) ? 16384 : l3);
+
+    // And across second shaper,
+    Out[0] = p->Shaper2R[ri];
+    Out[1] = p->Shaper2G[gi];
+    Out[2] = p->Shaper2B[bi];
+
+}
+
+// This table converts from 8 bits to 1.14 after applying the curve
+static
+void FillFirstShaper(cmsS1Fixed14Number* Table, cmsToneCurve* Curve)
+{
+    int i;
+    cmsFloat32Number R, y;
+
+    for (i=0; i < 256; i++) {
+
+        R   = (cmsFloat32Number) (i / 255.0);
+        y   = cmsEvalToneCurveFloat(Curve, R);
+
+        Table[i] = DOUBLE_TO_1FIXED14(y);
+    }
+}
+
+// This table converts form 1.14 (being 0x4000 the last entry) to 8 bits after applying the curve
+static
+void FillSecondShaper(cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8BitsOutput)
+{
+    int i;
+    cmsFloat32Number R, Val;
+
+    for (i=0; i < 16385; i++) {
+
+        R   = (cmsFloat32Number) (i / 16384.0);
+        Val = cmsEvalToneCurveFloat(Curve, R);    // Val comes 0..1.0
+
+        if (Is8BitsOutput) {
+
+            // If 8 bits output, we can optimize further by computing the / 257 part.
+            // first we compute the resulting byte and then we store the byte times
+            // 257. This quantization allows to round very quick by doing a >> 8, but
+            // since the low byte is always equal to msb, we can do a & 0xff and this works!
+            cmsUInt16Number w = _cmsQuickSaturateWord(Val * 65535.0 + 0.5);
+            cmsUInt8Number  b = FROM_16_TO_8(w);
+
+            Table[i] = FROM_8_TO_16(b);
+        }
+        else Table[i]  = _cmsQuickSaturateWord(Val * 65535.0 + 0.5);
+    }
+}
+
+// Compute the matrix-shaper structure
+static
+cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat)
+{
+    MatShaper8Data* p;
+    int i, j;
+    cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat);
+
+    // Allocate a big chuck of memory to store precomputed tables
+    p = (MatShaper8Data*) _cmsMalloc(Dest ->ContextID, sizeof(MatShaper8Data));
+    if (p == NULL) return FALSE;
+
+    p -> ContextID = Dest -> ContextID;
+
+    // Precompute tables
+    FillFirstShaper(p ->Shaper1R, Curve1[0]);
+    FillFirstShaper(p ->Shaper1G, Curve1[1]);
+    FillFirstShaper(p ->Shaper1B, Curve1[2]);
+
+    FillSecondShaper(p ->Shaper2R, Curve2[0], Is8Bits);
+    FillSecondShaper(p ->Shaper2G, Curve2[1], Is8Bits);
+    FillSecondShaper(p ->Shaper2B, Curve2[2], Is8Bits);
+
+    // Convert matrix to nFixed14. Note that those values may take more than 16 bits as
+    for (i=0; i < 3; i++) {
+        for (j=0; j < 3; j++) {
+            p ->Mat[i][j] = DOUBLE_TO_1FIXED14(Mat->v[i].n[j]);
+        }
+    }
+
+    for (i=0; i < 3; i++) {
+
+        if (Off == NULL) {
+            p ->Off[i] = 0;
+        }
+        else {
+            p ->Off[i] = DOUBLE_TO_1FIXED14(Off->n[i]);
+        }
+    }
+
+    // Mark as optimized for faster formatter
+    if (Is8Bits)
+        *OutputFormat |= OPTIMIZED_SH(1);
+
+    // Fill function pointers
+    _cmsPipelineSetOptimizationParameters(Dest, MatShaperEval16, (void*) p, FreeMatShaper, DupMatShaper);
+    return TRUE;
+}
+
+//  8 bits on input allows matrix-shaper boot up to 25 Mpixels per second on RGB. That's fast!
+// TODO: Allow a third matrix for abs. colorimetric
+static
+cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
+{
+    cmsStage* Curve1, *Curve2;
+    cmsStage* Matrix1, *Matrix2;
+    _cmsStageMatrixData* Data1;
+    _cmsStageMatrixData* Data2;
+    cmsMAT3 res;
+    cmsBool IdentityMat;
+    cmsPipeline* Dest, *Src;
+
+    // Only works on RGB to RGB
+    if (T_CHANNELS(*InputFormat) != 3 || T_CHANNELS(*OutputFormat) != 3) return FALSE;
+
+    // Only works on 8 bit input
+    if (!_cmsFormatterIs8bit(*InputFormat)) return FALSE;
+
+    // Seems suitable, proceed
+    Src = *Lut;
+
+    // Check for shaper-matrix-matrix-shaper structure, that is what this optimizer stands for
+    if (!cmsPipelineCheckAndRetreiveStages(Src, 4,
+        cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
+        &Curve1, &Matrix1, &Matrix2, &Curve2)) return FALSE;
+
+    // Get both matrices
+    Data1 = (_cmsStageMatrixData*) cmsStageData(Matrix1);
+    Data2 = (_cmsStageMatrixData*) cmsStageData(Matrix2);
+
+    // Input offset should be zero
+    if (Data1 ->Offset != NULL) return FALSE;
+
+    // Multiply both matrices to get the result
+    _cmsMAT3per(&res, (cmsMAT3*) Data2 ->Double, (cmsMAT3*) Data1 ->Double);
+
+    // Now the result is in res + Data2 -> Offset. Maybe is a plain identity?
+    IdentityMat = FALSE;
+    if (_cmsMAT3isIdentity(&res) && Data2 ->Offset == NULL) {
+
+        // We can get rid of full matrix
+        IdentityMat = TRUE;
+    }
+
+      // Allocate an empty LUT
+    Dest =  cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
+    if (!Dest) return FALSE;
+
+    // Assamble the new LUT
+    cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1));
+    if (!IdentityMat)
+        cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest ->ContextID, 3, 3, (const cmsFloat64Number*) &res, Data2 ->Offset));
+    cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2));
+
+    // If identity on matrix, we can further optimize the curves, so call the join curves routine
+    if (IdentityMat) {
+
+        OptimizeByJoiningCurves(&Dest, Intent, InputFormat, OutputFormat, dwFlags);
+    }
+    else {
+        _cmsStageToneCurvesData* mpeC1 = (_cmsStageToneCurvesData*) cmsStageData(Curve1);
+        _cmsStageToneCurvesData* mpeC2 = (_cmsStageToneCurvesData*) cmsStageData(Curve2);
+
+        // In this particular optimization, caché does not help as it takes more time to deal with
+        // the caché that with the pixel handling
+        *dwFlags |= cmsFLAGS_NOCACHE;
+
+        // Setup the optimizarion routines
+        SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Data2 ->Offset, mpeC2->TheCurves, OutputFormat);
+    }
+
+    cmsPipelineFree(Src);
+    *Lut = Dest;
+    return TRUE;
+}
+
+
+// -------------------------------------------------------------------------------------------------------------------------------------
+// Optimization plug-ins
+
+// List of optimizations
+typedef struct _cmsOptimizationCollection_st {
+
+    _cmsOPToptimizeFn  OptimizePtr;
+
+    struct _cmsOptimizationCollection_st *Next;
+
+} _cmsOptimizationCollection;
+
+
+// The built-in list. We currently implement 4 types of optimizations. Joining of curves, matrix-shaper, linearization and resampling
+static _cmsOptimizationCollection DefaultOptimization[] = {
+
+    { OptimizeByJoiningCurves,            &DefaultOptimization[1] },
+    { OptimizeMatrixShaper,               &DefaultOptimization[2] },
+    { OptimizeByComputingLinearization,   &DefaultOptimization[3] },
+    { OptimizeByResampling,               NULL }
+};
+
+// The linked list head
+static _cmsOptimizationCollection* OptimizationCollection = DefaultOptimization;
+
+// Register new ways to optimize
+cmsBool  _cmsRegisterOptimizationPlugin(cmsPluginBase* Data)
+{
+    cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;
+    _cmsOptimizationCollection* fl;
+
+    if (Data == NULL) {
+
+        OptimizationCollection = DefaultOptimization;
+        return TRUE;
+    }
+
+    // Optimizer callback is required
+    if (Plugin ->OptimizePtr == NULL) return FALSE;
+
+    fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(sizeof(_cmsOptimizationCollection));
+    if (fl == NULL) return FALSE;
+
+    // Copy the parameters
+    fl ->OptimizePtr = Plugin ->OptimizePtr;
+
+    // Keep linked list
+    fl ->Next = OptimizationCollection;
+    OptimizationCollection = fl;
+
+    // All is ok
+    return TRUE;
+}
+
+// The entry point for LUT optimization
+cmsBool _cmsOptimizePipeline(cmsPipeline**    PtrLut,
+                             int              Intent,
+                             cmsUInt32Number* InputFormat,
+                             cmsUInt32Number* OutputFormat,
+                             cmsUInt32Number* dwFlags)
+{
+    _cmsOptimizationCollection* Opts;
+    cmsBool AnySuccess = FALSE;
+
+    // A CLUT is being asked, so force this specific optimization
+    if (*dwFlags & cmsFLAGS_FORCE_CLUT) {
+
+        PreOptimize(*PtrLut);
+        return OptimizeByResampling(PtrLut, Intent, InputFormat, OutputFormat, dwFlags);
+    }
+
+    // Anything to optimize?
+    if ((*PtrLut) ->Elements == NULL) {
+        _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
+        return TRUE;
+    }
+
+    // Try to get rid of identities and trivial conversions.
+    AnySuccess = PreOptimize(*PtrLut);
+
+    // After removal do we end with an identity?
+    if ((*PtrLut) ->Elements == NULL) {
+        _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
+        return TRUE;
+    }
+
+    // Do not optimize, keep all precision
+    if (*dwFlags & cmsFLAGS_NOOPTIMIZE)
+        return FALSE;
+
+    // Try built-in optimizations and plug-in
+    for (Opts = OptimizationCollection;
+         Opts != NULL;
+         Opts = Opts ->Next) {
+
+            // If one schema succeeded, we are done
+            if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
+
+                return TRUE;    // Optimized!
+            }
+    }
+
+    // Only simple optimizations succeeded
+    return AnySuccess;
+}
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmspack.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmspack.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,8 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -47,2129 +49,2551 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-#include "lcms.h"
-
-// This module handles all formats supported by lcms
-
+//
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
+
+// This module handles all formats supported by lcms. There are two flavors, 16 bits and
+// floating point. Floating point is supported only in a subset, those formats holding
+// cmsFloat32Number (4 bytes per component) and double (marked as 0 bytes per component as special
+// case)
 
 // ---------------------------------------------------------------------------
 
 
 // This macro return words stored as big endian
-
-#define CHANGE_ENDIAN(w)    (WORD) ((WORD) ((w)<<8)|((w)>>8))
+#define CHANGE_ENDIAN(w)    (cmsUInt16Number) ((cmsUInt16Number) ((w)<<8)|((w)>>8))
 
 // These macros handles reversing (negative)
-
-#define REVERSE_FLAVOR_8(x)     ((BYTE) (0xff-(x)))
-#define REVERSE_FLAVOR_16(x)    ((WORD)(0xffff-(x)))
+#define REVERSE_FLAVOR_8(x)     ((cmsUInt8Number) (0xff-(x)))
+#define REVERSE_FLAVOR_16(x)    ((cmsUInt16Number)(0xffff-(x)))
+
+// * 0xffff / 0xff00 = (255 * 257) / (255 * 256) = 257 / 256
+cmsINLINE cmsUInt16Number FomLabV2ToLabV4(cmsUInt16Number x)
+{
+    int a;
+
+    a = (x << 8 | x) >> 8;  // * 257 / 256
+    if ( a > 0xffff) return 0xffff;
+    return (cmsUInt16Number) a;
+}
+
+// * 0xf00 / 0xffff = * 256 / 257
+cmsINLINE cmsUInt16Number FomLabV4ToLabV2(cmsUInt16Number x)
+{
+    return (cmsUInt16Number) (((x << 8) + 0x80) / 257);
+}
+
+
+typedef struct {
+    cmsUInt32Number Type;
+    cmsUInt32Number Mask;
+    cmsFormatter16 Frm;
+
+} cmsFormatters16;
+
+typedef struct {
+    cmsUInt32Number    Type;
+    cmsUInt32Number    Mask;
+    cmsFormatterFloat Frm;
+
+} cmsFormattersFloat;
+
+#define ANYSPACE        COLORSPACE_SH(31)
+#define ANYCHANNELS     CHANNELS_SH(15)
+#define ANYEXTRA        EXTRA_SH(7)
+#define ANYPLANAR       PLANAR_SH(1)
+#define ANYENDIAN       ENDIAN16_SH(1)
+#define ANYSWAP         DOSWAP_SH(1)
+#define ANYSWAPFIRST    SWAPFIRST_SH(1)
+#define ANYFLAVOR       FLAVOR_SH(1)
+
 
 // Supress waning about info never being used
 
-#ifdef __BORLANDC__
-#pragma warn -par
-#endif
-
 #ifdef _MSC_VER
 #pragma warning(disable : 4100)
 #endif
 
-// -------------------------------------------------------- Unpacking routines.
+// Unpacking routines (16 bits) ----------------------------------------------------------------------------------------
+
+// Does almost everything but is slow
+static
+cmsUInt8Number* UnrollChunkyBytes(register _cmsTRANSFORM* info,
+                                  register cmsUInt16Number wIn[],
+                                  register cmsUInt8Number* accum,
+                                  register cmsUInt32Number Stride)
+{
+    int nChan      = T_CHANNELS(info -> InputFormat);
+    int DoSwap     = T_DOSWAP(info ->InputFormat);
+    int Reverse    = T_FLAVOR(info ->InputFormat);
+    int SwapFirst  = T_SWAPFIRST(info -> InputFormat);
+    int Extra      = T_EXTRA(info -> InputFormat);
+    int ExtraFirst = DoSwap && !SwapFirst;
+    cmsUInt16Number v;
+    int i;
+
+    if (ExtraFirst) {
+        accum += Extra;
+    }
+
+    for (i=0; i < nChan; i++) {
+        int index = DoSwap ? (nChan - i - 1) : i;
+
+        v = FROM_8_TO_16(*accum);
+        v = Reverse ? REVERSE_FLAVOR_16(v) : v;
+        wIn[index] = v;
+        accum++;
+    }
+
+    if (!ExtraFirst) {
+        accum += Extra;
+    }
+
+    if (Extra == 0 && SwapFirst) {
+        cmsUInt16Number tmp = wIn[0];
+
+        memmove(&wIn[0], &wIn[1], (nChan-1) * sizeof(cmsUInt16Number));
+        wIn[nChan-1] = tmp;
+    }
+
+    return accum;
+}
+
+// Extra channels are just ignored because come in the next planes
+static
+cmsUInt8Number* UnrollPlanarBytes(register _cmsTRANSFORM* info,
+                                  register cmsUInt16Number wIn[],
+                                  register cmsUInt8Number* accum,
+                                  register cmsUInt32Number Stride)
+{
+    int nChan = T_CHANNELS(info -> InputFormat);
+    int DoSwap= T_DOSWAP(info ->InputFormat);
+    int Reverse= T_FLAVOR(info ->InputFormat);
+    int i;
+    cmsUInt8Number* Init = accum;
+
+    if (DoSwap) {
+        accum += T_EXTRA(info -> InputFormat) * Stride;
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+        cmsUInt16Number v = FROM_8_TO_16(*accum);
+
+        wIn[index] = Reverse ? REVERSE_FLAVOR_16(v) : v;
+        accum += Stride;
+    }
+
+    return (Init + 1);
+}
+
+// Special cases, provided for performance
+static
+cmsUInt8Number* Unroll4Bytes(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wIn[],
+                             register cmsUInt8Number* accum,
+                             register cmsUInt32Number Stride)
+{
+    wIn[0] = FROM_8_TO_16(*accum); accum++; // C
+    wIn[1] = FROM_8_TO_16(*accum); accum++; // M
+    wIn[2] = FROM_8_TO_16(*accum); accum++; // Y
+    wIn[3] = FROM_8_TO_16(*accum); accum++; // K
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll4BytesReverse(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wIn[],
+                                    register cmsUInt8Number* accum,
+                                    register cmsUInt32Number Stride)
+{
+    wIn[0] = FROM_8_TO_16(REVERSE_FLAVOR_8(*accum)); accum++; // C
+    wIn[1] = FROM_8_TO_16(REVERSE_FLAVOR_8(*accum)); accum++; // M
+    wIn[2] = FROM_8_TO_16(REVERSE_FLAVOR_8(*accum)); accum++; // Y
+    wIn[3] = FROM_8_TO_16(REVERSE_FLAVOR_8(*accum)); accum++; // K
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll4BytesSwapFirst(register _cmsTRANSFORM* info,
+                                      register cmsUInt16Number wIn[],
+                                      register cmsUInt8Number* accum,
+                                      register cmsUInt32Number Stride)
+{
+    wIn[3] = FROM_8_TO_16(*accum); accum++; // K
+    wIn[0] = FROM_8_TO_16(*accum); accum++; // C
+    wIn[1] = FROM_8_TO_16(*accum); accum++; // M
+    wIn[2] = FROM_8_TO_16(*accum); accum++; // Y
+
+    return accum;
+}
+
+// KYMC
+static
+cmsUInt8Number* Unroll4BytesSwap(register _cmsTRANSFORM* info,
+                                 register cmsUInt16Number wIn[],
+                                 register cmsUInt8Number* accum,
+                                 register cmsUInt32Number Stride)
+{
+    wIn[3] = FROM_8_TO_16(*accum); accum++;  // K
+    wIn[2] = FROM_8_TO_16(*accum); accum++;  // Y
+    wIn[1] = FROM_8_TO_16(*accum); accum++;  // M
+    wIn[0] = FROM_8_TO_16(*accum); accum++;  // C
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll4BytesSwapSwapFirst(register _cmsTRANSFORM* info,
+                                          register cmsUInt16Number wIn[],
+                                          register cmsUInt8Number* accum,
+                                          register cmsUInt32Number Stride)
+{
+    wIn[2] = FROM_8_TO_16(*accum); accum++;  // K
+    wIn[1] = FROM_8_TO_16(*accum); accum++;  // Y
+    wIn[0] = FROM_8_TO_16(*accum); accum++;  // M
+    wIn[3] = FROM_8_TO_16(*accum); accum++;  // C
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll3Bytes(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wIn[],
+                             register cmsUInt8Number* accum,
+                             register cmsUInt32Number Stride)
+{
+    wIn[0] = FROM_8_TO_16(*accum); accum++;     // R
+    wIn[1] = FROM_8_TO_16(*accum); accum++;     // G
+    wIn[2] = FROM_8_TO_16(*accum); accum++;     // B
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll3BytesSkip1Swap(register _cmsTRANSFORM* info,
+                                      register cmsUInt16Number wIn[],
+                                      register cmsUInt8Number* accum,
+                                      register cmsUInt32Number Stride)
+{
+    accum++; // A
+    wIn[2] = FROM_8_TO_16(*accum); accum++; // B
+    wIn[1] = FROM_8_TO_16(*accum); accum++; // G
+    wIn[0] = FROM_8_TO_16(*accum); accum++; // R
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll3BytesSkip1SwapFirst(register _cmsTRANSFORM* info,
+                                           register cmsUInt16Number wIn[],
+                                           register cmsUInt8Number* accum,
+                                           register cmsUInt32Number Stride)
+{
+    accum++; // A
+    wIn[0] = FROM_8_TO_16(*accum); accum++; // R
+    wIn[1] = FROM_8_TO_16(*accum); accum++; // G
+    wIn[2] = FROM_8_TO_16(*accum); accum++; // B
+
+    return accum;
+}
+
+
+// BRG
+static
+cmsUInt8Number* Unroll3BytesSwap(register _cmsTRANSFORM* info,
+                                 register cmsUInt16Number wIn[],
+                                 register cmsUInt8Number* accum,
+                                 register cmsUInt32Number Stride)
+{
+    wIn[2] = FROM_8_TO_16(*accum); accum++;     // B
+    wIn[1] = FROM_8_TO_16(*accum); accum++;     // G
+    wIn[0] = FROM_8_TO_16(*accum); accum++;     // R
+
+    return accum;
+}
+
+static
+cmsUInt8Number* UnrollLabV2_8(register _cmsTRANSFORM* info,
+                              register cmsUInt16Number wIn[],
+                              register cmsUInt8Number* accum,
+                              register cmsUInt32Number Stride)
+{
+    wIn[0] = FomLabV2ToLabV4(FROM_8_TO_16(*accum)); accum++;     // L
+    wIn[1] = FomLabV2ToLabV4(FROM_8_TO_16(*accum)); accum++;     // a
+    wIn[2] = FomLabV2ToLabV4(FROM_8_TO_16(*accum)); accum++;     // b
+
+    return accum;
+}
+
+static
+cmsUInt8Number* UnrollALabV2_8(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wIn[],
+                               register cmsUInt8Number* accum,
+                               register cmsUInt32Number Stride)
+{
+    accum++;  // A
+    wIn[0] = FomLabV2ToLabV4(FROM_8_TO_16(*accum)); accum++;     // L
+    wIn[1] = FomLabV2ToLabV4(FROM_8_TO_16(*accum)); accum++;     // a
+    wIn[2] = FomLabV2ToLabV4(FROM_8_TO_16(*accum)); accum++;     // b
+
+    return accum;
+}
+
+static
+cmsUInt8Number* UnrollLabV2_16(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wIn[],
+                               register cmsUInt8Number* accum,
+                               register cmsUInt32Number Stride)
+{
+    wIn[0] = FomLabV2ToLabV4(*(cmsUInt16Number*) accum); accum += 2;     // L
+    wIn[1] = FomLabV2ToLabV4(*(cmsUInt16Number*) accum); accum += 2;     // a
+    wIn[2] = FomLabV2ToLabV4(*(cmsUInt16Number*) accum); accum += 2;     // b
+
+    return accum;
+}
+
+
+
+// Monochrome + alpha. Alpha is lost
+static
+cmsUInt8Number* Unroll2Bytes(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wIn[],
+                             register cmsUInt8Number* accum,
+                             register cmsUInt32Number Stride)
+{
+    wIn[0] = wIn[1] = wIn[2] = FROM_8_TO_16(*accum); accum++;     // L
+    wIn[3] = FROM_8_TO_16(*accum); accum++;                       // alpha
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll2ByteSwapFirst(register _cmsTRANSFORM* info,
+                                     register cmsUInt16Number wIn[],
+                                     register cmsUInt8Number* accum,
+                                     register cmsUInt32Number Stride)
+{
+    wIn[3] = FROM_8_TO_16(*accum); accum++;                       // alpha
+    wIn[0] = wIn[1] = wIn[2] = FROM_8_TO_16(*accum); accum++;     // L
+    return accum;
+}
+
+
+// Monochrome duplicates L into RGB for null-transforms
+static
+cmsUInt8Number* Unroll1Byte(register _cmsTRANSFORM* info,
+                            register cmsUInt16Number wIn[],
+                            register cmsUInt8Number* accum,
+                            register cmsUInt32Number Stride)
+{
+    wIn[0] = wIn[1] = wIn[2] = FROM_8_TO_16(*accum); accum++;     // L
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll1ByteSkip2(register _cmsTRANSFORM* info,
+                                 register cmsUInt16Number wIn[],
+                                 register cmsUInt8Number* accum,
+                                 register cmsUInt32Number Stride)
+{
+    wIn[0] = wIn[1] = wIn[2] = FROM_8_TO_16(*accum); accum++;     // L
+    accum += 2;
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll1ByteReversed(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wIn[],
+                                    register cmsUInt8Number* accum,
+                                    register cmsUInt32Number Stride)
+{
+    wIn[0] = wIn[1] = wIn[2] = REVERSE_FLAVOR_16(FROM_8_TO_16(*accum)); accum++;     // L
+    return accum;
+}
+
+
+static
+cmsUInt8Number* UnrollAnyWords(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wIn[],
+                               register cmsUInt8Number* accum,
+                               register cmsUInt32Number Stride)
+{
+    int nChan       = T_CHANNELS(info -> InputFormat);
+    int SwapEndian  = T_ENDIAN16(info -> InputFormat);
+    int DoSwap      = T_DOSWAP(info ->InputFormat);
+    int Reverse     = T_FLAVOR(info ->InputFormat);
+    int SwapFirst   = T_SWAPFIRST(info -> InputFormat);
+    int Extra       = T_EXTRA(info -> InputFormat);
+    int ExtraFirst  = DoSwap && !SwapFirst;
+    int i;
+
+    if (ExtraFirst) {
+        accum += Extra * sizeof(cmsUInt16Number);
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+        cmsUInt16Number v = *(cmsUInt16Number*) accum;
+
+        if (SwapEndian)
+            v = CHANGE_ENDIAN(v);
+
+        wIn[index] = Reverse ? REVERSE_FLAVOR_16(v) : v;
+
+        accum += sizeof(cmsUInt16Number);
+    }
+
+    if (!ExtraFirst) {
+        accum += Extra * sizeof(cmsUInt16Number);
+    }
+
+    if (Extra == 0 && SwapFirst) {
+
+        cmsUInt16Number tmp = wIn[0];
+
+        memmove(&wIn[0], &wIn[1], (nChan-1) * sizeof(cmsUInt16Number));
+        wIn[nChan-1] = tmp;
+    }
+
+    return accum;
+}
+
+static
+cmsUInt8Number* UnrollPlanarWords(register _cmsTRANSFORM* info,
+                                  register cmsUInt16Number wIn[],
+                                  register cmsUInt8Number* accum,
+                                  register cmsUInt32Number Stride)
+{
+    int nChan = T_CHANNELS(info -> InputFormat);
+    int DoSwap= T_DOSWAP(info ->InputFormat);
+    int Reverse= T_FLAVOR(info ->InputFormat);
+    int SwapEndian = T_ENDIAN16(info -> InputFormat);
+    int i;
+    cmsUInt8Number* Init = accum;
+
+    if (DoSwap) {
+        accum += T_EXTRA(info -> InputFormat) * Stride * sizeof(cmsUInt16Number);
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+        cmsUInt16Number v = *(cmsUInt16Number*) accum;
+
+        if (SwapEndian)
+            v = CHANGE_ENDIAN(v);
+
+        wIn[index] = Reverse ? REVERSE_FLAVOR_16(v) : v;
+
+        accum +=  Stride * sizeof(cmsUInt16Number);
+    }
+
+    return (Init + sizeof(cmsUInt16Number));
+}
 
 
 static
-LPBYTE UnrollAnyBytes(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Unroll4Words(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wIn[],
+                             register cmsUInt8Number* accum,
+                             register cmsUInt32Number Stride)
+{
+    wIn[0] = *(cmsUInt16Number*) accum; accum+= 2; // C
+    wIn[1] = *(cmsUInt16Number*) accum; accum+= 2; // M
+    wIn[2] = *(cmsUInt16Number*) accum; accum+= 2; // Y
+    wIn[3] = *(cmsUInt16Number*) accum; accum+= 2; // K
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll4WordsReverse(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wIn[],
+                                    register cmsUInt8Number* accum,
+                                    register cmsUInt32Number Stride)
+{
+    wIn[0] = REVERSE_FLAVOR_16(*(cmsUInt16Number*) accum); accum+= 2; // C
+    wIn[1] = REVERSE_FLAVOR_16(*(cmsUInt16Number*) accum); accum+= 2; // M
+    wIn[2] = REVERSE_FLAVOR_16(*(cmsUInt16Number*) accum); accum+= 2; // Y
+    wIn[3] = REVERSE_FLAVOR_16(*(cmsUInt16Number*) accum); accum+= 2; // K
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll4WordsSwapFirst(register _cmsTRANSFORM* info,
+                                      register cmsUInt16Number wIn[],
+                                      register cmsUInt8Number* accum,
+                                      register cmsUInt32Number Stride)
+{
+    wIn[3] = *(cmsUInt16Number*) accum; accum+= 2; // K
+    wIn[0] = *(cmsUInt16Number*) accum; accum+= 2; // C
+    wIn[1] = *(cmsUInt16Number*) accum; accum+= 2; // M
+    wIn[2] = *(cmsUInt16Number*) accum; accum+= 2; // Y
+
+    return accum;
+}
+
+// KYMC
+static
+cmsUInt8Number* Unroll4WordsSwap(register _cmsTRANSFORM* info,
+                                 register cmsUInt16Number wIn[],
+                                 register cmsUInt8Number* accum,
+                                 register cmsUInt32Number Stride)
+{
+    wIn[3] = *(cmsUInt16Number*) accum; accum+= 2; // K
+    wIn[2] = *(cmsUInt16Number*) accum; accum+= 2; // Y
+    wIn[1] = *(cmsUInt16Number*) accum; accum+= 2; // M
+    wIn[0] = *(cmsUInt16Number*) accum; accum+= 2; // C
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll4WordsSwapSwapFirst(register _cmsTRANSFORM* info,
+                                          register cmsUInt16Number wIn[],
+                                          register cmsUInt8Number* accum,
+                                          register cmsUInt32Number Stride)
+{
+    wIn[2] = *(cmsUInt16Number*) accum; accum+= 2; // K
+    wIn[1] = *(cmsUInt16Number*) accum; accum+= 2; // Y
+    wIn[0] = *(cmsUInt16Number*) accum; accum+= 2; // M
+    wIn[3] = *(cmsUInt16Number*) accum; accum+= 2; // C
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll3Words(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wIn[],
+                             register cmsUInt8Number* accum,
+                             register cmsUInt32Number Stride)
+{
+    wIn[0] = *(cmsUInt16Number*) accum; accum+= 2;  // C R
+    wIn[1] = *(cmsUInt16Number*) accum; accum+= 2;  // M G
+    wIn[2] = *(cmsUInt16Number*) accum; accum+= 2;  // Y B
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll3WordsSwap(register _cmsTRANSFORM* info,
+                                 register cmsUInt16Number wIn[],
+                                 register cmsUInt8Number* accum,
+                                 register cmsUInt32Number Stride)
+{
+    wIn[2] = *(cmsUInt16Number*) accum; accum+= 2;  // C R
+    wIn[1] = *(cmsUInt16Number*) accum; accum+= 2;  // M G
+    wIn[0] = *(cmsUInt16Number*) accum; accum+= 2;  // Y B
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll3WordsSkip1Swap(register _cmsTRANSFORM* info,
+                                      register cmsUInt16Number wIn[],
+                                      register cmsUInt8Number* accum,
+                                      register cmsUInt32Number Stride)
+{
+    accum += 2; // A
+    wIn[2] = *(cmsUInt16Number*) accum; accum += 2; // R
+    wIn[1] = *(cmsUInt16Number*) accum; accum += 2; // G
+    wIn[0] = *(cmsUInt16Number*) accum; accum += 2; // B
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll3WordsSkip1SwapFirst(register _cmsTRANSFORM* info,
+                                           register cmsUInt16Number wIn[],
+                                           register cmsUInt8Number* accum,
+                                           register cmsUInt32Number Stride)
+{
+    accum += 2; // A
+    wIn[0] = *(cmsUInt16Number*) accum; accum += 2; // R
+    wIn[1] = *(cmsUInt16Number*) accum; accum += 2; // G
+    wIn[2] = *(cmsUInt16Number*) accum; accum += 2; // B
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll1Word(register _cmsTRANSFORM* info,
+                            register cmsUInt16Number wIn[],
+                            register cmsUInt8Number* accum,
+                            register cmsUInt32Number Stride)
+{
+    wIn[0] = wIn[1] = wIn[2] = *(cmsUInt16Number*) accum; accum+= 2;   // L
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll1WordReversed(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wIn[],
+                                    register cmsUInt8Number* accum,
+                                    register cmsUInt32Number Stride)
+{
+    wIn[0] = wIn[1] = wIn[2] = REVERSE_FLAVOR_16(*(cmsUInt16Number*) accum); accum+= 2;
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll1WordSkip3(register _cmsTRANSFORM* info,
+                                 register cmsUInt16Number wIn[],
+                                 register cmsUInt8Number* accum,
+                                 register cmsUInt32Number Stride)
+{
+    wIn[0] = wIn[1] = wIn[2] = *(cmsUInt16Number*) accum;
+
+    accum += 8;
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll2Words(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wIn[],
+                             register cmsUInt8Number* accum,
+                             register cmsUInt32Number Stride)
+{
+    wIn[0] = wIn[1] = wIn[2] = *(cmsUInt16Number*) accum; accum+= 2;   // L
+    wIn[3] = *(cmsUInt16Number*) accum; accum += 2;                    // alpha
+
+    return accum;
+}
+
+static
+cmsUInt8Number* Unroll2WordSwapFirst(register _cmsTRANSFORM* info,
+                                     register cmsUInt16Number wIn[],
+                                     register cmsUInt8Number* accum,
+                                     register cmsUInt32Number Stride)
+{
+    wIn[3] = *(cmsUInt16Number*) accum; accum += 2;                    // alpha
+    wIn[0] = wIn[1] = wIn[2] = *(cmsUInt16Number*) accum; accum+= 2;   // L
+
+    return accum;
+}
+
+// This is a conversion of Lab double to 16 bits
+static
+cmsUInt8Number* UnrollLabDoubleTo16(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wIn[],
+                                    register cmsUInt8Number* accum,
+                                    register cmsUInt32Number  Stride)
+{
+    if (T_PLANAR(info -> InputFormat)) {
+
+        cmsFloat64Number* Pt = (cmsFloat64Number*) accum;
+
+        cmsCIELab Lab;
+
+        Lab.L = Pt[0];
+        Lab.a = Pt[Stride];
+        Lab.b = Pt[Stride*2];
+
+        cmsFloat2LabEncoded(wIn, &Lab);
+        return accum + sizeof(cmsFloat64Number);
+    }
+    else {
+
+        cmsFloat2LabEncoded(wIn, (cmsCIELab*) accum);
+        accum += sizeof(cmsCIELab);
+        return accum;
+    }
+}
+
+// This is a conversion of XYZ double to 16 bits
+static
+cmsUInt8Number* UnrollXYZDoubleTo16(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wIn[],
+                                    register cmsUInt8Number* accum,
+                                    register cmsUInt32Number Stride)
+{
+    if (T_PLANAR(info -> InputFormat)) {
+
+        cmsFloat64Number* Pt = (cmsFloat64Number*) accum;
+        cmsCIEXYZ XYZ;
+
+        XYZ.X = Pt[0];
+        XYZ.Y = Pt[Stride];
+        XYZ.Z = Pt[Stride*2];
+        cmsFloat2XYZEncoded(wIn, &XYZ);
+
+        return accum + sizeof(cmsFloat64Number);
+
+    }
+
+    else {
+        cmsFloat2XYZEncoded(wIn, (cmsCIEXYZ*) accum);
+        accum += sizeof(cmsCIEXYZ);
+
+        return accum;
+    }
+}
+
+// Check if space is marked as ink
+cmsINLINE cmsBool IsInkSpace(cmsUInt32Number Type)
+{
+    switch (T_COLORSPACE(Type)) {
+
+     case PT_CMY:
+     case PT_CMYK:
+     case PT_MCH5:
+     case PT_MCH6:
+     case PT_MCH7:
+     case PT_MCH8:
+     case PT_MCH9:
+     case PT_MCH10:
+     case PT_MCH11:
+     case PT_MCH12:
+     case PT_MCH13:
+     case PT_MCH14:
+     case PT_MCH15: return TRUE;
+
+     default: return FALSE;
+    }
+}
+
+// Inks does come in percentage, remaining cases are between 0..1.0, again to 16 bits
+static
+cmsUInt8Number* UnrollDoubleTo16(register _cmsTRANSFORM* info,
+                                 register cmsUInt16Number wIn[],
+                                 register cmsUInt8Number* accum,
+                                 register cmsUInt32Number Stride)
 {
-       int nChan = T_CHANNELS(info -> InputFormat);
-       register int i;
-
-       for (i=0; i < nChan; i++) {
-
-              wIn[i] = RGB_8_TO_16(*accum); accum++;
-       }
-
-       return accum + T_EXTRA(info -> InputFormat);
+    cmsFloat64Number* Inks = (cmsFloat64Number*) accum;
+    int nChan  = T_CHANNELS(info -> InputFormat);
+    int Planar = T_PLANAR(info -> InputFormat);
+    int i;
+    cmsFloat64Number v;
+    cmsFloat64Number maximum = IsInkSpace(info ->InputFormat) ? 655.35 : 65535.0;
+
+    for (i=0; i < nChan; i++) {
+
+        if (Planar)
+
+            v = Inks[i * Stride];
+        else
+            v = Inks[i];
+
+        wIn[i] = _cmsQuickSaturateWord(v * maximum);
+    }
+
+    if (T_PLANAR(info -> InputFormat))
+        return accum + sizeof(cmsFloat64Number);
+    else
+        return accum + (nChan + T_EXTRA(info ->InputFormat)) * sizeof(cmsFloat64Number);
+}
+
+static
+cmsUInt8Number* UnrollFloatTo16(register _cmsTRANSFORM* info,
+                                register cmsUInt16Number wIn[],
+                                register cmsUInt8Number* accum,
+                                register cmsUInt32Number Stride)
+{
+    cmsFloat32Number* Inks = (cmsFloat32Number*) accum;
+    int nChan  = T_CHANNELS(info -> InputFormat);
+    int Planar = T_PLANAR(info -> InputFormat);
+    int i;
+    cmsFloat32Number v;
+    cmsFloat64Number maximum = IsInkSpace(info ->InputFormat) ? 655.35 : 65535.0;
+
+    for (i=0; i < nChan; i++) {
+
+        if (Planar)
+
+            v = Inks[i * Stride];
+        else
+            v = Inks[i];
+
+        wIn[i] = _cmsQuickSaturateWord(v * maximum);
+    }
+
+    if (T_PLANAR(info -> InputFormat))
+        return accum + sizeof(cmsFloat32Number);
+    else
+        return accum + (nChan + T_EXTRA(info ->InputFormat)) * sizeof(cmsFloat32Number);
+}
+
+
+// For 1 channel, we need to duplicate data (it comes in 0..1.0 range)
+static
+cmsUInt8Number* UnrollDouble1Chan(register _cmsTRANSFORM* info,
+                                  register cmsUInt16Number wIn[],
+                                  register cmsUInt8Number* accum,
+                                  register cmsUInt32Number Stride)
+{
+    cmsFloat64Number* Inks = (cmsFloat64Number*) accum;
+
+    wIn[0] = wIn[1] = wIn[2] = _cmsQuickSaturateWord(Inks[0] * 65535.0);
+
+    return accum + sizeof(cmsFloat64Number);
+}
+
+//-------------------------------------------------------------------------------------------------------------------
+
+// True cmsFloat32Number transformation.
+
+// For anything going from cmsFloat32Number
+static
+cmsUInt8Number* UnrollFloatsToFloat(_cmsTRANSFORM* info,
+                                    cmsFloat32Number wIn[],
+                                    cmsUInt8Number* accum,
+                                    cmsUInt32Number Stride)
+{
+    cmsFloat32Number* Inks = (cmsFloat32Number*) accum;
+    int nChan  = T_CHANNELS(info -> InputFormat);
+    int Planar = T_PLANAR(info -> InputFormat);
+    int i;
+    cmsFloat64Number maximum = IsInkSpace(info ->InputFormat) ? 100.0 : 1.0;
+
+
+    for (i=0; i <  nChan; i++) {
+
+        if (Planar)
+            wIn[i] = (cmsFloat32Number) (Inks[i * Stride] / maximum);
+        else
+            wIn[i] = (cmsFloat32Number) (Inks[i] / maximum);
+    }
+
+    if (T_PLANAR(info -> InputFormat))
+        return accum + sizeof(cmsFloat32Number);
+    else
+        return accum + (nChan + T_EXTRA(info ->InputFormat)) * sizeof(cmsFloat32Number);
+}
+
+// For anything going from double
+static
+cmsUInt8Number* UnrollDoublesToFloat(_cmsTRANSFORM* info,
+                                     cmsFloat32Number wIn[],
+                                     cmsUInt8Number* accum,
+                                     cmsUInt32Number Stride)
+{
+    cmsFloat64Number* Inks = (cmsFloat64Number*) accum;
+    int nChan  = T_CHANNELS(info -> InputFormat);
+    int Planar = T_PLANAR(info -> InputFormat);
+    int i;
+    cmsFloat64Number maximum = IsInkSpace(info ->InputFormat) ? 100.0 : 1.0;
+
+    for (i=0; i <  nChan; i++) {
+
+        if (Planar)
+            wIn[i] = (cmsFloat32Number) (Inks[i * Stride] / maximum);
+        else
+            wIn[i] = (cmsFloat32Number) (Inks[i] / maximum);
+    }
+
+    if (T_PLANAR(info -> InputFormat))
+        return accum + sizeof(cmsFloat64Number);
+    else
+        return accum + (nChan + T_EXTRA(info ->InputFormat)) * sizeof(cmsFloat64Number);
+}
+
+
+// From Lab double to cmsFloat32Number
+static
+cmsUInt8Number* UnrollLabDoubleToFloat(_cmsTRANSFORM* info,
+                                       cmsFloat32Number wIn[],
+                                       cmsUInt8Number* accum,
+                                       cmsUInt32Number Stride)
+{
+    cmsFloat64Number* Pt = (cmsFloat64Number*) accum;
+
+    if (T_PLANAR(info -> InputFormat)) {
+
+        wIn[0] = (cmsFloat32Number) (Pt[0] / 100.0);                            // from 0..100 to 0..1
+        wIn[1] = (cmsFloat32Number) ((Pt[Stride] + 128) / 255.0);    // form -128..+127 to 0..1
+        wIn[2] = (cmsFloat32Number) ((Pt[Stride*2] + 128) / 255.0);
+
+        return accum + sizeof(cmsFloat64Number);
+    }
+    else {
+
+        wIn[0] = (cmsFloat32Number) (Pt[0] / 100.0);             // from 0..100 to 0..1
+        wIn[1] = (cmsFloat32Number) ((Pt[1] + 128) / 255.0);    // form -128..+127 to 0..1
+        wIn[2] = (cmsFloat32Number) ((Pt[2] + 128) / 255.0);
+
+        accum += sizeof(cmsFloat64Number)*3;
+        return accum;
+    }
+}
+
+// From Lab double to cmsFloat32Number
+static
+cmsUInt8Number* UnrollLabFloatToFloat(_cmsTRANSFORM* info,
+                                      cmsFloat32Number wIn[],
+                                      cmsUInt8Number* accum,
+                                      cmsUInt32Number Stride)
+{
+    cmsFloat32Number* Pt = (cmsFloat32Number*) accum;
+
+    if (T_PLANAR(info -> InputFormat)) {
+
+        wIn[0] = (cmsFloat32Number) (Pt[0] / 100.0);                            // from 0..100 to 0..1
+        wIn[1] = (cmsFloat32Number) ((Pt[Stride] + 128) / 255.0);    // form -128..+127 to 0..1
+        wIn[2] = (cmsFloat32Number) ((Pt[Stride*2] + 128) / 255.0);
+
+        return accum + sizeof(cmsFloat32Number);
+    }
+    else {
+
+        wIn[0] = (cmsFloat32Number) (Pt[0] / 100.0);             // from 0..100 to 0..1
+        wIn[1] = (cmsFloat32Number) ((Pt[1] + 128) / 255.0);    // form -128..+127 to 0..1
+        wIn[2] = (cmsFloat32Number) ((Pt[2] + 128) / 255.0);
+
+        accum += sizeof(cmsFloat32Number)*3;
+        return accum;
+    }
+}
+
+
+// 1.15 fixed point, that means maximum value is MAX_ENCODEABLE_XYZ (0xFFFF)
+static
+cmsUInt8Number* UnrollXYZDoubleToFloat(_cmsTRANSFORM* info,
+                                       cmsFloat32Number wIn[],
+                                       cmsUInt8Number* accum,
+                                       cmsUInt32Number Stride)
+{
+    cmsFloat64Number* Pt = (cmsFloat64Number*) accum;
+
+    if (T_PLANAR(info -> InputFormat)) {
+
+        wIn[0] = (cmsFloat32Number) (Pt[0] / MAX_ENCODEABLE_XYZ);
+        wIn[1] = (cmsFloat32Number) (Pt[Stride] / MAX_ENCODEABLE_XYZ);
+        wIn[2] = (cmsFloat32Number) (Pt[Stride*2] / MAX_ENCODEABLE_XYZ);
+
+        return accum + sizeof(cmsFloat64Number);
+    }
+    else {
+
+        wIn[0] = (cmsFloat32Number) (Pt[0] / MAX_ENCODEABLE_XYZ);
+        wIn[1] = (cmsFloat32Number) (Pt[1] / MAX_ENCODEABLE_XYZ);
+        wIn[2] = (cmsFloat32Number) (Pt[2] / MAX_ENCODEABLE_XYZ);
+
+        accum += sizeof(cmsFloat64Number)*3;
+        return accum;
+    }
+}
+
+static
+cmsUInt8Number* UnrollXYZFloatToFloat(_cmsTRANSFORM* info,
+                                      cmsFloat32Number wIn[],
+                                      cmsUInt8Number* accum,
+                                      cmsUInt32Number Stride)
+{
+    cmsFloat32Number* Pt = (cmsFloat32Number*) accum;
+
+    if (T_PLANAR(info -> InputFormat)) {
+
+        wIn[0] = (cmsFloat32Number) (Pt[0] / MAX_ENCODEABLE_XYZ);
+        wIn[1] = (cmsFloat32Number) (Pt[Stride] / MAX_ENCODEABLE_XYZ);
+        wIn[2] = (cmsFloat32Number) (Pt[Stride*2] / MAX_ENCODEABLE_XYZ);
+
+        return accum + sizeof(cmsFloat32Number);
+    }
+    else {
+
+        wIn[0] = (cmsFloat32Number) (Pt[0] / MAX_ENCODEABLE_XYZ);
+        wIn[1] = (cmsFloat32Number) (Pt[1] / MAX_ENCODEABLE_XYZ);
+        wIn[2] = (cmsFloat32Number) (Pt[2] / MAX_ENCODEABLE_XYZ);
+
+        accum += sizeof(cmsFloat32Number)*3;
+        return accum;
+    }
+}
+
+// Packing routines -----------------------------------------------------------------------------------------------------------
+
+
+// Generic chunky for byte
+
+static
+cmsUInt8Number* PackAnyBytes(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wOut[],
+                             register cmsUInt8Number* output,
+                             register cmsUInt32Number Stride)
+{
+    int nChan      = T_CHANNELS(info -> OutputFormat);
+    int DoSwap     = T_DOSWAP(info ->OutputFormat);
+    int Reverse    = T_FLAVOR(info ->OutputFormat);
+    int Extra      = T_EXTRA(info -> OutputFormat);
+    int SwapFirst  = T_SWAPFIRST(info -> OutputFormat);
+    int ExtraFirst = DoSwap && !SwapFirst;
+    cmsUInt8Number* swap1;
+    cmsUInt8Number v = 0;
+    int i;
+
+    swap1 = output;
+
+    if (ExtraFirst) {
+        output += Extra;
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+
+        v = FROM_16_TO_8(wOut[index]);
+
+        if (Reverse)
+            v = REVERSE_FLAVOR_8(v);
+
+        *output++ = v;
+    }
+
+    if (!ExtraFirst) {
+        output += Extra;
+    }
+
+    if (Extra == 0 && SwapFirst) {
+
+        memmove(swap1 + 1, swap1, nChan-1);
+        *swap1 = v;
+    }
+
+
+    return output;
 }
 
 
 
 static
-LPBYTE Unroll4Bytes(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackAnyWords(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wOut[],
+                             register cmsUInt8Number* output,
+                             register cmsUInt32Number Stride)
 {
-       wIn[0] = RGB_8_TO_16(*accum); accum++; // C
-       wIn[1] = RGB_8_TO_16(*accum); accum++; // M
-       wIn[2] = RGB_8_TO_16(*accum); accum++; // Y
-       wIn[3] = RGB_8_TO_16(*accum); accum++; // K
-
-       return accum;
+    int nChan      = T_CHANNELS(info -> OutputFormat);
+    int SwapEndian = T_ENDIAN16(info -> InputFormat);
+    int DoSwap     = T_DOSWAP(info ->OutputFormat);
+    int Reverse    = T_FLAVOR(info ->OutputFormat);
+    int Extra      = T_EXTRA(info -> OutputFormat);
+    int SwapFirst  = T_SWAPFIRST(info -> OutputFormat);
+    int ExtraFirst = DoSwap && !SwapFirst;
+    cmsUInt16Number* swap1;
+    cmsUInt16Number v = 0;
+    int i;
+
+    swap1 = (cmsUInt16Number*) output;
+
+    if (ExtraFirst) {
+        output += Extra * sizeof(cmsUInt16Number);
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+
+        v = wOut[index];
+
+        if (SwapEndian)
+            v = CHANGE_ENDIAN(v);
+
+        if (Reverse)
+            v = REVERSE_FLAVOR_16(v);
+
+        *(cmsUInt16Number*) output = v;
+
+        output += sizeof(cmsUInt16Number);
+    }
+
+    if (!ExtraFirst) {
+        output += Extra * sizeof(cmsUInt16Number);
+    }
+
+    if (Extra == 0 && SwapFirst) {
+
+        memmove(swap1 + 1, swap1, (nChan-1)* sizeof(cmsUInt16Number));
+        *swap1 = v;
+    }
+
+
+    return output;
 }
 
+
 static
-LPBYTE Unroll4BytesReverse(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackPlanarBytes(register _cmsTRANSFORM* info,
+                                register cmsUInt16Number wOut[],
+                                register cmsUInt8Number* output,
+                                register cmsUInt32Number Stride)
 {
-       wIn[0] = RGB_8_TO_16(REVERSE_FLAVOR_8(*accum)); accum++; // C
-       wIn[1] = RGB_8_TO_16(REVERSE_FLAVOR_8(*accum)); accum++; // M
-       wIn[2] = RGB_8_TO_16(REVERSE_FLAVOR_8(*accum)); accum++; // Y
-       wIn[3] = RGB_8_TO_16(REVERSE_FLAVOR_8(*accum)); accum++; // K
-
-       return accum;
+    int nChan = T_CHANNELS(info -> OutputFormat);
+    int DoSwap = T_DOSWAP(info ->OutputFormat);
+    int Reverse= T_FLAVOR(info ->OutputFormat);
+    int i;
+    cmsUInt8Number* Init = output;
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+        cmsUInt8Number v = FROM_16_TO_8(wOut[index]);
+
+        *(cmsUInt8Number*)  output = (cmsUInt8Number) (Reverse ? REVERSE_FLAVOR_8(v) : v);
+        output += Stride;
+    }
+
+    return (Init + 1);
 }
 
 
 static
-LPBYTE Unroll4BytesSwapFirst(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackPlanarWords(register _cmsTRANSFORM* info,
+                                register cmsUInt16Number wOut[],
+                                register cmsUInt8Number* output,
+                                register cmsUInt32Number Stride)
 {
-
-       wIn[3] = RGB_8_TO_16(*accum); accum++; // K
-       wIn[0] = RGB_8_TO_16(*accum); accum++; // C
-       wIn[1] = RGB_8_TO_16(*accum); accum++; // M
-       wIn[2] = RGB_8_TO_16(*accum); accum++; // Y
-
-
-       return accum;
+    int nChan = T_CHANNELS(info -> OutputFormat);
+    int DoSwap = T_DOSWAP(info ->OutputFormat);
+    int Reverse= T_FLAVOR(info ->OutputFormat);
+    int SwapEndian = T_ENDIAN16(info -> OutputFormat);
+    int i;
+    cmsUInt8Number* Init = output;
+    cmsUInt16Number v;
+
+    if (DoSwap) {
+        output += T_EXTRA(info -> OutputFormat) * Stride * sizeof(cmsUInt16Number);
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+
+        v = wOut[index];
+
+        if (SwapEndian)
+            v = CHANGE_ENDIAN(v);
+
+        if (Reverse)
+            v =  REVERSE_FLAVOR_16(v);
+
+        *(cmsUInt16Number*) output = v;
+        output += (Stride * sizeof(cmsUInt16Number));
+    }
+
+    return (Init + sizeof(cmsUInt16Number));
+}
+
+// CMYKcm (unrolled for speed)
+
+static
+cmsUInt8Number* Pack6Bytes(register _cmsTRANSFORM* info,
+                           register cmsUInt16Number wOut[],
+                           register cmsUInt8Number* output,
+                           register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[0]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[2]);
+    *output++ = FROM_16_TO_8(wOut[3]);
+    *output++ = FROM_16_TO_8(wOut[4]);
+    *output++ = FROM_16_TO_8(wOut[5]);
+
+    return output;
 }
 
-
-
-// KYMC
+// KCMYcm
+
 static
-LPBYTE Unroll4BytesSwap(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack6BytesSwap(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wOut[],
+                               register cmsUInt8Number* output,
+                               register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[5]);
+    *output++ = FROM_16_TO_8(wOut[4]);
+    *output++ = FROM_16_TO_8(wOut[3]);
+    *output++ = FROM_16_TO_8(wOut[2]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[0]);
+
+    return output;
+}
+
+// CMYKcm
+static
+cmsUInt8Number* Pack6Words(register _cmsTRANSFORM* info,
+                           register cmsUInt16Number wOut[],
+                           register cmsUInt8Number* output,
+                           register cmsUInt32Number Stride)
 {
-       wIn[3] = RGB_8_TO_16(*accum); accum++;  // K
-       wIn[2] = RGB_8_TO_16(*accum); accum++;  // Y
-       wIn[1] = RGB_8_TO_16(*accum); accum++;  // M
-       wIn[0] = RGB_8_TO_16(*accum); accum++;  // C
-
-       return accum;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[3];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[4];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[5];
+    output+= 2;
+
+    return output;
+}
+
+// KCMYcm
+static
+cmsUInt8Number* Pack6WordsSwap(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wOut[],
+                               register cmsUInt8Number* output,
+                               register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = wOut[5];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[4];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[3];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+
+    return output;
 }
 
 
 static
-LPBYTE Unroll4BytesSwapSwapFirst(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack4Bytes(register _cmsTRANSFORM* info,
+                           register cmsUInt16Number wOut[],
+                           register cmsUInt8Number* output,
+                           register cmsUInt32Number Stride)
 {
-       wIn[2] = RGB_8_TO_16(*accum); accum++;  // K
-       wIn[1] = RGB_8_TO_16(*accum); accum++;  // Y
-       wIn[0] = RGB_8_TO_16(*accum); accum++;  // M
-       wIn[3] = RGB_8_TO_16(*accum); accum++;  // C
-
-       return accum;
+    *output++ = FROM_16_TO_8(wOut[0]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[2]);
+    *output++ = FROM_16_TO_8(wOut[3]);
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack4BytesReverse(register _cmsTRANSFORM* info,
+                                  register cmsUInt16Number wOut[],
+                                  register cmsUInt8Number* output,
+                                  register cmsUInt32Number Stride)
+{
+    *output++ = REVERSE_FLAVOR_8(FROM_16_TO_8(wOut[0]));
+    *output++ = REVERSE_FLAVOR_8(FROM_16_TO_8(wOut[1]));
+    *output++ = REVERSE_FLAVOR_8(FROM_16_TO_8(wOut[2]));
+    *output++ = REVERSE_FLAVOR_8(FROM_16_TO_8(wOut[3]));
+
+    return output;
 }
 
 
 static
-LPBYTE UnrollAnyWords(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack4BytesSwapFirst(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wOut[],
+                                    register cmsUInt8Number* output,
+                                    register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[3]);
+    *output++ = FROM_16_TO_8(wOut[0]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[2]);
+
+    return output;
+}
+
+// ABGR
+static
+cmsUInt8Number* Pack4BytesSwap(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wOut[],
+                               register cmsUInt8Number* output,
+                               register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[3]);
+    *output++ = FROM_16_TO_8(wOut[2]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[0]);
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack4BytesSwapSwapFirst(register _cmsTRANSFORM* info,
+                                        register cmsUInt16Number wOut[],
+                                        register cmsUInt8Number* output,
+                                        register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[2]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[0]);
+    *output++ = FROM_16_TO_8(wOut[3]);
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack4Words(register _cmsTRANSFORM* info,
+                           register cmsUInt16Number wOut[],
+                           register cmsUInt8Number* output,
+                           register cmsUInt32Number Stride)
 {
-     int nChan = T_CHANNELS(info -> InputFormat);
-     register int i;
-
-     for (i=0; i < nChan; i++) {
-
-              wIn[i] = *(LPWORD) accum; accum += 2;
-     }
-
-     return accum + T_EXTRA(info -> InputFormat) * sizeof(WORD);
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[3];
+    output+= 2;
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack4WordsReverse(register _cmsTRANSFORM* info,
+                                  register cmsUInt16Number wOut[],
+                                  register cmsUInt8Number* output,
+                                  register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = REVERSE_FLAVOR_16(wOut[0]);
+    output+= 2;
+    *(cmsUInt16Number*) output = REVERSE_FLAVOR_16(wOut[1]);
+    output+= 2;
+    *(cmsUInt16Number*) output = REVERSE_FLAVOR_16(wOut[2]);
+    output+= 2;
+    *(cmsUInt16Number*) output = REVERSE_FLAVOR_16(wOut[3]);
+    output+= 2;
+
+    return output;
+}
+
+// ABGR
+static
+cmsUInt8Number* Pack4WordsSwap(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wOut[],
+                               register cmsUInt8Number* output,
+                               register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = wOut[3];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+
+    return output;
+}
+
+// CMYK
+static
+cmsUInt8Number* Pack4WordsBigEndian(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wOut[],
+                                    register cmsUInt8Number* output,
+                                    register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = CHANGE_ENDIAN(wOut[0]);
+    output+= 2;
+    *(cmsUInt16Number*) output = CHANGE_ENDIAN(wOut[1]);
+    output+= 2;
+    *(cmsUInt16Number*) output = CHANGE_ENDIAN(wOut[2]);
+    output+= 2;
+    *(cmsUInt16Number*) output = CHANGE_ENDIAN(wOut[3]);
+    output+= 2;
+
+    return output;
 }
 
 
 static
-LPBYTE Unroll4Words(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackLabV2_8(register _cmsTRANSFORM* info,
+                            register cmsUInt16Number wOut[],
+                            register cmsUInt8Number* output,
+                            register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(FomLabV4ToLabV2(wOut[0]));
+    *output++ = FROM_16_TO_8(FomLabV4ToLabV2(wOut[1]));
+    *output++ = FROM_16_TO_8(FomLabV4ToLabV2(wOut[2]));
+
+    return output;
+}
+
+static
+cmsUInt8Number* PackALabV2_8(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wOut[],
+                             register cmsUInt8Number* output,
+                             register cmsUInt32Number Stride)
 {
-       wIn[0] = *(LPWORD) accum; accum+= 2; // C
-       wIn[1] = *(LPWORD) accum; accum+= 2; // M
-       wIn[2] = *(LPWORD) accum; accum+= 2; // Y
-       wIn[3] = *(LPWORD) accum; accum+= 2; // K
-
-       return accum;
+    output++;
+    *output++ = FROM_16_TO_8(FomLabV4ToLabV2(wOut[0]));
+    *output++ = FROM_16_TO_8(FomLabV4ToLabV2(wOut[1]));
+    *output++ = FROM_16_TO_8(FomLabV4ToLabV2(wOut[2]));
+
+    return output;
+}
+
+static
+cmsUInt8Number* PackLabV2_16(register _cmsTRANSFORM* info,
+                             register cmsUInt16Number wOut[],
+                             register cmsUInt8Number* output,
+                             register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = FomLabV4ToLabV2(wOut[0]);
+    output += 2;
+    *(cmsUInt16Number*) output = FomLabV4ToLabV2(wOut[1]);
+    output += 2;
+    *(cmsUInt16Number*) output = FomLabV4ToLabV2(wOut[2]);
+    output += 2;
+
+    return output;
 }
 
 static
-LPBYTE Unroll4WordsReverse(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3Bytes(register _cmsTRANSFORM* info,
+                           register cmsUInt16Number wOut[],
+                           register cmsUInt8Number* output,
+                           register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[0]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[2]);
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3BytesOptimized(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wOut[],
+                                    register cmsUInt8Number* output,
+                                    register cmsUInt32Number Stride)
 {
-       wIn[0] = REVERSE_FLAVOR_16(*(LPWORD) accum); accum+= 2; // C
-       wIn[1] = REVERSE_FLAVOR_16(*(LPWORD) accum); accum+= 2; // M
-       wIn[2] = REVERSE_FLAVOR_16(*(LPWORD) accum); accum+= 2; // Y
-       wIn[3] = REVERSE_FLAVOR_16(*(LPWORD) accum); accum+= 2; // K
-
-       return accum;
+    *output++ = (wOut[0] & 0xFF);
+    *output++ = (wOut[1] & 0xFF);
+    *output++ = (wOut[2] & 0xFF);
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3BytesSwap(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wOut[],
+                               register cmsUInt8Number* output,
+                               register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[2]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[0]);
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3BytesSwapOptimized(register _cmsTRANSFORM* info,
+                                        register cmsUInt16Number wOut[],
+                                        register cmsUInt8Number* output,
+                                        register cmsUInt32Number Stride)
+{
+    *output++ = (wOut[2] & 0xFF);
+    *output++ = (wOut[1] & 0xFF);
+    *output++ = (wOut[0] & 0xFF);
+
+    return output;
 }
 
 
 static
-LPBYTE Unroll4WordsSwapFirst(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3Words(register _cmsTRANSFORM* info,
+                           register cmsUInt16Number wOut[],
+                           register cmsUInt8Number* output,
+                           register cmsUInt32Number Stride)
 {
-       wIn[3] = *(LPWORD) accum; accum+= 2; // K
-       wIn[0] = *(LPWORD) accum; accum+= 2; // C
-       wIn[1] = *(LPWORD) accum; accum+= 2; // M
-       wIn[2] = *(LPWORD) accum; accum+= 2; // Y
-
-       return accum;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+
+    return output;
 }
 
-
-// KYMC
 static
-LPBYTE Unroll4WordsSwap(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3WordsSwap(register _cmsTRANSFORM* info,
+                               register cmsUInt16Number wOut[],
+                               register cmsUInt8Number* output,
+                               register cmsUInt32Number Stride)
 {
-       wIn[3] = *(LPWORD) accum; accum+= 2; // K
-       wIn[2] = *(LPWORD) accum; accum+= 2; // Y
-       wIn[1] = *(LPWORD) accum; accum+= 2; // M
-       wIn[0] = *(LPWORD) accum; accum+= 2; // C
-
-       return accum;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+
+    return output;
 }
 
 static
-LPBYTE Unroll4WordsSwapSwapFirst(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3WordsBigEndian(register _cmsTRANSFORM* info,
+                                    register cmsUInt16Number wOut[],
+                                    register cmsUInt8Number* output,
+                                    register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = CHANGE_ENDIAN(wOut[0]);
+    output+= 2;
+    *(cmsUInt16Number*) output = CHANGE_ENDIAN(wOut[1]);
+    output+= 2;
+    *(cmsUInt16Number*) output = CHANGE_ENDIAN(wOut[2]);
+    output+= 2;
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3BytesAndSkip1(register _cmsTRANSFORM* Info,
+                                   register cmsUInt16Number wOut[],
+                                   register cmsUInt8Number* output,
+                                   register cmsUInt32Number Stride)
 {
-       wIn[2] = *(LPWORD) accum; accum+= 2; // K
-       wIn[1] = *(LPWORD) accum; accum+= 2; // Y
-       wIn[0] = *(LPWORD) accum; accum+= 2; // M
-       wIn[3] = *(LPWORD) accum; accum+= 2; // C
-
-       return accum;
+    *output++ = FROM_16_TO_8(wOut[0]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[2]);
+    output++;
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3BytesAndSkip1Optimized(register _cmsTRANSFORM* Info,
+                                            register cmsUInt16Number wOut[],
+                                            register cmsUInt8Number* output,
+                                            register cmsUInt32Number Stride)
+{
+    *output++ = (wOut[0] & 0xFF);
+    *output++ = (wOut[1] & 0xFF);
+    *output++ = (wOut[2] & 0xFF);
+    output++;
+
+    return output;
 }
 
 
 static
-LPBYTE Unroll4WordsBigEndian(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       wIn[0] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2; //C
-       wIn[1] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2; //M
-       wIn[2] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2; //Y
-       wIn[3] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2; //K
-
-       return accum;
-}
-
-static
-LPBYTE Unroll4WordsBigEndianReverse(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3BytesAndSkip1SwapFirst(register _cmsTRANSFORM* Info,
+                                            register cmsUInt16Number wOut[],
+                                            register cmsUInt8Number* output,
+                                            register cmsUInt32Number Stride)
 {
-       wIn[0] = REVERSE_FLAVOR_16(CHANGE_ENDIAN(*(LPWORD) accum)); accum+= 2; //C
-       wIn[1] = REVERSE_FLAVOR_16(CHANGE_ENDIAN(*(LPWORD) accum)); accum+= 2; //M
-       wIn[2] = REVERSE_FLAVOR_16(CHANGE_ENDIAN(*(LPWORD) accum)); accum+= 2; //Y
-       wIn[3] = REVERSE_FLAVOR_16(CHANGE_ENDIAN(*(LPWORD) accum)); accum+= 2; //K
-
-       return accum;
-}
-
-
-// KYMC
-static
-LPBYTE Unroll4WordsSwapBigEndian(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       wIn[3] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2; //K
-       wIn[2] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2; //Y
-       wIn[1] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2; //M
-       wIn[0] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2; //C
-
-       return accum;
+    output++;
+    *output++ = FROM_16_TO_8(wOut[0]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[2]);
+
+    return output;
 }
 
 static
-LPBYTE Unroll3Bytes(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-
-       wIn[0] = RGB_8_TO_16(*accum); accum++;     // R
-       wIn[1] = RGB_8_TO_16(*accum); accum++;     // G
-       wIn[2] = RGB_8_TO_16(*accum); accum++;     // B
-
-       return accum;
-}
-
-
-// Lab8 encoding using v2 PCS
-
-static
-LPBYTE Unroll3BytesLab(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3BytesAndSkip1SwapFirstOptimized(register _cmsTRANSFORM* Info,
+                                                     register cmsUInt16Number wOut[],
+                                                     register cmsUInt8Number* output,
+                                                     register cmsUInt32Number Stride)
 {
-
-       wIn[0] = (WORD) ((*accum) << 8); accum++;
-       wIn[1] = (WORD) ((*accum) << 8); accum++;
-       wIn[2] = (WORD) ((*accum) << 8); accum++;
-
-       return accum;
-}
-
-
-// BRG
-
-static
-LPBYTE Unroll3BytesSwap(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-
-       wIn[2] = RGB_8_TO_16(*accum); accum++;     // B
-       wIn[1] = RGB_8_TO_16(*accum); accum++;     // G
-       wIn[0] = RGB_8_TO_16(*accum); accum++;     // R
-
-       return accum;
+    output++;
+    *output++ = (wOut[0] & 0xFF);
+    *output++ = (wOut[1] & 0xFF);
+    *output++ = (wOut[2] & 0xFF);
+
+    return output;
 }
 
 static
-LPBYTE Unroll3Words(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3BytesAndSkip1Swap(register _cmsTRANSFORM* Info,
+                                       register cmsUInt16Number wOut[],
+                                       register cmsUInt8Number* output,
+                                       register cmsUInt32Number Stride)
 {
-       wIn[0] = *(LPWORD) accum; accum+= 2;  // C R
-       wIn[1] = *(LPWORD) accum; accum+= 2;  // M G
-       wIn[2] = *(LPWORD) accum; accum+= 2;  // Y B
-       return accum;
+    output++;
+    *output++ = FROM_16_TO_8(wOut[2]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[0]);
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3BytesAndSkip1SwapOptimized(register _cmsTRANSFORM* Info,
+                                                register cmsUInt16Number wOut[],
+                                                register cmsUInt8Number* output,
+                                                register cmsUInt32Number Stride)
+{
+    output++;
+    *output++ = (wOut[2] & 0xFF);
+    *output++ = (wOut[1] & 0xFF);
+    *output++ = (wOut[0] & 0xFF);
+
+    return output;
 }
 
 
 static
-LPBYTE Unroll3WordsSwap(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3BytesAndSkip1SwapSwapFirst(register _cmsTRANSFORM* Info,
+                                                register cmsUInt16Number wOut[],
+                                                register cmsUInt8Number* output,
+                                                register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[2]);
+    *output++ = FROM_16_TO_8(wOut[1]);
+    *output++ = FROM_16_TO_8(wOut[0]);
+    output++;
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3BytesAndSkip1SwapSwapFirstOptimized(register _cmsTRANSFORM* Info,
+                                                         register cmsUInt16Number wOut[],
+                                                         register cmsUInt8Number* output,
+                                                         register cmsUInt32Number Stride)
+{
+    *output++ = (wOut[2] & 0xFF);
+    *output++ = (wOut[1] & 0xFF);
+    *output++ = (wOut[0] & 0xFF);
+    output++;
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3WordsAndSkip1(register _cmsTRANSFORM* Info,
+                                   register cmsUInt16Number wOut[],
+                                   register cmsUInt8Number* output,
+                                   register cmsUInt32Number Stride)
 {
-       wIn[2] = *(LPWORD) accum; accum+= 2;  // C R
-       wIn[1] = *(LPWORD) accum; accum+= 2;  // M G
-       wIn[0] = *(LPWORD) accum; accum+= 2;  // Y B
-       return accum;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+    output+= 2;
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack3WordsAndSkip1Swap(register _cmsTRANSFORM* Info,
+                                       register cmsUInt16Number wOut[],
+                                       register cmsUInt8Number* output,
+                                       register cmsUInt32Number Stride)
+{
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+
+    return output;
+}
+
+
+static
+cmsUInt8Number* Pack3WordsAndSkip1SwapFirst(register _cmsTRANSFORM* Info,
+                                            register cmsUInt16Number wOut[],
+                                            register cmsUInt8Number* output,
+                                            register cmsUInt32Number Stride)
+{
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+
+    return output;
 }
 
 
 static
-LPBYTE Unroll3WordsBigEndian(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack3WordsAndSkip1SwapSwapFirst(register _cmsTRANSFORM* Info,
+                                                register cmsUInt16Number wOut[],
+                                                register cmsUInt8Number* output,
+                                                register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = wOut[2];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[1];
+    output+= 2;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+    output+= 2;
+
+    return output;
+}
+
+
+
+static
+cmsUInt8Number* Pack1Byte(register _cmsTRANSFORM* Info,
+                          register cmsUInt16Number wOut[],
+                          register cmsUInt8Number* output,
+                          register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(wOut[0]);
+    return output;
+}
+
+
+static
+cmsUInt8Number* Pack1ByteReversed(register _cmsTRANSFORM* Info,
+                                  register cmsUInt16Number wOut[],
+                                  register cmsUInt8Number* output,
+                                  register cmsUInt32Number Stride)
+{
+    *output++ = FROM_16_TO_8(REVERSE_FLAVOR_16(wOut[0]));
+    return output;
+}
+
+
+static
+cmsUInt8Number* Pack1ByteSkip1(register _cmsTRANSFORM* Info,
+                               register cmsUInt16Number wOut[],
+                               register cmsUInt8Number* output,
+                               register cmsUInt32Number Stride)
 {
-       wIn[0] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-       wIn[1] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-       wIn[2] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-       return accum;
+    *output++ = FROM_16_TO_8(wOut[0]);
+    output++;
+    return output;
+}
+
+
+static
+cmsUInt8Number* Pack1ByteSkip1SwapFirst(register _cmsTRANSFORM* Info,
+                                        register cmsUInt16Number wOut[],
+                                        register cmsUInt8Number* output,
+                                        register cmsUInt32Number Stride)
+{
+    output++;
+    *output++ = FROM_16_TO_8(wOut[0]);
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack1Word(register _cmsTRANSFORM* Info,
+                          register cmsUInt16Number wOut[],
+                          register cmsUInt8Number* output,
+                          register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+
+    return output;
+}
+
+
+static
+cmsUInt8Number* Pack1WordReversed(register _cmsTRANSFORM* Info,
+                                  register cmsUInt16Number wOut[],
+                                  register cmsUInt8Number* output,
+                                  register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = REVERSE_FLAVOR_16(wOut[0]);
+    output+= 2;
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack1WordBigEndian(register _cmsTRANSFORM* Info,
+                                   register cmsUInt16Number wOut[],
+                                   register cmsUInt8Number* output,
+                                   register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = CHANGE_ENDIAN(wOut[0]);
+    output+= 2;
+
+    return output;
 }
 
 
 static
-LPBYTE Unroll3WordsSwapBigEndian(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* Pack1WordSkip1(register _cmsTRANSFORM* Info,
+                               register cmsUInt16Number wOut[],
+                               register cmsUInt8Number* output,
+                               register cmsUInt32Number Stride)
+{
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 4;
+
+    return output;
+}
+
+static
+cmsUInt8Number* Pack1WordSkip1SwapFirst(register _cmsTRANSFORM* Info,
+                                        register cmsUInt16Number wOut[],
+                                        register cmsUInt8Number* output,
+                                        register cmsUInt32Number Stride)
 {
-       wIn[2] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-       wIn[1] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-       wIn[0] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-       return accum;
+    output += 2;
+    *(cmsUInt16Number*) output = wOut[0];
+    output+= 2;
+
+    return output;
 }
 
 
-
-// Monochrome duplicates L into RGB for null-transforms
+// Unencoded Float values -- don't try optimize speed
+static
+cmsUInt8Number* PackLabDoubleFrom16(register _cmsTRANSFORM* Info,
+                                    register cmsUInt16Number wOut[],
+                                    register cmsUInt8Number* output,
+                                    register cmsUInt32Number Stride)
+{
+
+    if (T_PLANAR(Info -> OutputFormat)) {
+
+        cmsCIELab  Lab;
+        cmsFloat64Number* Out = (cmsFloat64Number*) output;
+        cmsLabEncoded2Float(&Lab, wOut);
+
+        Out[0]        = Lab.L;
+        Out[Stride]   = Lab.a;
+        Out[Stride*2] = Lab.b;
+
+        return output + sizeof(cmsFloat64Number);
+    }
+    else {
+
+        cmsLabEncoded2Float((cmsCIELab*) output, wOut);
+        return output + (sizeof(cmsCIELab) + T_EXTRA(Info ->OutputFormat) * sizeof(cmsFloat64Number));
+    }
+
+}
 
 static
-LPBYTE Unroll1Byte(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackXYZDoubleFrom16(register _cmsTRANSFORM* Info,
+                                    register cmsUInt16Number wOut[],
+                                    register cmsUInt8Number* output,
+                                    register cmsUInt32Number Stride)
 {
-       wIn[0] = wIn[1] = wIn[2] = RGB_8_TO_16(*accum); accum++;     // L
-       return accum;
+    if (T_PLANAR(Info -> OutputFormat)) {
+
+        cmsCIEXYZ XYZ;
+        cmsFloat64Number* Out = (cmsFloat64Number*) output;
+        cmsXYZEncoded2Float(&XYZ, wOut);
+
+        Out[0]                  = XYZ.X;
+        Out[Stride]   = XYZ.Y;
+        Out[Stride*2] = XYZ.Z;
+
+        return output + sizeof(cmsFloat64Number);
+
+    }
+    else {
+
+        cmsXYZEncoded2Float((cmsCIEXYZ*) output, wOut);
+
+        return output + (sizeof(cmsCIEXYZ) + T_EXTRA(Info ->OutputFormat) * sizeof(cmsFloat64Number));
+    }
 }
 
-
 static
-LPBYTE Unroll1ByteSkip2(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackDoubleFrom16(register _cmsTRANSFORM* Info,
+                                 register cmsUInt16Number wOut[],
+                                 register cmsUInt8Number* output,
+                                 register cmsUInt32Number Stride)
 {
-       wIn[0] = wIn[1] = wIn[2] = RGB_8_TO_16(*accum); accum++;     // L
-       accum += 2;
-       return accum;
+    cmsFloat64Number* Inks = (cmsFloat64Number*) output;
+    int nChan = T_CHANNELS(Info -> OutputFormat);
+    int i;
+    cmsFloat64Number maximum = IsInkSpace(Info ->InputFormat) ? 655.35 : 65535.0;
+
+    if (T_PLANAR(Info -> OutputFormat)) {
+
+        for (i=0; i <  nChan; i++) {
+
+            Inks[i*Stride] = wOut[i] / maximum;
+        }
+
+        return output + sizeof(cmsFloat64Number);
+    }
+    else {
+
+        for (i=0; i <  nChan; i++) {
+
+            Inks[i] = wOut[i] /  maximum;
+        }
+
+
+        return output + (nChan + T_EXTRA(Info ->OutputFormat)) * sizeof(cmsFloat64Number);
+    }
+
 }
 
 static
-LPBYTE Unroll1ByteReversed(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackFloatFrom16(register _cmsTRANSFORM* Info,
+                                register cmsUInt16Number wOut[],
+                                register cmsUInt8Number* output,
+                                register cmsUInt32Number Stride)
 {
-       wIn[0] = wIn[1] = wIn[2] = REVERSE_FLAVOR_16(RGB_8_TO_16(*accum)); accum++;     // L
-       return accum;
+    cmsFloat32Number* Inks = (cmsFloat32Number*) output;
+    int nChan = T_CHANNELS(Info -> OutputFormat);
+    int i;
+    cmsFloat64Number maximum = IsInkSpace(Info ->OutputFormat) ? 655.35 : 65535.0;
+
+    if (T_PLANAR(Info -> OutputFormat)) {
+
+        for (i=0; i <  nChan; i++) {
+
+            Inks[i*Stride] = (cmsFloat32Number) (wOut[i] / maximum);
+        }
+
+        return output + sizeof(cmsFloat32Number);
+    }
+    else {
+
+        for (i=0; i <  nChan; i++) {
+
+            Inks[i] = (cmsFloat32Number) (wOut[i] /  maximum);
+        }
+
+
+        return output + (nChan + T_EXTRA(Info ->OutputFormat)) * sizeof(cmsFloat32Number);
+    }
+
 }
 
 
+// --------------------------------------------------------------------------------------------------------
+
 static
-LPBYTE Unroll1Word(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackChunkyFloatsFromFloat(_cmsTRANSFORM* info,
+                                          cmsFloat32Number wOut[],
+                                          cmsUInt8Number* output,
+                                          cmsUInt32Number Stride)
 {
-       wIn[0] = wIn[1] = wIn[2] = *(LPWORD) accum; accum+= 2;   // L
-       return accum;
+    int nChan      = T_CHANNELS(info -> OutputFormat);
+    int DoSwap     = T_DOSWAP(info ->OutputFormat);
+    int Reverse    = T_FLAVOR(info ->OutputFormat);
+    int Extra      = T_EXTRA(info -> OutputFormat);
+    int SwapFirst  = T_SWAPFIRST(info -> OutputFormat);
+    int ExtraFirst = DoSwap && !SwapFirst;
+    cmsFloat64Number maximum = IsInkSpace(info ->OutputFormat) ? 100.0 : 1.0;
+    cmsFloat32Number* swap1;
+    cmsFloat64Number v = 0;
+    int i;
+
+    swap1 = (cmsFloat32Number*) output;
+
+    if (ExtraFirst) {
+        output += Extra * sizeof(cmsFloat32Number);
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+
+        v = wOut[index] * maximum;
+
+        if (Reverse)
+            v = maximum - v;
+
+        *(cmsFloat32Number*) output = (cmsFloat32Number) v;
+
+        output += sizeof(cmsFloat32Number);
+    }
+
+    if (!ExtraFirst) {
+        output += Extra * sizeof(cmsFloat32Number);
+    }
+
+    if (Extra == 0 && SwapFirst) {
+
+        memmove(swap1 + 1, swap1, (nChan-1)* sizeof(cmsFloat32Number));
+        *swap1 = (cmsFloat32Number) v;
+    }
+
+
+    return output;
 }
 
 static
-LPBYTE Unroll1WordReversed(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackPlanarFloatsFromFloat(_cmsTRANSFORM* info,
+                                          cmsFloat32Number wOut[],
+                                          cmsUInt8Number* output,
+                                          cmsUInt32Number Stride)
 {
-       wIn[0] = wIn[1] = wIn[2] = REVERSE_FLAVOR_16(*(LPWORD) accum); accum+= 2;
-       return accum;
+    int nChan = T_CHANNELS(info -> OutputFormat);
+    int DoSwap = T_DOSWAP(info ->OutputFormat);
+    int Reverse= T_FLAVOR(info ->OutputFormat);
+    int i;
+    cmsUInt8Number* Init = output;
+    cmsFloat64Number maximum = IsInkSpace(info ->OutputFormat) ? 100.0 : 1.0;
+    cmsFloat64Number v;
+
+    if (DoSwap) {
+        output += T_EXTRA(info -> OutputFormat) * Stride * sizeof(cmsFloat32Number);
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+
+        v = wOut[index] * maximum;
+
+        if (Reverse)
+            v =  maximum - v;
+
+        *(cmsFloat32Number*) output = (cmsFloat32Number) v;
+        output += (Stride * sizeof(cmsFloat32Number));
+    }
+
+    return (Init + sizeof(cmsFloat32Number));
 }
 
 
 static
-LPBYTE Unroll1WordBigEndian(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       wIn[0] = wIn[1] = wIn[2] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-       return accum;
-}
-
-static
-LPBYTE Unroll1WordSkip3(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackChunkyDoublesFromFloat(_cmsTRANSFORM* info,
+                                           cmsFloat32Number wOut[],
+                                           cmsUInt8Number* output,
+                                           cmsUInt32Number Stride)
 {
-       wIn[0] = wIn[1] = wIn[2] = *(LPWORD) accum;
-
-       accum += 8;
-       return accum;
-}
-
-
-// Monochrome + alpha. Alpha is lost
-
-static
-LPBYTE Unroll2Byte(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       wIn[0] = wIn[1] = wIn[2] = RGB_8_TO_16(*accum); accum++;     // L
-       wIn[3] = RGB_8_TO_16(*accum); accum++;                       // alpha
-       return accum;
+    int nChan      = T_CHANNELS(info -> OutputFormat);
+    int DoSwap     = T_DOSWAP(info ->OutputFormat);
+    int Reverse    = T_FLAVOR(info ->OutputFormat);
+    int Extra      = T_EXTRA(info -> OutputFormat);
+    int SwapFirst  = T_SWAPFIRST(info -> OutputFormat);
+    int ExtraFirst = DoSwap && !SwapFirst;
+    cmsFloat64Number* swap1;
+    cmsFloat64Number maximum = IsInkSpace(info ->OutputFormat) ? 100.0 : 1.0;
+    cmsFloat64Number v = 0;
+    int i;
+
+    swap1 = (cmsFloat64Number*) output;
+
+    if (ExtraFirst) {
+        output += Extra * sizeof(cmsFloat64Number);
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+
+        v = (cmsFloat64Number) wOut[index] * maximum;
+
+        if (Reverse)
+            v = maximum - v;
+
+        *(cmsFloat64Number*) output = v;
+
+        output += sizeof(cmsFloat64Number);
+    }
+
+    if (!ExtraFirst) {
+        output += Extra * sizeof(cmsFloat64Number);
+    }
+
+    if (Extra == 0 && SwapFirst) {
+
+        memmove(swap1 + 1, swap1, (nChan-1)* sizeof(cmsFloat64Number));
+        *swap1 = v;
+    }
+
+
+    return output;
 }
 
 static
-LPBYTE Unroll2ByteSwapFirst(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       wIn[3] = RGB_8_TO_16(*accum); accum++;                       // alpha
-       wIn[0] = wIn[1] = wIn[2] = RGB_8_TO_16(*accum); accum++;     // L
-       return accum;
-}
-
-
-static
-LPBYTE Unroll2Word(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackPlanarDoublesFromFloat(_cmsTRANSFORM* info,
+                                           cmsFloat32Number wOut[],
+                                           cmsUInt8Number* output,
+                                           cmsUInt32Number Stride)
 {
-       wIn[0] = wIn[1] = wIn[2] = *(LPWORD) accum; accum+= 2;   // L
-       wIn[3] = *(LPWORD) accum; accum += 2;                    // alpha
-
-       return accum;
-}
-
-
-static
-LPBYTE Unroll2WordSwapFirst(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       wIn[3] = *(LPWORD) accum; accum += 2;                    // alpha
-       wIn[0] = wIn[1] = wIn[2] = *(LPWORD) accum; accum+= 2;   // L
-
-       return accum;
-}
-
-static
-LPBYTE Unroll2WordBigEndian(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       wIn[0] = wIn[1] = wIn[2] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-       wIn[3] = CHANGE_ENDIAN(*(LPWORD) accum); accum+= 2;
-
-       return accum;
+    int nChan = T_CHANNELS(info -> OutputFormat);
+    int DoSwap = T_DOSWAP(info ->OutputFormat);
+    int Reverse= T_FLAVOR(info ->OutputFormat);
+    int i;
+    cmsUInt8Number* Init = output;
+    cmsFloat64Number maximum = IsInkSpace(info ->OutputFormat) ? 100.0 : 1.0;
+    cmsFloat64Number v;
+
+    if (DoSwap) {
+        output += T_EXTRA(info -> OutputFormat) * Stride * sizeof(cmsFloat64Number);
+    }
+
+    for (i=0; i < nChan; i++) {
+
+        int index = DoSwap ? (nChan - i - 1) : i;
+
+        v = (cmsFloat64Number) wOut[index] * maximum;
+
+        if (Reverse)
+            v =  maximum - v;
+
+        *(cmsFloat64Number*) output = v;
+        output += (Stride * sizeof(cmsFloat64Number));
+    }
+
+    return (Init + sizeof(cmsFloat64Number));
 }
 
 
 
 
 static
-LPBYTE UnrollPlanarBytes(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       int nChan = T_CHANNELS(info -> InputFormat);
-       register int i;
-       LPBYTE Init = accum;
-
-       for (i=0; i < nChan; i++) {
-
-              wIn[i] = RGB_8_TO_16(*accum);
-              accum += info -> StrideIn;
-       }
-
-       return (Init + 1);
-}
-
-
-
-static
-LPBYTE UnrollPlanarWords(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+cmsUInt8Number* PackLabFloatFromFloat(_cmsTRANSFORM* Info,
+                                      cmsFloat32Number wOut[],
+                                      cmsUInt8Number* output,
+                                      cmsUInt32Number Stride)
 {
-       int nChan = T_CHANNELS(info -> InputFormat);
-       register int i;
-       LPBYTE Init = accum;
-
-       for (i=0; i < nChan; i++) {
-
-              wIn[i] = *(LPWORD) accum;
-              accum += (info -> StrideIn * sizeof(WORD));
-       }
-
-       return (Init + sizeof(WORD));
-}
-
-
-
-static
-LPBYTE UnrollPlanarWordsBigEndian(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-       int nChan = T_CHANNELS(info -> InputFormat);
-       register int i;
-       LPBYTE Init = accum;
-
-       for (i=0; i < nChan; i++) {
-
-              wIn[i] = CHANGE_ENDIAN(*(LPWORD) accum);
-              accum += (info -> StrideIn * sizeof(WORD));
-       }
-
-       return (Init + sizeof(WORD));
-}
-
-
-// floating point
-static
-LPBYTE UnrollLabDouble(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-
-    if (T_PLANAR(info -> InputFormat)) {
-
-        double* Pt = (double*) accum;
-
-        cmsCIELab Lab;
-
-        Lab.L = Pt[0];
-        Lab.a = Pt[info->StrideIn];
-        Lab.b = Pt[info->StrideIn*2];
-
-        if (info ->lInputV4Lab)
-            cmsFloat2LabEncoded4(wIn, &Lab);
-        else
-            cmsFloat2LabEncoded(wIn, &Lab);
-
-        return accum + sizeof(double);
+    cmsFloat32Number* Out = (cmsFloat32Number*) output;
+
+    if (T_PLANAR(Info -> OutputFormat)) {
+
+        Out[0]                  = (cmsFloat32Number) (wOut[0] * 100.0);
+        Out[Stride]   = (cmsFloat32Number) (wOut[1] * 255.0 - 128.0);
+        Out[Stride*2] = (cmsFloat32Number) (wOut[2] * 255.0 - 128.0);
+
+        return output + sizeof(cmsFloat32Number);
     }
     else {
 
-        if (info ->lInputV4Lab)
-            cmsFloat2LabEncoded4(wIn, (LPcmsCIELab) accum);
-        else
-            cmsFloat2LabEncoded(wIn, (LPcmsCIELab) accum);
-
-        accum += sizeof(cmsCIELab);
-
-        return accum;
-    }
-}
-
-static
-LPBYTE UnrollXYZDouble(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-    if (T_PLANAR(info -> InputFormat)) {
-
-        double* Pt = (double*) accum;
-        cmsCIEXYZ XYZ;
-
-        XYZ.X = Pt[0];
-        XYZ.Y = Pt[info->StrideIn];
-        XYZ.Z = Pt[info->StrideIn*2];
-        cmsFloat2XYZEncoded(wIn, &XYZ);
-
-        return accum + sizeof(double);
-
-    }
-
-    else {
-
-
-        cmsFloat2XYZEncoded(wIn, (LPcmsCIEXYZ) accum);
-        accum += sizeof(cmsCIEXYZ);
-
-        return accum;
-    }
-}
-
-
-
-// Inks does come in percentage
-static
-LPBYTE UnrollInkDouble(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-    double* Inks = (double*) accum;
-    int nChan  = T_CHANNELS(info -> InputFormat);
-    int Planar = T_PLANAR(info -> InputFormat);
-    int i;
-    double v;
-
-    for (i=0; i <  nChan; i++) {
-
-        if (Planar)
-
-            v = Inks[i * info ->StrideIn];
-        else
-            v = Inks[i];
-
-        v = floor(v * 655.35 + 0.5);
-
-        if (v > 65535.0) v = 65535.0;
-        if (v < 0) v = 0;
-
-        wIn[i] = (WORD) v;
-    }
-
-    if (T_PLANAR(info -> InputFormat))
-        return accum + sizeof(double);
-    else
-        return accum + (nChan + T_EXTRA(info ->InputFormat)) * sizeof(double);
-}
-
-
-// Remaining cases are between 0..1.0
-static
-LPBYTE UnrollDouble(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-    double* Inks = (double*) accum;
-    int nChan = T_CHANNELS(info -> InputFormat);
-    int Planar = T_PLANAR(info -> InputFormat);
-    int i;
-    double v;
-
-    for (i=0; i < nChan; i++) {
-
-        if (Planar)
-
-            v = Inks[i * info ->StrideIn];
-        else
-            v = Inks[i];
-
-        v = floor(v * 65535.0 + 0.5);
-
-        if (v > 65535.0) v = 65535.0;
-        if (v < 0) v = 0;
-
-        wIn[i] = (WORD) v;
-    }
-
-    if (T_PLANAR(info -> InputFormat))
-        return accum + sizeof(double);
-    else
-        return accum + (nChan + T_EXTRA(info ->InputFormat)) * sizeof(double);
-}
-
-
-
-static
-LPBYTE UnrollDouble1Chan(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
-{
-    double* Inks = (double*) accum;
-    double v;
-
-
-    v = floor(Inks[0] * 65535.0 + 0.5);
-
-    if (v > 65535.0) v = 65535.0;
-    if (v < 0) v = 0;
-
-
-    wIn[0] = wIn[1] = wIn[2] = (WORD) v;
-
-    return accum + sizeof(double);
-}
-
-
-// ----------------------------------------------------------- Packing routines
-
-
-// Generic N-bytes plus dither 16-to-8 conversion. Currently is just a quick hack
-
-static int err[MAXCHANNELS];
-
-static
-LPBYTE PackNBytesDither(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan  = T_CHANNELS(info -> OutputFormat);
-       register int i;
-       unsigned int n, pe, pf;
-
-       for (i=0; i < nChan;  i++) {
-
-              n = wOut[i] + err[i]; // Value
-
-              pe = (n / 257);       // Whole part
-              pf = (n % 257);       // Fractional part
-
-              err[i] = pf;          // Store it for next pixel
-
-              *output++ = (BYTE) pe;
-       }
-
-       return output + T_EXTRA(info ->OutputFormat);
-}
-
-
-
-static
-LPBYTE PackNBytesSwapDither(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan  = T_CHANNELS(info -> OutputFormat);
-       register int i;
-       unsigned int n, pe, pf;
-
-       for (i=nChan-1; i >= 0;  --i) {
-
-              n = wOut[i] + err[i];     // Value
-
-              pe = (n / 257);           // Whole part
-              pf = (n % 257);           // Fractional part
-
-              err[i] = pf;              // Store it for next pixel
-
-              *output++ = (BYTE) pe;
-       }
-
-
-       return output + T_EXTRA(info ->OutputFormat);
-}
-
-
-
-// Generic chunky for byte
-
-static
-LPBYTE PackNBytes(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan  = T_CHANNELS(info -> OutputFormat);
-       register int i;
-
-       for (i=0; i < nChan;  i++)
-              *output++ = RGB_16_TO_8(wOut[i]);
-
-       return output + T_EXTRA(info ->OutputFormat);
-}
-
-// Chunky reversed order bytes
-
-static
-LPBYTE PackNBytesSwap(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan  = T_CHANNELS(info -> OutputFormat);
-       register int i;
-
-       for (i=nChan-1; i >= 0;  --i)
-              *output++ = RGB_16_TO_8(wOut[i]);
-
-       return output + T_EXTRA(info ->OutputFormat);
-
-}
-
-
-static
-LPBYTE PackNWords(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan  = T_CHANNELS(info -> OutputFormat);
-       register int i;
-
-       for (i=0; i < nChan; i++) {
-              *(LPWORD) output = wOut[i];
-              output += sizeof(WORD);
-       }
-
-       return output + T_EXTRA(info ->OutputFormat) * sizeof(WORD);
-}
-
-static
-LPBYTE PackNWordsSwap(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan  = T_CHANNELS(info -> OutputFormat);
-       register int i;
-
-       for (i=nChan-1; i >= 0; --i) {
-              *(LPWORD) output = wOut[i];
-              output += sizeof(WORD);
-       }
-
-       return output + T_EXTRA(info ->OutputFormat) * sizeof(WORD);
-}
-
-
-
-static
-LPBYTE PackNWordsBigEndian(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan  = T_CHANNELS(info -> OutputFormat);
-       register int i;
-
-       for (i=0; i < nChan; i++) {
-              *(LPWORD) output = CHANGE_ENDIAN(wOut[i]);
-              output += sizeof(WORD);
-       }
-
-       return output + T_EXTRA(info ->OutputFormat) * sizeof(WORD);
-}
-
-
-static
-LPBYTE PackNWordsSwapBigEndian(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan  = T_CHANNELS(info -> OutputFormat);
-       register int i;
-
-       for (i=nChan-1; i >= 0; --i) {
-              *(LPWORD) output = CHANGE_ENDIAN(wOut[i]);
-              output += sizeof(WORD);
-       }
-
-       return output + T_EXTRA(info ->OutputFormat) * sizeof(WORD);
-}
-
-
-static
-LPBYTE PackPlanarBytes(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan = T_CHANNELS(info -> OutputFormat);
-       register int i;
-       LPBYTE Init = output;
-
-       for (i=0; i < nChan; i++) {
-
-              *(LPBYTE) output = RGB_16_TO_8(wOut[i]);
-              output += info -> StrideOut;
-       }
-
-       return (Init + 1);
-}
-
-
-static
-LPBYTE PackPlanarWords(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       int nChan = T_CHANNELS(info -> OutputFormat);
-       register int i;
-       LPBYTE Init = output;
-
-       for (i=0; i < nChan; i++) {
-
-              *(LPWORD) output = wOut[i];
-              output += (info -> StrideOut * sizeof(WORD));
-       }
-
-       return (Init + 2);
-}
-
-
-// CMYKcm (unrolled for speed)
-
-static
-LPBYTE Pack6Bytes(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-         *output++ = RGB_16_TO_8(wOut[0]);
-         *output++ = RGB_16_TO_8(wOut[1]);
-         *output++ = RGB_16_TO_8(wOut[2]);
-         *output++ = RGB_16_TO_8(wOut[3]);
-         *output++ = RGB_16_TO_8(wOut[4]);
-         *output++ = RGB_16_TO_8(wOut[5]);
-
-         return output;
-}
-
-// KCMYcm
-
-static
-LPBYTE Pack6BytesSwap(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[3]);
-       *output++ = RGB_16_TO_8(wOut[0]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[2]);
-       *output++ = RGB_16_TO_8(wOut[4]);
-       *output++ = RGB_16_TO_8(wOut[5]);
-
-       return output;
-}
-
-// CMYKcm
-static
-LPBYTE Pack6Words(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-       *(LPWORD) output = wOut[3];
-       output+= 2;
-       *(LPWORD) output = wOut[4];
-       output+= 2;
-       *(LPWORD) output = wOut[5];
-       output+= 2;
-
-       return output;
-}
-
-// KCMYcm
-static
-LPBYTE Pack6WordsSwap(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[3];
-       output+= 2;
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-       *(LPWORD) output = wOut[4];
-       output+= 2;
-       *(LPWORD) output = wOut[5];
-       output+= 2;
-
-       return output;
-}
-
-// CMYKcm
-static
-LPBYTE Pack6WordsBigEndian(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[2]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[3]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[4]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[5]);
-       output+= 2;
-
-       return output;
-}
-
-// KCMYcm
-static
-LPBYTE Pack6WordsSwapBigEndian(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[3]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[2]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[4]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[5]);
-       output+= 2;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack4Bytes(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-         *output++ = RGB_16_TO_8(wOut[0]);
-         *output++ = RGB_16_TO_8(wOut[1]);
-         *output++ = RGB_16_TO_8(wOut[2]);
-         *output++ = RGB_16_TO_8(wOut[3]);
-
-         return output;
-}
-
-static
-LPBYTE Pack4BytesReverse(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-         *output++ = REVERSE_FLAVOR_8(RGB_16_TO_8(wOut[0]));
-         *output++ = REVERSE_FLAVOR_8(RGB_16_TO_8(wOut[1]));
-         *output++ = REVERSE_FLAVOR_8(RGB_16_TO_8(wOut[2]));
-         *output++ = REVERSE_FLAVOR_8(RGB_16_TO_8(wOut[3]));
-
-         return output;
-}
-
-
-static
-LPBYTE Pack4BytesSwapFirst(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-         *output++ = RGB_16_TO_8(wOut[3]);
-         *output++ = RGB_16_TO_8(wOut[0]);
-         *output++ = RGB_16_TO_8(wOut[1]);
-         *output++ = RGB_16_TO_8(wOut[2]);
-
-         return output;
-}
-
-
-// ABGR
-
-static
-LPBYTE Pack4BytesSwap(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[3]);
-       *output++ = RGB_16_TO_8(wOut[2]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[0]);
-
-       return output;
-}
-
-
-static
-LPBYTE Pack4BytesSwapSwapFirst(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[2]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[0]);
-       *output++ = RGB_16_TO_8(wOut[3]);
-
-       return output;
-}
-
-
-static
-LPBYTE Pack4Words(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-       *(LPWORD) output = wOut[3];
-       output+= 2;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack4WordsReverse(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = REVERSE_FLAVOR_16(wOut[0]);
-       output+= 2;
-       *(LPWORD) output = REVERSE_FLAVOR_16(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = REVERSE_FLAVOR_16(wOut[2]);
-       output+= 2;
-       *(LPWORD) output = REVERSE_FLAVOR_16(wOut[3]);
-       output+= 2;
-
-       return output;
-}
-
-// ABGR
-
-static
-LPBYTE Pack4WordsSwap(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[3];
-       output+= 2;
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-
-       return output;
-}
-
-// CMYK
-static
-LPBYTE Pack4WordsBigEndian(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[2]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[3]);
-       output+= 2;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack4WordsBigEndianReverse(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(REVERSE_FLAVOR_16(wOut[0]));
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(REVERSE_FLAVOR_16(wOut[1]));
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(REVERSE_FLAVOR_16(wOut[2]));
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(REVERSE_FLAVOR_16(wOut[3]));
-       output+= 2;
-
-       return output;
-}
-
-// KYMC
-
-static
-LPBYTE Pack4WordsSwapBigEndian(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[3]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[2]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-
-       return output;
-}
-
-static
-LPBYTE Pack3Bytes(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[0]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[2]);
-
-       return output;
-}
-
-static
-LPBYTE Pack3BytesLab(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = (BYTE) (wOut[0] >> 8);
-       *output++ = (BYTE) (wOut[1] >> 8);
-       *output++ = (BYTE) (wOut[2] >> 8);
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3BytesSwap(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[2]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[0]);
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3Words(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-
-       return output;
-}
-
-static
-LPBYTE Pack3WordsSwap(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-
-       return output;
-}
-
-static
-LPBYTE Pack3WordsBigEndian(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[2]);
-       output+= 2;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3WordsSwapBigEndian(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[2]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3BytesAndSkip1(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[0]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[2]);
-       output++;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3BytesAndSkip1SwapFirst(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-        output++;
-       *output++ = RGB_16_TO_8(wOut[0]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[2]);
-
-       return output;
-}
-
-static
-LPBYTE Pack3BytesAndSkip1Swap(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-        output++;
-       *output++ = RGB_16_TO_8(wOut[2]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[0]);
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3BytesAndSkip1SwapSwapFirst(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[2]);
-       *output++ = RGB_16_TO_8(wOut[1]);
-       *output++ = RGB_16_TO_8(wOut[0]);
-       output++;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3WordsAndSkip1(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-       output+= 2;
-
-       return output;
-}
-
-static
-LPBYTE Pack3WordsAndSkip1Swap(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       output+= 2;
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3WordsAndSkip1SwapSwapFirst(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[2];
-       output+= 2;
-       *(LPWORD) output = wOut[1];
-       output+= 2;
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-       output+= 2;
-
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3WordsAndSkip1BigEndian(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[2]);
-       output+= 2;
-       output+= 2;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack3WordsAndSkip1SwapBigEndian(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-        output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[2]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[1]);
-       output+= 2;
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-
-
-       return output;
-}
-
-
-
-static
-LPBYTE Pack1Byte(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[0]);
-       return output;
-}
-
-
-static
-LPBYTE Pack1ByteAndSkip1(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *output++ = RGB_16_TO_8(wOut[0]);
-       output++;
-       return output;
-}
-
-
-static
-LPBYTE Pack1ByteAndSkip1SwapFirst(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       output++;
-       *output++ = RGB_16_TO_8(wOut[0]);
-
-       return output;
-}
-
-static
-LPBYTE Pack1Word(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-
-       return output;
-}
-
-static
-LPBYTE Pack1WordBigEndian(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 2;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack1WordAndSkip1(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = wOut[0];
-       output+= 4;
-
-       return output;
-}
-
-static
-LPBYTE Pack1WordAndSkip1SwapFirst(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       output += 2;
-       *(LPWORD) output = wOut[0];
-       output+= 2;
-
-       return output;
-}
-
-
-static
-LPBYTE Pack1WordAndSkip1BigEndian(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-       *(LPWORD) output = CHANGE_ENDIAN(wOut[0]);
-       output+= 4;
-
-       return output;
-}
-
-
-// Unencoded Float values -- don't try optimize speed
-
-static
-LPBYTE PackLabDouble(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-
-    if (T_PLANAR(Info -> OutputFormat)) {
-
-        cmsCIELab  Lab;
-        double* Out = (double*) output;
-        cmsLabEncoded2Float(&Lab, wOut);
-
-        Out[0]                  = Lab.L;
-        Out[Info ->StrideOut]   = Lab.a;
-        Out[Info ->StrideOut*2] = Lab.b;
-
-        return output + sizeof(double);
-
-    }
-    else {
-
-       if (Info ->lOutputV4Lab)
-           cmsLabEncoded2Float4((LPcmsCIELab) output, wOut);
-       else
-           cmsLabEncoded2Float((LPcmsCIELab) output, wOut);
-
-        return output + (sizeof(cmsCIELab) + T_EXTRA(Info ->OutputFormat) * sizeof(double));
+        Out[0] = (cmsFloat32Number) (wOut[0] * 100.0);
+        Out[1] = (cmsFloat32Number) (wOut[1] * 255.0 - 128.0);
+        Out[2] = (cmsFloat32Number) (wOut[2] * 255.0 - 128.0);
+
+        return output + (sizeof(cmsFloat32Number)*3 + T_EXTRA(Info ->OutputFormat) * sizeof(cmsFloat32Number));
     }
 
 }
 
 static
-LPBYTE PackXYZDouble(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
+cmsUInt8Number* PackLabDoubleFromFloat(_cmsTRANSFORM* Info,
+                                       cmsFloat32Number wOut[],
+                                       cmsUInt8Number* output,
+                                       cmsUInt32Number Stride)
 {
+    cmsFloat64Number* Out = (cmsFloat64Number*) output;
 
     if (T_PLANAR(Info -> OutputFormat)) {
 
-        cmsCIEXYZ XYZ;
-        double* Out = (double*) output;
-        cmsXYZEncoded2Float(&XYZ, wOut);
-
-        Out[0]                  = XYZ.X;
-        Out[Info ->StrideOut]   = XYZ.Y;
-        Out[Info ->StrideOut*2] = XYZ.Z;
-
-        return output + sizeof(double);
-
+        Out[0]                  = (cmsFloat64Number) (wOut[0] * 100.0);
+        Out[Stride]   = (cmsFloat64Number) (wOut[1] * 255.0 - 128.0);
+        Out[Stride*2] = (cmsFloat64Number) (wOut[2] * 255.0 - 128.0);
+
+        return output + sizeof(cmsFloat64Number);
     }
     else {
 
-        cmsXYZEncoded2Float((LPcmsCIEXYZ) output, wOut);
-
-        return output + (sizeof(cmsCIEXYZ) + T_EXTRA(Info ->OutputFormat) * sizeof(double));
-    }
-}
-
-
-
-static
-LPBYTE PackInkDouble(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
-{
-    double* Inks = (double*) output;
-    int nChan = T_CHANNELS(Info -> OutputFormat);
-    int i;
-
-    if (T_PLANAR(Info -> OutputFormat)) {
-
-        for (i=0; i <  nChan; i++) {
-
-            Inks[i*Info ->StrideOut] = wOut[i] / 655.35;
-        }
-
-        return output + sizeof(double);
-    }
-    else {
-
-        for (i=0; i <  nChan; i++) {
-
-            Inks[i] = wOut[i] /  655.35;
-        }
-
-
-    return output + (nChan + T_EXTRA(Info ->OutputFormat)) * sizeof(double);
+        Out[0] = (cmsFloat64Number) (wOut[0] * 100.0);
+        Out[1] = (cmsFloat64Number) (wOut[1] * 255.0 - 128.0);
+        Out[2] = (cmsFloat64Number) (wOut[2] * 255.0 - 128.0);
+
+        return output + (sizeof(cmsFloat64Number)*3 + T_EXTRA(Info ->OutputFormat) * sizeof(cmsFloat64Number));
     }
 
 }
 
 
+// From 0..1 range to 0..MAX_ENCODEABLE_XYZ
 static
-LPBYTE PackDouble(register _LPcmsTRANSFORM Info, register WORD wOut[], register LPBYTE output)
+cmsUInt8Number* PackXYZFloatFromFloat(_cmsTRANSFORM* Info,
+                                      cmsFloat32Number wOut[],
+                                      cmsUInt8Number* output,
+                                      cmsUInt32Number Stride)
 {
-    double* Inks = (double*) output;
-    int nChan = T_CHANNELS(Info -> OutputFormat);
-    int i;
-
+    cmsFloat32Number* Out = (cmsFloat32Number*) output;
 
     if (T_PLANAR(Info -> OutputFormat)) {
 
-        for (i=0; i <  nChan; i++) {
-
-            Inks[i*Info ->StrideOut] = wOut[i] / 65535.0;
-        }
-
-        return output + sizeof(double);
-
+        Out[0]                  = (cmsFloat32Number) (wOut[0] * MAX_ENCODEABLE_XYZ);
+        Out[Stride]   = (cmsFloat32Number) (wOut[1] * MAX_ENCODEABLE_XYZ);
+        Out[Stride*2] = (cmsFloat32Number) (wOut[2] * MAX_ENCODEABLE_XYZ);
+
+        return output + sizeof(cmsFloat32Number);
     }
     else {
-        for (i=0; i <  nChan; i++) {
-
-            Inks[i] = wOut[i] /  65535.0;
-        }
-
-        return output + (nChan + T_EXTRA(Info ->OutputFormat)) * sizeof(double);
+
+        Out[0] = (cmsFloat32Number) (wOut[0] * MAX_ENCODEABLE_XYZ);
+        Out[1] = (cmsFloat32Number) (wOut[1] * MAX_ENCODEABLE_XYZ);
+        Out[2] = (cmsFloat32Number) (wOut[2] * MAX_ENCODEABLE_XYZ);
+
+        return output + (sizeof(cmsFloat32Number)*3 + T_EXTRA(Info ->OutputFormat) * sizeof(cmsFloat32Number));
+    }
+
+}
+
+
+// Same, but convert to double
+static
+cmsUInt8Number* PackXYZDoubleFromFloat(_cmsTRANSFORM* Info,
+                                       cmsFloat32Number wOut[],
+                                       cmsUInt8Number* output,
+                                       cmsUInt32Number Stride)
+{
+    cmsFloat64Number* Out = (cmsFloat64Number*) output;
+
+    if (T_PLANAR(Info -> OutputFormat)) {
+
+        Out[0]                  = (cmsFloat64Number) (wOut[0] * MAX_ENCODEABLE_XYZ);
+        Out[Stride]   = (cmsFloat64Number) (wOut[1] * MAX_ENCODEABLE_XYZ);
+        Out[Stride*2] = (cmsFloat64Number) (wOut[2] * MAX_ENCODEABLE_XYZ);
+
+        return output + sizeof(cmsFloat64Number);
+    }
+    else {
+
+        Out[0] = (cmsFloat64Number) (wOut[0] * MAX_ENCODEABLE_XYZ);
+        Out[1] = (cmsFloat64Number) (wOut[1] * MAX_ENCODEABLE_XYZ);
+        Out[2] = (cmsFloat64Number) (wOut[2] * MAX_ENCODEABLE_XYZ);
+
+        return output + (sizeof(cmsFloat64Number)*3 + T_EXTRA(Info ->OutputFormat) * sizeof(cmsFloat64Number));
     }
 
 }
 
 
-//  choose routine from Input identifier
-
-_cmsFIXFN _cmsIdentifyInputFormat(_LPcmsTRANSFORM xform, DWORD dwInput)
-{
-       _cmsFIXFN FromInput = NULL;
-
-
-       // Check Named Color
-
-       if (xform) {
-
-           if (xform ->InputProfile) {
-
-           if (cmsGetDeviceClass(xform ->InputProfile) == icSigNamedColorClass) {
-
-                if (dwInput != TYPE_NAMED_COLOR_INDEX) {
-                    cmsSignalError(LCMS_ERRC_ABORTED, "Named color needs TYPE_NAMED_COLOR_INDEX");
-                    return NULL;
-                }
-           }
-
-        }
-       }
-
-       // Unencoded modes
-
-       if (T_BYTES(dwInput) == 0) {
-
-           switch (T_COLORSPACE(dwInput)) {
-
-           case PT_Lab:
-                    FromInput = UnrollLabDouble;
-                    break;
-           case PT_XYZ:
-                    FromInput = UnrollXYZDouble;
-                    break;
-
-           // 0.0 .. 1.0 range
-
-           case PT_GRAY:
-           case PT_RGB:
-           case PT_YCbCr:
-           case PT_YUV:
-           case PT_YUVK:
-           case PT_HSV:
-           case PT_HLS:
-           case PT_Yxy:
-                    if (T_CHANNELS(dwInput) == 1)
-                        FromInput = UnrollDouble1Chan;
-                    else
-                        FromInput = UnrollDouble;
-                    break;
-
-            // Inks (%) 0.0 .. 100.0
-
-           default:
-                    FromInput = UnrollInkDouble;
-                    break;
-           }
-
-       }
-       else {
-
-           if (T_PLANAR(dwInput)) {
-
-               switch (T_BYTES(dwInput)) {
-
-               case 1:
-                   FromInput = UnrollPlanarBytes;
-                   break;
-
-               case 2:
-                   if (T_ENDIAN16(dwInput))
-                       FromInput = UnrollPlanarWordsBigEndian;
-                   else
-                       FromInput = UnrollPlanarWords;
-                   break;
-
-               default:;
-               }
-       }
-       else {
-
-       switch (T_BYTES(dwInput)) {
-
-       case 1: // 1 byte per channel
-
-              switch (T_CHANNELS(dwInput) + T_EXTRA(dwInput)) {
-
-              case 1: if (T_FLAVOR(dwInput))
-                                FromInput = Unroll1ByteReversed;
-                            else
-                                  FromInput = Unroll1Byte;
-                      break;
-
-              case 2: if (T_SWAPFIRST(dwInput))
-                        FromInput = Unroll2ByteSwapFirst;
-                      else
-                        FromInput = Unroll2Byte;
-                      break;
-
-              case 3: if (T_DOSWAP(dwInput))
-                            FromInput = Unroll3BytesSwap;
-                      else {
-                            if (T_EXTRA(dwInput) == 2)
-                                FromInput = Unroll1ByteSkip2;
-                            else
-                                if (T_COLORSPACE(dwInput) == PT_Lab)
-                                    FromInput = Unroll3BytesLab;
-                                else
-                                    FromInput = Unroll3Bytes;
-                      }
-                      break;
-              case 4:
-                      // TODO: ALab8 must be fixed to match v2 encoding
-
-                      if (T_DOSWAP(dwInput)) {
-                            if (T_SWAPFIRST(dwInput))
-
-                                FromInput = Unroll4BytesSwapSwapFirst;
-                            else
-                                FromInput = Unroll4BytesSwap;
-                      }
-                      else {
-                            if (T_SWAPFIRST(dwInput))
-                                FromInput = Unroll4BytesSwapFirst;
-                            else {
-                                if (T_FLAVOR(dwInput))
-                                    FromInput = Unroll4BytesReverse;
-                                else
-                                    FromInput = Unroll4Bytes;
-                            }
-                      }
-                      break;
-
-
-              case 5:
-              case 6:
-              case 7:
-              case 8:
-                   if (!T_DOSWAP(dwInput) && !T_SWAPFIRST(dwInput))
-                       FromInput = UnrollAnyBytes;
-                   break;
-
-
-              default:;
-              }
-              break;
-
-
-       case 2: // 1 word per channel
-
-              switch (T_CHANNELS(dwInput) + T_EXTRA(dwInput))
-              {
-              case 1: if (T_ENDIAN16(dwInput))
-                            FromInput = Unroll1WordBigEndian;
-                      else
-                          if (T_FLAVOR(dwInput))
-                                FromInput = Unroll1WordReversed;
-                            else
-                                  FromInput = Unroll1Word;
-                      break;
-
-              case 2: if (T_ENDIAN16(dwInput))
-                            FromInput = Unroll2WordBigEndian;
-                        else {
-                          if (T_SWAPFIRST(dwInput))
-                              FromInput = Unroll2WordSwapFirst;
-                          else
-                              FromInput = Unroll2Word;
-                        }
-                        break;
-
-              case 3: if (T_DOSWAP(dwInput)) {
-                            if (T_ENDIAN16(dwInput))
-                                   FromInput = Unroll3WordsSwapBigEndian;
-                            else
-                                   FromInput = Unroll3WordsSwap;
-                      }
-                      else {
-                            if (T_ENDIAN16(dwInput))
-                                   FromInput = Unroll3WordsBigEndian;
-                            else
-                                   FromInput = Unroll3Words;
-                      }
-                      break;
-
-              case 4: if (T_DOSWAP(dwInput)) {
-
-                            if (T_ENDIAN16(dwInput))
-                                   FromInput = Unroll4WordsSwapBigEndian;
-                            else {
-
-                                    if (T_SWAPFIRST(dwInput))
-                                        FromInput = Unroll4WordsSwapSwapFirst;
-                                    else
-                                        FromInput = Unroll4WordsSwap;
-
-                            }
-
-                      }
-                      else {
-
-                            if (T_EXTRA(dwInput) == 3)
-                                    FromInput = Unroll1WordSkip3;
-                            else
-
-                                if (T_ENDIAN16(dwInput)) {
-
-                                    if (T_FLAVOR(dwInput))
-                                        FromInput = Unroll4WordsBigEndianReverse;
-                                    else
-                                        FromInput = Unroll4WordsBigEndian;
-                                }
-                            else {
-                                  if (T_SWAPFIRST(dwInput))
-                                    FromInput = Unroll4WordsSwapFirst;
-                                  else {
-                                      if (T_FLAVOR(dwInput))
-                                            FromInput = Unroll4WordsReverse;
-                                      else
-                                            FromInput = Unroll4Words;
-                                  }
-                            }
-                      }
-                      break;
-
-
-              case 5:
-              case 6:
-              case 7:
-              case 8:
-                    if (!T_DOSWAP(dwInput) && !T_SWAPFIRST(dwInput))
-                       FromInput = UnrollAnyWords;
-                    break;
-
-              }
-              break;
-
-       default:;
-       }
-       }
-       }
-
-
-       if (!FromInput)
-              cmsSignalError(LCMS_ERRC_ABORTED, "Unknown input format");
-
-       return FromInput;
-}
-
-//  choose routine from Input identifier
-
-_cmsFIXFN _cmsIdentifyOutputFormat(_LPcmsTRANSFORM xform, DWORD dwOutput)
+// ----------------------------------------------------------------------------------------------------------------
+
+
+static cmsFormatters16 InputFormatters16[] = {
+
+    //    Type                                          Mask                  Function
+    //  ----------------------------   ------------------------------------  ----------------------------
+    { TYPE_Lab_DBL,                                          ANYPLANAR,   UnrollLabDoubleTo16},
+    { TYPE_XYZ_DBL,                                          ANYPLANAR,   UnrollXYZDoubleTo16},
+    { TYPE_GRAY_DBL,                                                 0,   UnrollDouble1Chan},
+    { FLOAT_SH(1)|BYTES_SH(0), ANYCHANNELS|ANYPLANAR|ANYEXTRA|ANYSPACE,   UnrollDoubleTo16},
+    { FLOAT_SH(1)|BYTES_SH(4), ANYCHANNELS|ANYPLANAR|ANYEXTRA|ANYSPACE,   UnrollFloatTo16},
+
+
+    { CHANNELS_SH(1)|BYTES_SH(1),                              ANYSPACE,  Unroll1Byte},
+    { CHANNELS_SH(1)|BYTES_SH(1)|EXTRA_SH(2),                  ANYSPACE,  Unroll1ByteSkip2},
+    { CHANNELS_SH(1)|BYTES_SH(1)|FLAVOR_SH(1),                 ANYSPACE,  Unroll1ByteReversed},
+
+    { CHANNELS_SH(2)|BYTES_SH(1),                              ANYSPACE,  Unroll2Bytes},
+    { CHANNELS_SH(2)|BYTES_SH(1)|SWAPFIRST_SH(1),              ANYSPACE,  Unroll2ByteSwapFirst},
+
+    { TYPE_LabV2_8,                                                   0,  UnrollLabV2_8 },
+    { TYPE_ALabV2_8,                                                  0,  UnrollALabV2_8 },
+    { TYPE_LabV2_16,                                                  0,  UnrollLabV2_16 },
+
+    { CHANNELS_SH(3)|BYTES_SH(1),                              ANYSPACE,  Unroll3Bytes},
+    { CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1),                 ANYSPACE,  Unroll3BytesSwap},
+    { CHANNELS_SH(3)|EXTRA_SH(1)|BYTES_SH(1)|DOSWAP_SH(1),     ANYSPACE,  Unroll3BytesSkip1Swap},
+    { CHANNELS_SH(3)|EXTRA_SH(1)|BYTES_SH(1)|SWAPFIRST_SH(1),  ANYSPACE,  Unroll3BytesSkip1SwapFirst},
+
+    { CHANNELS_SH(4)|BYTES_SH(1),                              ANYSPACE,  Unroll4Bytes},
+    { CHANNELS_SH(4)|BYTES_SH(1)|FLAVOR_SH(1),                 ANYSPACE,  Unroll4BytesReverse},
+    { CHANNELS_SH(4)|BYTES_SH(1)|SWAPFIRST_SH(1),              ANYSPACE,  Unroll4BytesSwapFirst},
+    { CHANNELS_SH(4)|BYTES_SH(1)|DOSWAP_SH(1),                 ANYSPACE,  Unroll4BytesSwap},
+    { CHANNELS_SH(4)|BYTES_SH(1)|DOSWAP_SH(1)|SWAPFIRST_SH(1), ANYSPACE,  Unroll4BytesSwapSwapFirst},
+
+    { BYTES_SH(1)|PLANAR_SH(1),    ANYFLAVOR|ANYSWAP|ANYEXTRA|ANYCHANNELS|ANYSPACE, UnrollPlanarBytes},
+    { BYTES_SH(1),    ANYFLAVOR|ANYSWAPFIRST|ANYSWAP|ANYEXTRA|ANYCHANNELS|ANYSPACE, UnrollChunkyBytes},
+
+
+    { CHANNELS_SH(1)|BYTES_SH(2),                              ANYSPACE,  Unroll1Word},
+    { CHANNELS_SH(1)|BYTES_SH(2)|FLAVOR_SH(1),                 ANYSPACE,  Unroll1WordReversed},
+    { CHANNELS_SH(1)|BYTES_SH(2)|EXTRA_SH(3),                  ANYSPACE,  Unroll1WordSkip3},
+
+    { CHANNELS_SH(2)|BYTES_SH(2),                              ANYSPACE,  Unroll2Words},
+    { CHANNELS_SH(2)|BYTES_SH(2)|SWAPFIRST_SH(1),              ANYSPACE,  Unroll2WordSwapFirst},
+
+    { CHANNELS_SH(3)|BYTES_SH(2),                              ANYSPACE,  Unroll3Words},
+    { CHANNELS_SH(4)|BYTES_SH(2),                              ANYSPACE,  Unroll4Words},
+
+    { CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1),                 ANYSPACE,  Unroll3WordsSwap},
+    { CHANNELS_SH(3)|BYTES_SH(2)|EXTRA_SH(1)|SWAPFIRST_SH(1),  ANYSPACE,  Unroll3WordsSkip1SwapFirst},
+    { CHANNELS_SH(3)|BYTES_SH(2)|EXTRA_SH(1)|DOSWAP_SH(1),     ANYSPACE,  Unroll3WordsSkip1Swap},
+    { CHANNELS_SH(4)|BYTES_SH(2)|FLAVOR_SH(1),                 ANYSPACE,  Unroll4WordsReverse},
+    { CHANNELS_SH(4)|BYTES_SH(2)|SWAPFIRST_SH(1),              ANYSPACE,  Unroll4WordsSwapFirst},
+    { CHANNELS_SH(4)|BYTES_SH(2)|DOSWAP_SH(1),                 ANYSPACE,  Unroll4WordsSwap},
+    { CHANNELS_SH(4)|BYTES_SH(2)|DOSWAP_SH(1)|SWAPFIRST_SH(1), ANYSPACE,  Unroll4WordsSwapSwapFirst},
+
+
+    { BYTES_SH(2)|PLANAR_SH(1),  ANYFLAVOR|ANYSWAP|ANYENDIAN|ANYEXTRA|ANYCHANNELS|ANYSPACE,  UnrollPlanarWords },
+    { BYTES_SH(2),  ANYFLAVOR|ANYSWAPFIRST|ANYSWAP|ANYENDIAN|ANYEXTRA|ANYCHANNELS|ANYSPACE,  UnrollAnyWords},
+};
+
+
+
+static cmsFormattersFloat InputFormattersFloat[] = {
+
+    //    Type                                          Mask                  Function
+    //  ----------------------------   ------------------------------------  ----------------------------
+    {     TYPE_Lab_DBL,                                                    ANYPLANAR,   UnrollLabDoubleToFloat},
+    {     TYPE_Lab_FLT,                                                    ANYPLANAR,   UnrollLabFloatToFloat},
+    {     TYPE_XYZ_DBL,                                                    ANYPLANAR,   UnrollXYZDoubleToFloat},
+    {     TYPE_XYZ_FLT,                                                    ANYPLANAR,   UnrollXYZFloatToFloat},
+
+    {     FLOAT_SH(1)|BYTES_SH(4),           ANYPLANAR|ANYEXTRA|ANYCHANNELS|ANYSPACE,   UnrollFloatsToFloat},
+    {     FLOAT_SH(1)|BYTES_SH(0),           ANYPLANAR|ANYEXTRA|ANYCHANNELS|ANYSPACE,   UnrollDoublesToFloat},
+};
+
+
+// Bit fields set to one in the mask are not compared
+static
+cmsFormatter _cmsGetStockInputFormatter(cmsUInt32Number dwInput, cmsUInt32Number dwFlags)
 {
-       _cmsFIXFN ToOutput = NULL;
-
-
-       if (T_BYTES(dwOutput) == 0) {
-
-           switch (T_COLORSPACE(dwOutput)) {
-
-           case PT_Lab:
-                    ToOutput = PackLabDouble;
-                    break;
-           case PT_XYZ:
-                    ToOutput = PackXYZDouble;
-                    break;
-
-           // 0.0 .. 1.0 range
-           case PT_GRAY:
-           case PT_RGB:
-           case PT_YCbCr:
-           case PT_YUV:
-           case PT_YUVK:
-           case PT_HSV:
-           case PT_HLS:
-           case PT_Yxy:
-                    ToOutput = PackDouble;
-                    break;
-
-            // Inks (%) 0.0 .. 100.0
-
-           default:
-                    ToOutput = PackInkDouble;
-                    break;
-           }
-
-       }
-       else
-
-       if (T_PLANAR(dwOutput)) {
-
-       switch (T_BYTES(dwOutput)) {
-
-              case 1: ToOutput = PackPlanarBytes;
-                      break;
-
-              case 2:if (!T_ENDIAN16(dwOutput))
-                            ToOutput = PackPlanarWords;
-                      break;
-
-              default:;
-       }
-       }
-       else {
-
-              switch (T_BYTES(dwOutput)) {
-
-              case 1:
-                     switch (T_CHANNELS(dwOutput))
-                     {
-                     case 1:
-                            if (T_DITHER(dwOutput))
-                                    ToOutput = PackNBytesDither;
-                            else
-                            ToOutput = Pack1Byte;
-                            if (T_EXTRA(dwOutput) == 1) {
-                                if (T_SWAPFIRST(dwOutput))
-                                   ToOutput = Pack1ByteAndSkip1SwapFirst;
-                                else
-                                   ToOutput = Pack1ByteAndSkip1;
-                            }
-                            break;
-
-                     case 3:
-                         switch (T_EXTRA(dwOutput)) {
-
-                         case 0: if (T_DOSWAP(dwOutput))
-                                   ToOutput = Pack3BytesSwap;
-                                 else
-                                     if (T_COLORSPACE(dwOutput) == PT_Lab)
-                                        ToOutput = Pack3BytesLab;
-                                     else {
-                                         if (T_DITHER(dwOutput))
-                                                 ToOutput = PackNBytesDither;
-                                     else
-                                        ToOutput = Pack3Bytes;
-                                     }
-                             break;
-
-                         case 1:    // TODO: ALab8 should be handled here
-
-                                    if (T_DOSWAP(dwOutput)) {
-
-                                    if (T_SWAPFIRST(dwOutput))
-                                        ToOutput = Pack3BytesAndSkip1SwapSwapFirst;
-                                    else
-                                        ToOutput = Pack3BytesAndSkip1Swap;
-                                 }
-                             else {
-                                   if (T_SWAPFIRST(dwOutput))
-                                    ToOutput = Pack3BytesAndSkip1SwapFirst;
-                                   else
-                                    ToOutput = Pack3BytesAndSkip1;
-                             }
-                             break;
-
-                         default:;
-                         }
-                         break;
-
-                     case 4: if (T_EXTRA(dwOutput) == 0) {
-
-
-                                if (T_DOSWAP(dwOutput)) {
-
-
-                                     if (T_SWAPFIRST(dwOutput)) {
-                                         ToOutput = Pack4BytesSwapSwapFirst;
-                                     }
-                                     else {
-
-                                           if (T_DITHER(dwOutput)) {
-                                                  ToOutput = PackNBytesSwapDither;
-                                           }
-                                           else {
-                                         ToOutput = Pack4BytesSwap;
-                                 }
-                                     }
-                                 }
-                                 else {
-                                     if (T_SWAPFIRST(dwOutput))
-                                         ToOutput = Pack4BytesSwapFirst;
-                                     else {
-
-                                         if (T_FLAVOR(dwOutput))
-                                             ToOutput = Pack4BytesReverse;
-                                         else {
-                                             if (T_DITHER(dwOutput))
-                                                 ToOutput = PackNBytesDither;
-                                         else
-                                             ToOutput = Pack4Bytes;
-                                     }
-                                 }
-                             }
-                             }
-                            else {
-                                    if (!T_DOSWAP(dwOutput) && !T_SWAPFIRST(dwOutput))
-                                             ToOutput = PackNBytes;
-                            }
-                            break;
-
-                     // Hexachrome separations.
-                     case 6: if (T_EXTRA(dwOutput) == 0) {
-
-                                    if( T_DOSWAP(dwOutput))
-                                            ToOutput = Pack6BytesSwap;
-                            else
-                                   ToOutput = Pack6Bytes;
-                            }
-                            else {
-                                    if (!T_DOSWAP(dwOutput) && !T_SWAPFIRST(dwOutput))
-                                             ToOutput = PackNBytes;
-
-                            }
-                            break;
-
-                     case 2:
-                     case 5:
-                     case 7:
-                     case 8:
-                     case 9:
-                     case 10:
-                     case 11:
-                     case 12:
-                     case 13:
-                     case 14:
-                     case 15:
-
-                            if ((T_EXTRA(dwOutput) == 0) && (T_SWAPFIRST(dwOutput) == 0))
-                            {
-                                   if (T_DOSWAP(dwOutput))
-                                          ToOutput = PackNBytesSwap;
-                                   else {
-
-                                       if (T_DITHER(dwOutput))
-                                                 ToOutput = PackNBytesDither;
-                                   else
-                                          ToOutput = PackNBytes;
-                                   }
-                            }
-                            break;
-
-                     default:;
-                     }
-                     break;
-
-
-              case 2:
-
-                     switch (T_CHANNELS(dwOutput)) {
-
-                     case 1:
-                            if (T_ENDIAN16(dwOutput))
-
-                                   ToOutput = Pack1WordBigEndian;
-                            else
-                                   ToOutput = Pack1Word;
-
-                            if (T_EXTRA(dwOutput) == 1) {
-
-                               if (T_ENDIAN16(dwOutput))
-
-                                   ToOutput = Pack1WordAndSkip1BigEndian;
-                               else {
-                                   if (T_SWAPFIRST(dwOutput))
-                                      ToOutput = Pack1WordAndSkip1SwapFirst;
-                                   else
-                                      ToOutput = Pack1WordAndSkip1;
-                               }
-                            }
-                            break;
-
-                     case 3:
-
-                         switch (T_EXTRA(dwOutput)) {
-
-                         case 0:
-                               if (T_DOSWAP(dwOutput)) {
-
-                                   if (T_ENDIAN16(dwOutput))
-
-                                          ToOutput = Pack3WordsSwapBigEndian;
-                                   else
-                                          ToOutput = Pack3WordsSwap;
-                               }
-                               else {
-                                   if (T_ENDIAN16(dwOutput))
-
-                                      ToOutput = Pack3WordsBigEndian;
-                                   else
-                                      ToOutput = Pack3Words;
-                                   }
-                             break;
-
-                         case 1: if (T_DOSWAP(dwOutput)) {
-
-                                   if (T_ENDIAN16(dwOutput))
-
-                                          ToOutput = Pack3WordsAndSkip1SwapBigEndian;
-                                   else {
-                                       if (T_SWAPFIRST(dwOutput))
-                                          ToOutput = Pack3WordsAndSkip1SwapSwapFirst;
-                                       else
-                                          ToOutput = Pack3WordsAndSkip1Swap;
-                                   }
-                             }
-                             else  {
-                                   if (T_ENDIAN16(dwOutput))
-                                          ToOutput = Pack3WordsAndSkip1BigEndian;
-                                   else
-                                          ToOutput = Pack3WordsAndSkip1;
-                                   }
-                         default:;
-                         }
-                         break;
-
-                     case 4: if (T_EXTRA(dwOutput) == 0) {
-
-                                   if (T_DOSWAP(dwOutput)) {
-
-                                           if (T_ENDIAN16(dwOutput))
-                                                 ToOutput = Pack4WordsSwapBigEndian;
-                                           else
-                                                 ToOutput = Pack4WordsSwap;
-                                   }
-                                   else {
-
-                                       if (T_ENDIAN16(dwOutput)) {
-
-                                           if (T_FLAVOR(dwOutput))
-                                                ToOutput = Pack4WordsBigEndianReverse;
-                                           else
-                                                ToOutput = Pack4WordsBigEndian;
-                                       }
-                                       else {
-                                          if (T_FLAVOR(dwOutput))
-                                              ToOutput = Pack4WordsReverse;
-                                          else
-                                               ToOutput = Pack4Words;
-                                        }
-                                   }
-                            }
-                            else {
-                                    if (!T_DOSWAP(dwOutput) && !T_SWAPFIRST(dwOutput))
-                                             ToOutput = PackNWords;
-                            }
-                            break;
-
-                     case 6: if (T_EXTRA(dwOutput) == 0) {
-
-                                   if (T_DOSWAP(dwOutput)) {
-
-                                          if (T_ENDIAN16(dwOutput))
-                                                 ToOutput = Pack6WordsSwapBigEndian;
-                                          else
-                                                 ToOutput = Pack6WordsSwap;
-                                   }
-                                   else {
-
-                                   if (T_ENDIAN16(dwOutput))
-                                          ToOutput = Pack6WordsBigEndian;
-                                   else
-                                          ToOutput = Pack6Words;
-                                   }
-                             }
-                            else {
-                                    if (!T_DOSWAP(dwOutput) && !T_SWAPFIRST(dwOutput))
-                                             ToOutput = PackNWords;
-                            }
-                            break;
-
-
-                     case 2:
-                     case 5:
-                     case 7:
-                     case 8:
-                     case 9:
-                     case 10:
-                     case 11:
-                     case 12:
-                     case 13:
-                     case 14:
-                     case 15: if ((T_EXTRA(dwOutput) == 0) && (T_SWAPFIRST(dwOutput) == 0)) {
-
-                                   if (T_DOSWAP(dwOutput)) {
-
-                                          if (T_ENDIAN16(dwOutput))
-                                                 ToOutput = PackNWordsSwapBigEndian;
-                                          else
-                                                 ToOutput = PackNWordsSwap;
-                                   }
-                                   else {
-
-                                          if (T_ENDIAN16(dwOutput))
-                                                 ToOutput = PackNWordsBigEndian;
-                                          else
-                                                 ToOutput = PackNWords;
-                                          }
-                             }
-                             break;
-
-                     default:;
-                     }
-                     break;
-
-              default:;
-              }
-              }
-
-              if (!ToOutput)
-                     cmsSignalError(LCMS_ERRC_ABORTED, "Unknown output format");
-
-              return ToOutput;
+    cmsUInt32Number i;
+    cmsFormatter fr;
+
+
+    if (!(dwFlags & CMS_PACK_FLAGS_FLOAT)) {
+
+        for (i=0; i < sizeof(InputFormatters16) / sizeof(cmsFormatters16); i++) {
+            cmsFormatters16* f = InputFormatters16 + i;
+
+            if ((dwInput & ~f ->Mask) == f ->Type) {
+                fr.Fmt16 = f ->Frm;
+                return fr;
+            }
+        }
+    }
+    else {
+        for (i=0; i < sizeof(InputFormattersFloat) / sizeof(cmsFormattersFloat); i++) {
+            cmsFormattersFloat* f = InputFormattersFloat + i;
+
+            if ((dwInput & ~f ->Mask) == f ->Type) {
+                fr.FmtFloat = f ->Frm;
+                return fr;
+            }
+        }
+    }
+
+    fr.Fmt16 = NULL;
+    return fr;
 }
 
-// User formatters for (weird) cases not already included
-
-void LCMSEXPORT cmsSetUserFormatters(cmsHTRANSFORM hTransform, DWORD dwInput,  cmsFORMATTER Input,
-                                                               DWORD dwOutput, cmsFORMATTER Output)
-{
-    _LPcmsTRANSFORM xform = (_LPcmsTRANSFORM) (LPSTR) hTransform;
-
-    if (Input != NULL) {
-        xform ->FromInput = (_cmsFIXFN) Input;
-        xform ->InputFormat = dwInput;
-    }
-
-    if (Output != NULL) {
-        xform ->ToOutput  = (_cmsFIXFN) Output;
-        xform ->OutputFormat = dwOutput;
-    }
-
-}
-
-void LCMSEXPORT cmsGetUserFormatters(cmsHTRANSFORM hTransform,
-                                     LPDWORD InputFormat, cmsFORMATTER* Input,
-                                     LPDWORD OutputFormat, cmsFORMATTER* Output)
+static cmsFormatters16 OutputFormatters16[] = {
+    //    Type                                          Mask                  Function
+    //  ----------------------------   ------------------------------------  ----------------------------
+
+    { TYPE_Lab_DBL,                                               ANYPLANAR,  PackLabDoubleFrom16},
+    { TYPE_XYZ_DBL,                                               ANYPLANAR,  PackXYZDoubleFrom16},
+    { FLOAT_SH(1)|BYTES_SH(0),      ANYCHANNELS|ANYPLANAR|ANYEXTRA|ANYSPACE,  PackDoubleFrom16},
+    { FLOAT_SH(1)|BYTES_SH(4),      ANYCHANNELS|ANYPLANAR|ANYEXTRA|ANYSPACE,  PackFloatFrom16},
+
+    { CHANNELS_SH(1)|BYTES_SH(1),                                  ANYSPACE,  Pack1Byte},
+    { CHANNELS_SH(1)|BYTES_SH(1)|EXTRA_SH(1),                      ANYSPACE,  Pack1ByteSkip1},
+    { CHANNELS_SH(1)|BYTES_SH(1)|EXTRA_SH(1)|SWAPFIRST_SH(1),      ANYSPACE,  Pack1ByteSkip1SwapFirst},
+
+    { CHANNELS_SH(1)|BYTES_SH(1)|FLAVOR_SH(1),                     ANYSPACE,  Pack1ByteReversed},
+
+    { TYPE_LabV2_8,                                                       0,  PackLabV2_8 },
+    { TYPE_ALabV2_8,                                                      0,  PackALabV2_8 },
+    { TYPE_LabV2_16,                                                      0,  PackLabV2_16 },
+
+    { CHANNELS_SH(3)|BYTES_SH(1)|OPTIMIZED_SH(1),                  ANYSPACE,  Pack3BytesOptimized},
+    { CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)|OPTIMIZED_SH(1),      ANYSPACE,  Pack3BytesAndSkip1Optimized},
+    { CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)|SWAPFIRST_SH(1)|OPTIMIZED_SH(1),
+                                                                   ANYSPACE,  Pack3BytesAndSkip1SwapFirstOptimized},
+    { CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)|DOSWAP_SH(1)|SWAPFIRST_SH(1)|OPTIMIZED_SH(1),
+                                                                   ANYSPACE,  Pack3BytesAndSkip1SwapSwapFirstOptimized},
+    { CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1)|EXTRA_SH(1)|OPTIMIZED_SH(1),
+                                                                   ANYSPACE,  Pack3BytesAndSkip1SwapOptimized},
+    { CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1)|OPTIMIZED_SH(1),     ANYSPACE,  Pack3BytesSwapOptimized},
+
+
+
+    { CHANNELS_SH(3)|BYTES_SH(1),                                  ANYSPACE,  Pack3Bytes},
+    { CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1),                      ANYSPACE,  Pack3BytesAndSkip1},
+    { CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)|SWAPFIRST_SH(1),      ANYSPACE,  Pack3BytesAndSkip1SwapFirst},
+    { CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)|DOSWAP_SH(1)|SWAPFIRST_SH(1),
+                                                                   ANYSPACE,  Pack3BytesAndSkip1SwapSwapFirst},
+    { CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1)|EXTRA_SH(1),         ANYSPACE,  Pack3BytesAndSkip1Swap},
+    { CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1),                     ANYSPACE,  Pack3BytesSwap},
+    { CHANNELS_SH(6)|BYTES_SH(1),                                  ANYSPACE,  Pack6Bytes},
+    { CHANNELS_SH(6)|BYTES_SH(1)|DOSWAP_SH(1),                     ANYSPACE,  Pack6BytesSwap},
+    { CHANNELS_SH(4)|BYTES_SH(1),                                  ANYSPACE,  Pack4Bytes},
+    { CHANNELS_SH(4)|BYTES_SH(1)|FLAVOR_SH(1),                     ANYSPACE,  Pack4BytesReverse},
+    { CHANNELS_SH(4)|BYTES_SH(1)|SWAPFIRST_SH(1),                  ANYSPACE,  Pack4BytesSwapFirst},
+    { CHANNELS_SH(4)|BYTES_SH(1)|DOSWAP_SH(1),                     ANYSPACE,  Pack4BytesSwap},
+    { CHANNELS_SH(4)|BYTES_SH(1)|DOSWAP_SH(1)|SWAPFIRST_SH(1),     ANYSPACE,  Pack4BytesSwapSwapFirst},
+
+    { BYTES_SH(1),                 ANYFLAVOR|ANYSWAPFIRST|ANYSWAP|ANYEXTRA|ANYCHANNELS|ANYSPACE, PackAnyBytes},
+    { BYTES_SH(1)|PLANAR_SH(1),    ANYFLAVOR|ANYSWAP|ANYEXTRA|ANYCHANNELS|ANYSPACE, PackPlanarBytes},
+
+    { CHANNELS_SH(1)|BYTES_SH(2),                                  ANYSPACE,  Pack1Word},
+    { CHANNELS_SH(1)|BYTES_SH(2)|EXTRA_SH(1),                      ANYSPACE,  Pack1WordSkip1},
+    { CHANNELS_SH(1)|BYTES_SH(2)|EXTRA_SH(1)|SWAPFIRST_SH(1),      ANYSPACE,  Pack1WordSkip1SwapFirst},
+    { CHANNELS_SH(1)|BYTES_SH(2)|FLAVOR_SH(1),                     ANYSPACE,  Pack1WordReversed},
+    { CHANNELS_SH(1)|BYTES_SH(2)|ENDIAN16_SH(1),                   ANYSPACE,  Pack1WordBigEndian},
+    { CHANNELS_SH(3)|BYTES_SH(2),                                  ANYSPACE,  Pack3Words},
+    { CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1),                     ANYSPACE,  Pack3WordsSwap},
+    { CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1),                   ANYSPACE,  Pack3WordsBigEndian},
+    { CHANNELS_SH(3)|BYTES_SH(2)|EXTRA_SH(1),                      ANYSPACE,  Pack3WordsAndSkip1},
+    { CHANNELS_SH(3)|BYTES_SH(2)|EXTRA_SH(1)|DOSWAP_SH(1),         ANYSPACE,  Pack3WordsAndSkip1Swap},
+    { CHANNELS_SH(3)|BYTES_SH(2)|EXTRA_SH(1)|SWAPFIRST_SH(1),      ANYSPACE,  Pack3WordsAndSkip1SwapFirst},
+
+    { CHANNELS_SH(3)|BYTES_SH(2)|EXTRA_SH(1)|DOSWAP_SH(1)|SWAPFIRST_SH(1),
+                                                                   ANYSPACE,  Pack3WordsAndSkip1SwapSwapFirst},
+
+    { CHANNELS_SH(4)|BYTES_SH(2),                                  ANYSPACE,  Pack4Words},
+    { CHANNELS_SH(4)|BYTES_SH(2)|FLAVOR_SH(1),                     ANYSPACE,  Pack4WordsReverse},
+    { CHANNELS_SH(4)|BYTES_SH(2)|DOSWAP_SH(1),                     ANYSPACE,  Pack4WordsSwap},
+    { CHANNELS_SH(4)|BYTES_SH(2)|ENDIAN16_SH(1),                   ANYSPACE,  Pack4WordsBigEndian},
+
+    { CHANNELS_SH(6)|BYTES_SH(2),                                  ANYSPACE,  Pack6Words},
+    { CHANNELS_SH(6)|BYTES_SH(2)|DOSWAP_SH(1),                     ANYSPACE,  Pack6WordsSwap},
+
+    { BYTES_SH(2)|PLANAR_SH(1),     ANYFLAVOR|ANYENDIAN|ANYSWAP|ANYEXTRA|ANYCHANNELS|ANYSPACE, PackPlanarWords},
+    { BYTES_SH(2),                  ANYFLAVOR|ANYSWAPFIRST|ANYSWAP|ANYENDIAN|ANYEXTRA|ANYCHANNELS|ANYSPACE, PackAnyWords}
+
+};
+
+
+static cmsFormattersFloat OutputFormattersFloat[] = {
+    //    Type                                          Mask                                 Function
+    //  ----------------------------   ---------------------------------------------------  ----------------------------
+    {     TYPE_Lab_FLT,                                                         ANYPLANAR,   PackLabFloatFromFloat},
+    {     TYPE_XYZ_FLT,                                                         ANYPLANAR,   PackXYZFloatFromFloat},
+    {     TYPE_Lab_DBL,                                                         ANYPLANAR,   PackLabDoubleFromFloat},
+    {     TYPE_XYZ_DBL,                                                         ANYPLANAR,   PackXYZDoubleFromFloat},
+    {     FLOAT_SH(1)|BYTES_SH(4),
+          ANYFLAVOR|ANYSWAPFIRST|ANYSWAP|ANYEXTRA|ANYCHANNELS|ANYSPACE,   PackChunkyFloatsFromFloat },
+    {     FLOAT_SH(1)|BYTES_SH(4)|PLANAR_SH(1),             ANYEXTRA|ANYCHANNELS|ANYSPACE,   PackPlanarFloatsFromFloat},
+    {     FLOAT_SH(1)|BYTES_SH(0),
+          ANYFLAVOR|ANYSWAPFIRST|ANYSWAP|ANYEXTRA|ANYCHANNELS|ANYSPACE,   PackChunkyDoublesFromFloat },
+    {     FLOAT_SH(1)|BYTES_SH(0)|PLANAR_SH(1),             ANYEXTRA|ANYCHANNELS|ANYSPACE,   PackPlanarDoublesFromFloat},
+
+
+};
+
+
+// Bit fields set to one in the mask are not compared
+cmsFormatter _cmsGetStockOutputFormatter(cmsUInt32Number dwInput, cmsUInt32Number dwFlags)
 {
-    _LPcmsTRANSFORM xform = (_LPcmsTRANSFORM) (LPSTR) hTransform;
-
-    if (Input)        *Input =  (cmsFORMATTER) xform ->FromInput;
-    if (InputFormat)  *InputFormat = xform -> InputFormat;
-    if (Output)       *Output = (cmsFORMATTER) xform ->ToOutput;
-    if (OutputFormat) *OutputFormat = xform -> OutputFormat;
+    cmsUInt32Number i;
+    cmsFormatter fr;
+
+
+    if (dwFlags & CMS_PACK_FLAGS_FLOAT) {
+
+        for (i=0; i < sizeof(OutputFormattersFloat) / sizeof(cmsFormattersFloat); i++) {
+            cmsFormattersFloat* f = OutputFormattersFloat + i;
+
+            if ((dwInput & ~f ->Mask) == f ->Type) {
+                fr.FmtFloat = f ->Frm;
+                return fr;
+            }
+        }
+
+    }
+    else {
+
+        for (i=0; i < sizeof(OutputFormatters16) / sizeof(cmsFormatters16); i++) {
+            cmsFormatters16* f = OutputFormatters16 + i;
+
+            if ((dwInput & ~f ->Mask) == f ->Type) {
+                fr.Fmt16 = f ->Frm;
+                return fr;
+            }
+        }
+    }
+
+    fr.Fmt16 = NULL;
+    return fr;
 }
 
 
-// Change format of yet existing transform. No colorspace checking is performed
-
-void LCMSEXPORT cmsChangeBuffersFormat(cmsHTRANSFORM hTransform,
-                                        DWORD dwInputFormat,
-                                        DWORD dwOutputFormat)
+typedef struct _cms_formatters_factory_list {
+
+    cmsFormatterFactory Factory;
+    struct _cms_formatters_factory_list *Next;
+
+} cmsFormattersFactoryList;
+
+static cmsFormattersFactoryList* FactoryList = NULL;
+
+
+// Formatters management
+cmsBool  _cmsRegisterFormattersPlugin(cmsPluginBase* Data)
+{
+    cmsPluginFormatters* Plugin = (cmsPluginFormatters*) Data;
+    cmsFormattersFactoryList* fl ;
+
+    // Reset
+    if (Data == NULL) {
+
+        FactoryList = NULL;
+        return TRUE;
+    }
+
+    fl = (cmsFormattersFactoryList*) _cmsPluginMalloc(sizeof(cmsFormattersFactoryList));
+    if (fl == NULL) return FALSE;
+
+    fl ->Factory    = Plugin ->FormattersFactory;
+
+    fl ->Next = FactoryList;
+    FactoryList = fl;
+
+    return TRUE;
+}
+
+cmsFormatter _cmsGetFormatter(cmsUInt32Number Type,         // Specific type, i.e. TYPE_RGB_8
+                             cmsFormatterDirection Dir,
+                             cmsUInt32Number dwFlags)       // Float or 16 bits
 {
-
-    cmsSetUserFormatters(hTransform,
-                        dwInputFormat,
-                        (cmsFORMATTER) _cmsIdentifyInputFormat((_LPcmsTRANSFORM) hTransform, dwInputFormat),
-                        dwOutputFormat,
-                        (cmsFORMATTER) _cmsIdentifyOutputFormat((_LPcmsTRANSFORM) hTransform, dwOutputFormat));
+    cmsFormattersFactoryList* f;
+
+    for (f = FactoryList; f != NULL; f = f ->Next) {
+
+        cmsFormatter fn = f ->Factory(Type, Dir, dwFlags);
+        if (fn.Fmt16 != NULL) return fn;
+    }
+
+    // Revert to default
+    if (Dir == cmsFormatterInput)
+        return _cmsGetStockInputFormatter(Type, dwFlags);
+    else
+        return _cmsGetStockOutputFormatter(Type, dwFlags);
+}
+
+
+// Return whatever given formatter refers to float values
+cmsBool  _cmsFormatterIsFloat(cmsUInt32Number Type)
+{
+    return T_FLOAT(Type) ? TRUE : FALSE;
 }
+
+// Return whatever given formatter refers to 8 bits
+cmsBool  _cmsFormatterIs8bit(cmsUInt32Number Type)
+{
+    int Bytes = T_BYTES(Type);
+
+    return (Bytes == 1);
+}
+
+// Build a suitable formatter for the colorspace of this profile
+cmsUInt32Number CMSEXPORT cmsFormatterForColorspaceOfProfile(cmsHPROFILE hProfile, cmsUInt32Number nBytes, cmsBool lIsFloat)
+{
+
+    cmsColorSpaceSignature ColorSpace      = cmsGetColorSpace(hProfile);
+    cmsUInt32Number        ColorSpaceBits  = _cmsLCMScolorSpace(ColorSpace);
+    cmsUInt32Number        nOutputChans    = cmsChannelsOf(ColorSpace);
+    cmsUInt32Number        Float           = lIsFloat ? 1 : 0;
+
+    // Create a fake formatter for result
+    return FLOAT_SH(Float) | COLORSPACE_SH(ColorSpaceBits) | BYTES_SH(nBytes) | CHANNELS_SH(nOutputChans);
+}
+
+// Build a suitable formatter for the colorspace of this profile
+cmsUInt32Number CMSEXPORT cmsFormatterForPCSOfProfile(cmsHPROFILE hProfile, cmsUInt32Number nBytes, cmsBool lIsFloat)
+{
+
+    cmsColorSpaceSignature ColorSpace      = cmsGetPCS(hProfile);
+    int                    ColorSpaceBits  = _cmsLCMScolorSpace(ColorSpace);
+    cmsUInt32Number        nOutputChans    = cmsChannelsOf(ColorSpace);
+    cmsUInt32Number        Float           = lIsFloat ? 1 : 0;
+
+    // Create a fake formatter for result
+    return FLOAT_SH(Float) | COLORSPACE_SH(ColorSpaceBits) | BYTES_SH(nBytes) | CHANNELS_SH(nOutputChans);
+}
--- a/src/share/native/sun/java2d/cmm/lcms/cmspcs.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmspcs.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,11 +49,13 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
 
 //      inter PCS conversions XYZ <-> CIE L* a* b*
-
-#include "lcms.h"
-
 /*
 
 
@@ -75,7 +78,7 @@
 
 
 
-       Following ICC. PCS in Lab is coded as:
+       PCS in Lab2 is encoded as:
 
               8 bit Lab PCS:
 
@@ -90,9 +93,6 @@
                      b*
 
 
-       We are always playing with 16 bits-data, so I will ignore the
-       8-bits encoding scheme.
-
 
 Interchange Space   Component     Actual Range        Encoded Range
 CIE XYZ             X             0 -> 1.99997        0x0000 -> 0xffff
@@ -116,318 +116,134 @@
 
 */
 
+// Conversions
+void CMSEXPORT cmsXYZ2xyY(cmsCIExyY* Dest, const cmsCIEXYZ* Source)
+{
+    cmsFloat64Number ISum;
 
-
+    ISum = 1./(Source -> X + Source -> Y + Source -> Z);
 
-// On most modern computers, D > 4 M (i.e. a division takes more than 4
-// multiplications worth of time), so it is probably preferable to compute
-// a 24 bit result directly.
+    Dest -> x = (Source -> X) * ISum;
+    Dest -> y = (Source -> Y) * ISum;
+    Dest -> Y = Source -> Y;
+}
 
-// #define ITERATE 1
+void CMSEXPORT cmsxyY2XYZ(cmsCIEXYZ* Dest, const cmsCIExyY* Source)
+{
+    Dest -> X = (Source -> x / Source -> y) * Source -> Y;
+    Dest -> Y = Source -> Y;
+    Dest -> Z = ((1 - Source -> x - Source -> y) / Source -> y) * Source -> Y;
+}
 
 static
-float CubeRoot(float x)
+cmsFloat64Number f(cmsFloat64Number t)
 {
-       float fr, r;
-       int ex, shx;
-
-       /* Argument reduction */
-       fr = (float) frexp(x, &ex); /* separate into mantissa and exponent */
-       shx = ex % 3;
-
-       if (shx > 0)
-              shx -= 3; /* compute shx such that (ex - shx) is divisible by 3 */
-
-       ex = (ex - shx) / 3;        /* exponent of cube root */
-       fr = (float) ldexp(fr, shx);
-
-       /* 0.125 <= fr < 1.0 */
-
-#ifdef ITERATE
-       /* Compute seed with a quadratic approximation */
-
-       fr = (-0.46946116F * fr + 1.072302F) * fr + 0.3812513F;/* 0.5<=fr<1 */
-       r = ldexp(fr, ex);          /* 6 bits of precision */
+    const cmsFloat64Number Limit = (24.0/116.0) * (24.0/116.0) * (24.0/116.0);
 
-       /* Newton-Raphson iterations */
-
-       r = (float)(2.0/3.0) * r + (float)(1.0/3.0) * x / (r * r); /* 12 bits */
-       r = (float)(2.0/3.0) * r + (float)(1.0/3.0) * x / (r * r); /* 24 bits */
-#else /* ITERATE */
-
-       /* Use quartic rational polynomial with error < 2^(-24) */
-
-       fr = (float) (((((45.2548339756803022511987494 * fr +
-       192.2798368355061050458134625) * fr +
-       119.1654824285581628956914143) * fr +
-       13.43250139086239872172837314) * fr +
-       0.1636161226585754240958355063)
-       /
-       ((((14.80884093219134573786480845 * fr +
-       151.9714051044435648658557668) * fr +
-       168.5254414101568283957668343) * fr +
-       33.9905941350215598754191872) * fr +
-       1.0));
-       r = (float) ldexp(fr, ex); /* 24 bits of precision */
-#endif
-       return r;
+    if (t <= Limit)
+        return (841.0/108.0) * t + (16.0/116.0);
+    else
+        return pow(t, 1.0/3.0);
 }
 
 static
-double f(double t)
+cmsFloat64Number f_1(cmsFloat64Number t)
+{
+    const cmsFloat64Number Limit = (24.0/116.0);
+
+    if (t <= Limit) {
+        return (108.0/841.0) * (t - (16.0/116.0));
+    }
+
+    return t * t * t;
+}
+
+
+// Standard XYZ to Lab. it can handle negative XZY numbers in some cases
+void CMSEXPORT cmsXYZ2Lab(const cmsCIEXYZ* WhitePoint, cmsCIELab* Lab, const cmsCIEXYZ* xyz)
 {
+    cmsFloat64Number fx, fy, fz;
 
-      const double Limit = (24.0/116.0) * (24.0/116.0) * (24.0/116.0);
+    if (WhitePoint == NULL)
+        WhitePoint = cmsD50_XYZ();
+
+    fx = f(xyz->X / WhitePoint->X);
+    fy = f(xyz->Y / WhitePoint->Y);
+    fz = f(xyz->Z / WhitePoint->Z);
+
+    Lab->L = 116.0*fy - 16.0;
+    Lab->a = 500.0*(fx - fy);
+    Lab->b = 200.0*(fy - fz);
+}
+
+
+// Standard XYZ to Lab. It can return negative XYZ in some cases
+void CMSEXPORT cmsLab2XYZ(const cmsCIEXYZ* WhitePoint, cmsCIEXYZ* xyz,  const cmsCIELab* Lab)
+{
+    cmsFloat64Number x, y, z;
 
-       if (t <= Limit)
-              return (841.0/108.0) * t + (16.0/116.0);
-       else
-              return CubeRoot((float) t);
+    if (WhitePoint == NULL)
+        WhitePoint = cmsD50_XYZ();
+
+    y = (Lab-> L + 16.0) / 116.0;
+    x = y + 0.002 * Lab -> a;
+    z = y - 0.005 * Lab -> b;
+
+    xyz -> X = f_1(x) * WhitePoint -> X;
+    xyz -> Y = f_1(y) * WhitePoint -> Y;
+    xyz -> Z = f_1(z) * WhitePoint -> Z;
+
+}
+
+static
+cmsFloat64Number L2float2(cmsUInt16Number v)
+{
+    return (cmsFloat64Number) v / 652.800;
+}
+
+// the a/b part
+static
+cmsFloat64Number ab2float2(cmsUInt16Number v)
+{
+    return ((cmsFloat64Number) v / 256.0) - 128.0;
+}
+
+static
+cmsUInt16Number L2Fix2(cmsFloat64Number L)
+{
+    return _cmsQuickSaturateWord(L *  652.8);
+}
+
+static
+cmsUInt16Number ab2Fix2(cmsFloat64Number ab)
+{
+    return _cmsQuickSaturateWord((ab + 128.0) * 256.0);
 }
 
 
 static
-double f_1(double t)
-{
-       const double Limit = (24.0/116.0);
-
-       if (t <= Limit)
-       {
-              double tmp;
-
-              tmp = (108.0/841.0) * (t - (16.0/116.0));
-              if (tmp <= 0.0) return 0.0;
-              else return tmp;
-       }
-
-       return t * t * t;
-}
-
-
-
-void LCMSEXPORT cmsXYZ2Lab(LPcmsCIEXYZ WhitePoint, LPcmsCIELab Lab, const cmsCIEXYZ* xyz)
+cmsFloat64Number L2float4(cmsUInt16Number v)
 {
-       double fx, fy, fz;
-
-       if (xyz -> X == 0 && xyz -> Y == 0 && xyz -> Z == 0)
-       {
-        Lab -> L = 0;
-        Lab -> a = 0;
-        Lab -> b = 0;
-        return;
-       }
-
-       if (WhitePoint == NULL)
-            WhitePoint = cmsD50_XYZ();
-
-       fx = f(xyz->X / WhitePoint->X);
-       fy = f(xyz->Y / WhitePoint->Y);
-       fz = f(xyz->Z / WhitePoint->Z);
-
-       Lab->L = 116.0* fy - 16.;
-
-       Lab->a = 500.0*(fx - fy);
-       Lab->b = 200.0*(fy - fz);
+    return (cmsFloat64Number) v / 655.35;
 }
 
-
-
-void cmsXYZ2LabEncoded(WORD XYZ[3], WORD Lab[3])
+// the a/b part
+static
+cmsFloat64Number ab2float4(cmsUInt16Number v)
 {
-       Fixed32 X, Y, Z;
-       double x, y, z, L, a, b;
-       double fx, fy, fz;
-       Fixed32 wL, wa, wb;
-
-       X = (Fixed32) XYZ[0] << 1;
-       Y = (Fixed32) XYZ[1] << 1;
-       Z = (Fixed32) XYZ[2] << 1;
-
-
-       if (X==0 && Y==0 && Z==0) {
-
-                     Lab[0] = 0;
-                     Lab[1] = Lab[2] =  0x8000;
-                     return;
-       }
-
-       // PCS is in D50
-
-
-       x = FIXED_TO_DOUBLE(X) / D50X;
-       y = FIXED_TO_DOUBLE(Y) / D50Y;
-       z = FIXED_TO_DOUBLE(Z) / D50Z;
-
-
-       fx = f(x);
-       fy = f(y);
-       fz = f(z);
-
-       L = 116.* fy - 16.;
-
-       a = 500.*(fx - fy);
-       b = 200.*(fy - fz);
-
-       a += 128.;
-       b += 128.;
-
-       wL = (int) (L * 652.800 + .5);
-       wa = (int) (a * 256.0   + .5);
-       wb = (int) (b * 256.0   + .5);
-
-
-       Lab[0] = Clamp_L(wL);
-       Lab[1] = Clamp_ab(wa);
-       Lab[2] = Clamp_ab(wb);
-
-
+    return ((cmsFloat64Number) v / 257.0) - 128.0;
 }
 
 
-
-
-
-
-void LCMSEXPORT cmsLab2XYZ(LPcmsCIEXYZ WhitePoint, LPcmsCIEXYZ xyz,  const cmsCIELab* Lab)
+void CMSEXPORT cmsLabEncoded2FloatV2(cmsCIELab* Lab, const cmsUInt16Number wLab[3])
 {
-        double x, y, z;
-
-        if (Lab -> L <= 0) {
-               xyz -> X = 0;
-               xyz -> Y = 0;
-               xyz -> Z = 0;
-               return;
-        }
-
-
-       if (WhitePoint == NULL)
-            WhitePoint = cmsD50_XYZ();
-
-       y = (Lab-> L + 16.0) / 116.0;
-       x = y + 0.002 * Lab -> a;
-       z = y - 0.005 * Lab -> b;
-
-       xyz -> X = f_1(x) * WhitePoint -> X;
-       xyz -> Y = f_1(y) * WhitePoint -> Y;
-       xyz -> Z = f_1(z) * WhitePoint -> Z;
-
+        Lab->L = L2float2(wLab[0]);
+        Lab->a = ab2float2(wLab[1]);
+        Lab->b = ab2float2(wLab[2]);
 }
 
 
-
-void cmsLab2XYZEncoded(WORD Lab[3], WORD XYZ[3])
-{
-       double L, a, b;
-       double X, Y, Z, x, y, z;
-
-
-       L = ((double) Lab[0] * 100.0) / 65280.0;
-       if (L==0.0) {
-
-       XYZ[0] = 0; XYZ[1] = 0; XYZ[2] = 0;
-       return;
-       }
-
-       a = ((double) Lab[1] / 256.0) - 128.0;
-       b = ((double) Lab[2] / 256.0) - 128.0;
-
-       y = (L + 16.) / 116.0;
-       x = y + 0.002 * a;
-       z = y - 0.005 * b;
-
-       X = f_1(x) * D50X;
-       Y = f_1(y) * D50Y;
-       Z = f_1(z) * D50Z;
-
-       // Convert to 1.15 fixed format PCS
-
-
-       XYZ[0] = _cmsClampWord((int) floor(X * 32768.0 + 0.5));
-       XYZ[1] = _cmsClampWord((int) floor(Y * 32768.0 + 0.5));
-       XYZ[2] = _cmsClampWord((int) floor(Z * 32768.0 + 0.5));
-
-
-}
-
-static
-double L2float3(WORD v)
-{
-       Fixed32 fix32;
-
-       fix32 = (Fixed32) v;
-       return (double) fix32 / 652.800;
-}
-
-
-// the a/b part
-
-static
-double ab2float3(WORD v)
-{
-       Fixed32 fix32;
-
-       fix32 = (Fixed32) v;
-       return ((double) fix32/256.0)-128.0;
-}
-
-static
-WORD L2Fix3(double L)
-{
-        return (WORD) (L *  652.800 + 0.5);
-}
-
-static
-WORD ab2Fix3(double ab)
-{
-        return (WORD) ((ab + 128.0) * 256.0 + 0.5);
-}
-
-
-// ICC 4.0 -- ICC has changed PCS Lab encoding.
-
-static
-WORD L2Fix4(double L)
-{
-     return (WORD) (L *  655.35 + 0.5);
-}
-
-static
-WORD ab2Fix4(double ab)
-{
-        return (WORD) ((ab + 128.0) * 257.0 + 0.5);
-}
-
-static
-double L2float4(WORD v)
-{
-       Fixed32 fix32;
-
-       fix32 = (Fixed32) v;
-       return (double) fix32 / 655.35;
-}
-
-
-// the a/b part
-
-static
-double ab2float4(WORD v)
-{
-       Fixed32 fix32;
-
-       fix32 = (Fixed32) v;
-       return ((double) fix32/257.0)-128.0;
-}
-
-
-void LCMSEXPORT cmsLabEncoded2Float(LPcmsCIELab Lab, const WORD wLab[3])
-{
-        Lab->L = L2float3(wLab[0]);
-        Lab->a = ab2float3(wLab[1]);
-        Lab->b = ab2float3(wLab[2]);
-}
-
-
-void LCMSEXPORT cmsLabEncoded2Float4(LPcmsCIELab Lab, const WORD wLab[3])
+void CMSEXPORT cmsLabEncoded2Float(cmsCIELab* Lab, const cmsUInt16Number wLab[3])
 {
         Lab->L = L2float4(wLab[0]);
         Lab->a = ab2float4(wLab[1]);
@@ -435,122 +251,147 @@
 }
 
 static
-double Clamp_L_double(double L)
+cmsFloat64Number Clamp_L_doubleV2(cmsFloat64Number L)
 {
+    const cmsFloat64Number L_max = (cmsFloat64Number) (0xFFFF * 100.0) / 0xFF00;
+
     if (L < 0) L = 0;
-    if (L > 100) L = 100;
+    if (L > L_max) L = L_max;
 
     return L;
 }
 
 
 static
-double Clamp_ab_double(double ab)
+cmsFloat64Number Clamp_ab_doubleV2(cmsFloat64Number ab)
 {
-    if (ab < -128) ab = -128.0;
-    if (ab > +127.9961) ab = +127.9961;
+    if (ab < MIN_ENCODEABLE_ab2) ab = MIN_ENCODEABLE_ab2;
+    if (ab > MAX_ENCODEABLE_ab2) ab = MAX_ENCODEABLE_ab2;
 
     return ab;
 }
 
-void LCMSEXPORT cmsFloat2LabEncoded(WORD wLab[3], const cmsCIELab* fLab)
+void CMSEXPORT cmsFloat2LabEncodedV2(cmsUInt16Number wLab[3], const cmsCIELab* fLab)
 {
     cmsCIELab Lab;
 
+    Lab.L = Clamp_L_doubleV2(fLab ->L);
+    Lab.a = Clamp_ab_doubleV2(fLab ->a);
+    Lab.b = Clamp_ab_doubleV2(fLab ->b);
 
-    Lab.L = Clamp_L_double(fLab ->L);
-    Lab.a = Clamp_ab_double(fLab ->a);
-    Lab.b = Clamp_ab_double(fLab ->b);
-
-    wLab[0] = L2Fix3(Lab.L);
-    wLab[1] = ab2Fix3(Lab.a);
-    wLab[2] = ab2Fix3(Lab.b);
+    wLab[0] = L2Fix2(Lab.L);
+    wLab[1] = ab2Fix2(Lab.a);
+    wLab[2] = ab2Fix2(Lab.b);
 }
 
 
-void LCMSEXPORT cmsFloat2LabEncoded4(WORD wLab[3], const cmsCIELab* fLab)
+static
+cmsFloat64Number Clamp_L_doubleV4(cmsFloat64Number L)
+{
+    if (L < 0) L = 0;
+    if (L > 100.0) L = 100.0;
+
+    return L;
+}
+
+static
+cmsFloat64Number Clamp_ab_doubleV4(cmsFloat64Number ab)
+{
+    if (ab < MIN_ENCODEABLE_ab4) ab = MIN_ENCODEABLE_ab4;
+    if (ab > MAX_ENCODEABLE_ab4) ab = MAX_ENCODEABLE_ab4;
+
+    return ab;
+}
+
+static
+cmsUInt16Number L2Fix4(cmsFloat64Number L)
+{
+    return _cmsQuickSaturateWord(L *  655.35);
+}
+
+static
+cmsUInt16Number ab2Fix4(cmsFloat64Number ab)
+{
+    return _cmsQuickSaturateWord((ab + 128.0) * 257.0);
+}
+
+void CMSEXPORT cmsFloat2LabEncoded(cmsUInt16Number wLab[3], const cmsCIELab* fLab)
 {
     cmsCIELab Lab;
 
-
-    Lab.L = fLab ->L;
-    Lab.a = fLab ->a;
-    Lab.b = fLab ->b;
-
-
-    if (Lab.L < 0) Lab.L = 0;
-    if (Lab.L > 100.) Lab.L = 100.;
-
-    if (Lab.a < -128.) Lab.a = -128.;
-    if (Lab.a > 127.) Lab.a = 127.;
-    if (Lab.b < -128.) Lab.b = -128.;
-    if (Lab.b > 127.) Lab.b = 127.;
-
+    Lab.L = Clamp_L_doubleV4(fLab ->L);
+    Lab.a = Clamp_ab_doubleV4(fLab ->a);
+    Lab.b = Clamp_ab_doubleV4(fLab ->b);
 
     wLab[0] = L2Fix4(Lab.L);
     wLab[1] = ab2Fix4(Lab.a);
     wLab[2] = ab2Fix4(Lab.b);
 }
 
-
+// Auxiliar: convert to Radians
+static
+cmsFloat64Number RADIANS(cmsFloat64Number deg)
+{
+    return (deg * M_PI) / 180.;
+}
 
 
-void LCMSEXPORT cmsLab2LCh(LPcmsCIELCh LCh, const cmsCIELab* Lab)
+// Auxiliar: atan2 but operating in degrees and returning 0 if a==b==0
+static
+cmsFloat64Number atan2deg(cmsFloat64Number a, cmsFloat64Number b)
 {
-    double a, b;
-
-    LCh -> L = Clamp_L_double(Lab -> L);
-
-    a = Clamp_ab_double(Lab -> a);
-    b = Clamp_ab_double(Lab -> b);
-
-    LCh -> C = pow(a * a + b * b, 0.5);
+   cmsFloat64Number h;
 
-    if (a == 0 && b == 0)
-            LCh -> h   = 0;
+   if (a == 0 && b == 0)
+            h   = 0;
     else
-            LCh -> h = atan2(b, a);
+            h = atan2(a, b);
 
-
-    LCh -> h *= (180. / M_PI);
+    h *= (180. / M_PI);
 
-
-    while (LCh -> h >= 360.)         // Not necessary, but included as a check.
-                LCh -> h -= 360.;
+    while (h > 360.)
+        h -= 360.;
 
-    while (LCh -> h < 0)
-                LCh -> h += 360.;
+    while ( h < 0)
+        h += 360.;
 
+    return h;
 }
 
 
-
-
-void LCMSEXPORT cmsLCh2Lab(LPcmsCIELab Lab, const cmsCIELCh* LCh)
+// Auxiliar: Square
+static
+cmsFloat64Number Sqr(cmsFloat64Number v)
 {
-
-    double h = (LCh -> h * M_PI) / 180.0;
-
-    Lab -> L = Clamp_L_double(LCh -> L);
-    Lab -> a = Clamp_ab_double(LCh -> C * cos(h));
-    Lab -> b = Clamp_ab_double(LCh -> C * sin(h));
-
+    return v *  v;
+}
+// From cylindrical coordinates. No check is performed, then negative values are allowed
+void CMSEXPORT cmsLab2LCh(cmsCIELCh* LCh, const cmsCIELab* Lab)
+{
+    LCh -> L = Lab -> L;
+    LCh -> C = pow(Sqr(Lab ->a) + Sqr(Lab ->b), 0.5);
+    LCh -> h = atan2deg(Lab ->b, Lab ->a);
 }
 
 
+// To cylindrical coordinates. No check is performed, then negative values are allowed
+void CMSEXPORT cmsLCh2Lab(cmsCIELab* Lab, const cmsCIELCh* LCh)
+{
+    cmsFloat64Number h = (LCh -> h * M_PI) / 180.0;
 
-
+    Lab -> L = LCh -> L;
+    Lab -> a = LCh -> C * cos(h);
+    Lab -> b = LCh -> C * sin(h);
+}
 
 // In XYZ All 3 components are encoded using 1.15 fixed point
-
 static
-WORD XYZ2Fix(double d)
+cmsUInt16Number XYZ2Fix(cmsFloat64Number d)
 {
-    return (WORD) floor(d * 32768.0 + 0.5);
+    return _cmsQuickSaturateWord(d * 32768.0);
 }
 
-
-void LCMSEXPORT cmsFloat2XYZEncoded(WORD XYZ[3], const cmsCIEXYZ* fXYZ)
+void CMSEXPORT cmsFloat2XYZEncoded(cmsUInt16Number XYZ[3], const cmsCIEXYZ* fXYZ)
 {
     cmsCIEXYZ xyz;
 
@@ -558,73 +399,557 @@
     xyz.Y = fXYZ -> Y;
     xyz.Z = fXYZ -> Z;
 
-
     // Clamp to encodeable values.
-    // 1.99997 is reserved as out-of-gamut marker
-
-
     if (xyz.Y <= 0) {
 
-                xyz.X = 0;
-                xyz.Y = 0;
-                xyz.Z = 0;
+        xyz.X = 0;
+        xyz.Y = 0;
+        xyz.Z = 0;
     }
 
-
-    if (xyz.X > 1.99996)
-           xyz.X = 1.99996;
+    if (xyz.X > MAX_ENCODEABLE_XYZ)
+        xyz.X = MAX_ENCODEABLE_XYZ;
 
     if (xyz.X < 0)
-           xyz.X = 0;
+        xyz.X = 0;
 
-    if (xyz.Y > 1.99996)
-                xyz.Y = 1.99996;
+    if (xyz.Y > MAX_ENCODEABLE_XYZ)
+        xyz.Y = MAX_ENCODEABLE_XYZ;
 
     if (xyz.Y < 0)
-           xyz.Y = 0;
-
+        xyz.Y = 0;
 
-    if (xyz.Z > 1.99996)
-                xyz.Z = 1.99996;
+    if (xyz.Z > MAX_ENCODEABLE_XYZ)
+        xyz.Z = MAX_ENCODEABLE_XYZ;
 
     if (xyz.Z < 0)
-           xyz.Z = 0;
-
+        xyz.Z = 0;
 
 
     XYZ[0] = XYZ2Fix(xyz.X);
     XYZ[1] = XYZ2Fix(xyz.Y);
     XYZ[2] = XYZ2Fix(xyz.Z);
+}
 
+
+//  To convert from Fixed 1.15 point to cmsFloat64Number
+static
+cmsFloat64Number XYZ2float(cmsUInt16Number v)
+{
+    cmsS15Fixed16Number fix32;
+
+    // From 1.15 to 15.16
+    fix32 = v << 1;
+
+    // From fixed 15.16 to cmsFloat64Number
+    return _cms15Fixed16toDouble(fix32);
+}
+
+
+void CMSEXPORT cmsXYZEncoded2Float(cmsCIEXYZ* fXYZ, const cmsUInt16Number XYZ[3])
+{
+    fXYZ -> X = XYZ2float(XYZ[0]);
+    fXYZ -> Y = XYZ2float(XYZ[1]);
+    fXYZ -> Z = XYZ2float(XYZ[2]);
+}
+
+
+// Returns dE on two Lab values
+cmsFloat64Number CMSEXPORT cmsDeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2)
+{
+    cmsFloat64Number dL, da, db;
+
+    dL = fabs(Lab1 -> L - Lab2 -> L);
+    da = fabs(Lab1 -> a - Lab2 -> a);
+    db = fabs(Lab1 -> b - Lab2 -> b);
+
+    return pow(Sqr(dL) + Sqr(da) + Sqr(db), 0.5);
 }
 
 
-//  To convert from Fixed 1.15 point to double
+// Return the CIE94 Delta E
+cmsFloat64Number CMSEXPORT cmsCIE94DeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2)
+{
+    cmsCIELCh LCh1, LCh2;
+    cmsFloat64Number dE, dL, dC, dh, dhsq;
+    cmsFloat64Number c12, sc, sh;
 
-static
-double XYZ2float(WORD v)
-{
-       Fixed32 fix32;
+    dL = fabs(Lab1 ->L - Lab2 ->L);
+
+    cmsLab2LCh(&LCh1, Lab1);
+    cmsLab2LCh(&LCh2, Lab2);
 
-       // From 1.15 to 15.16
-
-       fix32 = v << 1;
+    dC  = fabs(LCh1.C - LCh2.C);
+    dE  = cmsDeltaE(Lab1, Lab2);
 
-       // From fixed 15.16 to double
+    dhsq = Sqr(dE) - Sqr(dL) - Sqr(dC);
+    if (dhsq < 0)
+        dh = 0;
+    else
+        dh = pow(dhsq, 0.5);
 
-       return FIXED_TO_DOUBLE(fix32);
+    c12 = sqrt(LCh1.C * LCh2.C);
+
+    sc = 1.0 + (0.048 * c12);
+    sh = 1.0 + (0.014 * c12);
+
+    return sqrt(Sqr(dL)  + Sqr(dC) / Sqr(sc) + Sqr(dh) / Sqr(sh));
 }
 
 
-void LCMSEXPORT cmsXYZEncoded2Float(LPcmsCIEXYZ fXYZ, const WORD XYZ[3])
+// Auxiliary
+static
+cmsFloat64Number ComputeLBFD(const cmsCIELab* Lab)
 {
+  cmsFloat64Number yt;
 
-    fXYZ -> X = XYZ2float(XYZ[0]);
-    fXYZ -> Y = XYZ2float(XYZ[1]);
-    fXYZ -> Z = XYZ2float(XYZ[2]);
+  if (Lab->L > 7.996969)
+        yt = (Sqr((Lab->L+16)/116)*((Lab->L+16)/116))*100;
+  else
+        yt = 100 * (Lab->L / 903.3);
 
+  return (54.6 * (M_LOG10E * (log(yt + 1.5))) - 9.6);
 }
 
 
 
+// bfd - gets BFD(1:1) difference between Lab1, Lab2
+cmsFloat64Number CMSEXPORT cmsBFDdeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2)
+{
+    cmsFloat64Number lbfd1,lbfd2,AveC,Aveh,dE,deltaL,
+        deltaC,deltah,dc,t,g,dh,rh,rc,rt,bfd;
+    cmsCIELCh LCh1, LCh2;
 
+
+    lbfd1 = ComputeLBFD(Lab1);
+    lbfd2 = ComputeLBFD(Lab2);
+    deltaL = lbfd2 - lbfd1;
+
+    cmsLab2LCh(&LCh1, Lab1);
+    cmsLab2LCh(&LCh2, Lab2);
+
+    deltaC = LCh2.C - LCh1.C;
+    AveC = (LCh1.C+LCh2.C)/2;
+    Aveh = (LCh1.h+LCh2.h)/2;
+
+    dE = cmsDeltaE(Lab1, Lab2);
+
+    if (Sqr(dE)>(Sqr(Lab2->L-Lab1->L)+Sqr(deltaC)))
+        deltah = sqrt(Sqr(dE)-Sqr(Lab2->L-Lab1->L)-Sqr(deltaC));
+    else
+        deltah =0;
+
+
+    dc   = 0.035 * AveC / (1 + 0.00365 * AveC)+0.521;
+    g    = sqrt(Sqr(Sqr(AveC))/(Sqr(Sqr(AveC))+14000));
+    t    = 0.627+(0.055*cos((Aveh-254)/(180/M_PI))-
+           0.040*cos((2*Aveh-136)/(180/M_PI))+
+           0.070*cos((3*Aveh-31)/(180/M_PI))+
+           0.049*cos((4*Aveh+114)/(180/M_PI))-
+           0.015*cos((5*Aveh-103)/(180/M_PI)));
+
+    dh    = dc*(g*t+1-g);
+    rh    = -0.260*cos((Aveh-308)/(180/M_PI))-
+           0.379*cos((2*Aveh-160)/(180/M_PI))-
+           0.636*cos((3*Aveh+254)/(180/M_PI))+
+           0.226*cos((4*Aveh+140)/(180/M_PI))-
+           0.194*cos((5*Aveh+280)/(180/M_PI));
+
+    rc = sqrt((AveC*AveC*AveC*AveC*AveC*AveC)/((AveC*AveC*AveC*AveC*AveC*AveC)+70000000));
+    rt = rh*rc;
+
+    bfd = sqrt(Sqr(deltaL)+Sqr(deltaC/dc)+Sqr(deltah/dh)+(rt*(deltaC/dc)*(deltah/dh)));
+
+    return bfd;
+}
+
+
+//  cmc - CMC(l:c) difference between Lab1, Lab2
+cmsFloat64Number CMSEXPORT cmsCMCdeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2, cmsFloat64Number l, cmsFloat64Number c)
+{
+  cmsFloat64Number dE,dL,dC,dh,sl,sc,sh,t,f,cmc;
+  cmsCIELCh LCh1, LCh2;
+
+  if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;
+
+  cmsLab2LCh(&LCh1, Lab1);
+  cmsLab2LCh(&LCh2, Lab2);
+
+
+  dL = Lab2->L-Lab1->L;
+  dC = LCh2.C-LCh1.C;
+
+  dE = cmsDeltaE(Lab1, Lab2);
+
+  if (Sqr(dE)>(Sqr(dL)+Sqr(dC)))
+            dh = sqrt(Sqr(dE)-Sqr(dL)-Sqr(dC));
+  else
+            dh =0;
+
+  if ((LCh1.h > 164) && (LCh1.h < 345))
+      t = 0.56 + fabs(0.2 * cos(((LCh1.h + 168)/(180/M_PI))));
+  else
+      t = 0.36 + fabs(0.4 * cos(((LCh1.h + 35 )/(180/M_PI))));
+
+   sc  = 0.0638   * LCh1.C / (1 + 0.0131  * LCh1.C) + 0.638;
+   sl  = 0.040975 * Lab1->L /(1 + 0.01765 * Lab1->L);
+
+   if (Lab1->L<16)
+         sl = 0.511;
+
+   f   = sqrt((LCh1.C * LCh1.C * LCh1.C * LCh1.C)/((LCh1.C * LCh1.C * LCh1.C * LCh1.C)+1900));
+   sh  = sc*(t*f+1-f);
+   cmc = sqrt(Sqr(dL/(l*sl))+Sqr(dC/(c*sc))+Sqr(dh/sh));
+
+   return cmc;
+}
+
+// dE2000 The weightings KL, KC and KH can be modified to reflect the relative
+// importance of lightness, chroma and hue in different industrial applications
+cmsFloat64Number CMSEXPORT cmsCIE2000DeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2,
+                                  cmsFloat64Number Kl, cmsFloat64Number Kc, cmsFloat64Number Kh)
+{
+    cmsFloat64Number L1  = Lab1->L;
+    cmsFloat64Number a1  = Lab1->a;
+    cmsFloat64Number b1  = Lab1->b;
+    cmsFloat64Number C   = sqrt( Sqr(a1) + Sqr(b1) );
+
+    cmsFloat64Number Ls = Lab2 ->L;
+    cmsFloat64Number as = Lab2 ->a;
+    cmsFloat64Number bs = Lab2 ->b;
+    cmsFloat64Number Cs = sqrt( Sqr(as) + Sqr(bs) );
+
+    cmsFloat64Number G = 0.5 * ( 1 - sqrt(pow((C + Cs) / 2 , 7.0) / (pow((C + Cs) / 2, 7.0) + pow(25.0, 7.0) ) ));
+
+    cmsFloat64Number a_p = (1 + G ) * a1;
+    cmsFloat64Number b_p = b1;
+    cmsFloat64Number C_p = sqrt( Sqr(a_p) + Sqr(b_p));
+    cmsFloat64Number h_p = atan2deg(b_p, a_p);
+
+
+    cmsFloat64Number a_ps = (1 + G) * as;
+    cmsFloat64Number b_ps = bs;
+    cmsFloat64Number C_ps = sqrt(Sqr(a_ps) + Sqr(b_ps));
+    cmsFloat64Number h_ps = atan2deg(b_ps, a_ps);
+
+    cmsFloat64Number meanC_p =(C_p + C_ps) / 2;
+
+    cmsFloat64Number hps_plus_hp  = h_ps + h_p;
+    cmsFloat64Number hps_minus_hp = h_ps - h_p;
+
+    cmsFloat64Number meanh_p = fabs(hps_minus_hp) <= 180.000001 ? (hps_plus_hp)/2 :
+                            (hps_plus_hp) < 360 ? (hps_plus_hp + 360)/2 :
+                                                 (hps_plus_hp - 360)/2;
+
+    cmsFloat64Number delta_h = (hps_minus_hp) <= -180.000001 ?  (hps_minus_hp + 360) :
+                            (hps_minus_hp) > 180 ? (hps_minus_hp - 360) :
+                                                    (hps_minus_hp);
+    cmsFloat64Number delta_L = (Ls - L1);
+    cmsFloat64Number delta_C = (C_ps - C_p );
+
+
+    cmsFloat64Number delta_H =2 * sqrt(C_ps*C_p) * sin(RADIANS(delta_h) / 2);
+
+    cmsFloat64Number T = 1 - 0.17 * cos(RADIANS(meanh_p-30))
+                 + 0.24 * cos(RADIANS(2*meanh_p))
+                 + 0.32 * cos(RADIANS(3*meanh_p + 6))
+                 - 0.2  * cos(RADIANS(4*meanh_p - 63));
+
+    cmsFloat64Number Sl = 1 + (0.015 * Sqr((Ls + L1) /2- 50) )/ sqrt(20 + Sqr( (Ls+L1)/2 - 50) );
+
+    cmsFloat64Number Sc = 1 + 0.045 * (C_p + C_ps)/2;
+    cmsFloat64Number Sh = 1 + 0.015 * ((C_ps + C_p)/2) * T;
+
+    cmsFloat64Number delta_ro = 30 * exp( -Sqr(((meanh_p - 275 ) / 25)));
+
+    cmsFloat64Number Rc = 2 * sqrt(( pow(meanC_p, 7.0) )/( pow(meanC_p, 7.0) + pow(25.0, 7.0)));
+
+    cmsFloat64Number Rt = -sin(2 * RADIANS(delta_ro)) * Rc;
+
+    cmsFloat64Number deltaE00 = sqrt( Sqr(delta_L /(Sl * Kl)) +
+                            Sqr(delta_C/(Sc * Kc))  +
+                            Sqr(delta_H/(Sh * Kh))  +
+                            Rt*(delta_C/(Sc * Kc)) * (delta_H / (Sh * Kh)));
+
+    return deltaE00;
+}
+
+// This function returns a number of gridpoints to be used as LUT table. It assumes same number
+// of gripdpoints in all dimensions. Flags may override the choice.
+int _cmsReasonableGridpointsByColorspace(cmsColorSpaceSignature Colorspace, cmsUInt32Number dwFlags)
+{
+    int nChannels;
+
+    // Already specified?
+    if (dwFlags & 0x00FF0000) {
+            // Yes, grab'em
+            return (dwFlags >> 16) & 0xFF;
+    }
+
+    nChannels = cmsChannelsOf(Colorspace);
+
+    // HighResPrecalc is maximum resolution
+    if (dwFlags & cmsFLAGS_HIGHRESPRECALC) {
+
+        if (nChannels > 4)
+                return 7;       // 7 for Hifi
+
+        if (nChannels == 4)     // 23 for CMYK
+                return 23;
+
+        return 49;      // 49 for RGB and others
+    }
+
+
+    // LowResPrecal is lower resolution
+    if (dwFlags & cmsFLAGS_LOWRESPRECALC) {
+
+        if (nChannels > 4)
+                return 6;       // 6 for more than 4 channels
+
+        if (nChannels == 1)
+                return 33;      // For monochrome
+
+        return 17;              // 17 for remaining
+    }
+
+    // Default values
+    if (nChannels > 4)
+                return 7;       // 7 for Hifi
+
+    if (nChannels == 4)
+                return 17;      // 17 for CMYK
+
+    return 33;                  // 33 for RGB
+}
+
+
+cmsBool  _cmsEndPointsBySpace(cmsColorSpaceSignature Space,
+                             cmsUInt16Number **White,
+                             cmsUInt16Number **Black,
+                             cmsUInt32Number *nOutputs)
+{
+       // Only most common spaces
+
+       static cmsUInt16Number RGBblack[4]  = { 0, 0, 0 };
+       static cmsUInt16Number RGBwhite[4]  = { 0xffff, 0xffff, 0xffff };
+       static cmsUInt16Number CMYKblack[4] = { 0xffff, 0xffff, 0xffff, 0xffff };   // 400% of ink
+       static cmsUInt16Number CMYKwhite[4] = { 0, 0, 0, 0 };
+       static cmsUInt16Number LABblack[4]  = { 0, 0x8080, 0x8080 };               // V4 Lab encoding
+       static cmsUInt16Number LABwhite[4]  = { 0xFFFF, 0x8080, 0x8080 };
+       static cmsUInt16Number CMYblack[4]  = { 0xffff, 0xffff, 0xffff };
+       static cmsUInt16Number CMYwhite[4]  = { 0, 0, 0 };
+       static cmsUInt16Number Grayblack[4] = { 0 };
+       static cmsUInt16Number GrayWhite[4] = { 0xffff };
+
+       switch (Space) {
+
+       case cmsSigGrayData: if (White)    *White = GrayWhite;
+                           if (Black)    *Black = Grayblack;
+                           if (nOutputs) *nOutputs = 1;
+                           return TRUE;
+
+       case cmsSigRgbData:  if (White)    *White = RGBwhite;
+                           if (Black)    *Black = RGBblack;
+                           if (nOutputs) *nOutputs = 3;
+                           return TRUE;
+
+       case cmsSigLabData:  if (White)    *White = LABwhite;
+                           if (Black)    *Black = LABblack;
+                           if (nOutputs) *nOutputs = 3;
+                           return TRUE;
+
+       case cmsSigCmykData: if (White)    *White = CMYKwhite;
+                           if (Black)    *Black = CMYKblack;
+                           if (nOutputs) *nOutputs = 4;
+                           return TRUE;
+
+       case cmsSigCmyData:  if (White)    *White = CMYwhite;
+                           if (Black)    *Black = CMYblack;
+                           if (nOutputs) *nOutputs = 3;
+                           return TRUE;
+
+       default:;
+       }
+
+  return FALSE;
+}
+
+
+
+// Several utilities -------------------------------------------------------
+
+// Translate from our colorspace to ICC representation
+
+cmsColorSpaceSignature CMSEXPORT _cmsICCcolorSpace(int OurNotation)
+{
+       switch (OurNotation) {
+
+       case 1:
+       case PT_GRAY: return cmsSigGrayData;
+
+       case 2:
+       case PT_RGB:  return cmsSigRgbData;
+
+       case PT_CMY:  return cmsSigCmyData;
+       case PT_CMYK: return cmsSigCmykData;
+       case PT_YCbCr:return cmsSigYCbCrData;
+       case PT_YUV:  return cmsSigLuvData;
+       case PT_XYZ:  return cmsSigXYZData;
+
+       case PT_LabV2:
+       case PT_Lab:  return cmsSigLabData;
+
+       case PT_YUVK: return cmsSigLuvKData;
+       case PT_HSV:  return cmsSigHsvData;
+       case PT_HLS:  return cmsSigHlsData;
+       case PT_Yxy:  return cmsSigYxyData;
+
+       case PT_MCH1: return cmsSigMCH1Data;
+       case PT_MCH2: return cmsSigMCH2Data;
+       case PT_MCH3: return cmsSigMCH3Data;
+       case PT_MCH4: return cmsSigMCH4Data;
+       case PT_MCH5: return cmsSigMCH5Data;
+       case PT_MCH6: return cmsSigMCH6Data;
+       case PT_MCH7: return cmsSigMCH7Data;
+       case PT_MCH8: return cmsSigMCH8Data;
+
+       case PT_MCH9:  return cmsSigMCH9Data;
+       case PT_MCH10: return cmsSigMCHAData;
+       case PT_MCH11: return cmsSigMCHBData;
+       case PT_MCH12: return cmsSigMCHCData;
+       case PT_MCH13: return cmsSigMCHDData;
+       case PT_MCH14: return cmsSigMCHEData;
+       case PT_MCH15: return cmsSigMCHFData;
+
+       default:  return (cmsColorSpaceSignature) (-1);
+       }
+}
+
+
+int CMSEXPORT _cmsLCMScolorSpace(cmsColorSpaceSignature ProfileSpace)
+{
+    switch (ProfileSpace) {
+
+    case cmsSigGrayData: return  PT_GRAY;
+    case cmsSigRgbData:  return  PT_RGB;
+    case cmsSigCmyData:  return  PT_CMY;
+    case cmsSigCmykData: return  PT_CMYK;
+    case cmsSigYCbCrData:return  PT_YCbCr;
+    case cmsSigLuvData:  return  PT_YUV;
+    case cmsSigXYZData:  return  PT_XYZ;
+    case cmsSigLabData:  return  PT_Lab;
+    case cmsSigLuvKData: return  PT_YUVK;
+    case cmsSigHsvData:  return  PT_HSV;
+    case cmsSigHlsData:  return  PT_HLS;
+    case cmsSigYxyData:  return  PT_Yxy;
+
+    case cmsSig1colorData:
+    case cmsSigMCH1Data: return PT_MCH1;
+
+    case cmsSig2colorData:
+    case cmsSigMCH2Data: return PT_MCH2;
+
+    case cmsSig3colorData:
+    case cmsSigMCH3Data: return PT_MCH3;
+
+    case cmsSig4colorData:
+    case cmsSigMCH4Data: return PT_MCH4;
+
+    case cmsSig5colorData:
+    case cmsSigMCH5Data: return PT_MCH5;
+
+    case cmsSig6colorData:
+    case cmsSigMCH6Data: return PT_MCH6;
+
+    case cmsSigMCH7Data:
+    case cmsSig7colorData:return PT_MCH7;
+
+    case cmsSigMCH8Data:
+    case cmsSig8colorData:return PT_MCH8;
+
+    case cmsSigMCH9Data:
+    case cmsSig9colorData:return PT_MCH9;
+
+    case cmsSigMCHAData:
+    case cmsSig10colorData:return PT_MCH10;
+
+    case cmsSigMCHBData:
+    case cmsSig11colorData:return PT_MCH11;
+
+    case cmsSigMCHCData:
+    case cmsSig12colorData:return PT_MCH12;
+
+    case cmsSigMCHDData:
+    case cmsSig13colorData:return PT_MCH13;
+
+    case cmsSigMCHEData:
+    case cmsSig14colorData:return PT_MCH14;
+
+    case cmsSigMCHFData:
+    case cmsSig15colorData:return PT_MCH15;
+
+    default:  return (cmsColorSpaceSignature) (-1);
+    }
+}
+
+
+cmsUInt32Number CMSEXPORT cmsChannelsOf(cmsColorSpaceSignature ColorSpace)
+{
+    switch (ColorSpace) {
+
+    case cmsSigGrayData: return 1;
+
+    case cmsSig2colorData:  return 2;
+
+    case cmsSigXYZData:
+    case cmsSigLabData:
+    case cmsSigLuvData:
+    case cmsSigYCbCrData:
+    case cmsSigYxyData:
+    case cmsSigRgbData:
+    case cmsSigHsvData:
+    case cmsSigHlsData:
+    case cmsSigCmyData:
+    case cmsSig3colorData:  return 3;
+
+    case cmsSigLuvKData:
+    case cmsSigCmykData:
+    case cmsSig4colorData:  return 4;
+
+    case cmsSigMCH5Data:
+    case cmsSig5colorData:  return 5;
+
+    case cmsSigMCH6Data:
+    case cmsSig6colorData:  return 6;
+
+    case cmsSigMCH7Data:
+    case cmsSig7colorData:  return  7;
+
+    case cmsSigMCH8Data:
+    case cmsSig8colorData:  return  8;
+
+    case cmsSigMCH9Data:
+    case cmsSig9colorData:  return  9;
+
+    case cmsSigMCHAData:
+    case cmsSig10colorData: return 10;
+
+    case cmsSigMCHBData:
+    case cmsSig11colorData: return 11;
+
+    case cmsSigMCHCData:
+    case cmsSig12colorData: return 12;
+
+    case cmsSigMCHDData:
+    case cmsSig13colorData: return 13;
+
+    case cmsSigMCHEData:
+    case cmsSig14colorData: return 14;
+
+    case cmsSigMCHFData:
+    case cmsSig15colorData: return 15;
+
+    default: return 3;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,641 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
+
+
+// ----------------------------------------------------------------------------------
+// Encoding & Decoding support functions
+// ----------------------------------------------------------------------------------
+
+//      Little-Endian to Big-Endian
+
+// Adjust a word value after being readed/ before being written from/to an ICC profile
+cmsUInt16Number CMSEXPORT  _cmsAdjustEndianess16(cmsUInt16Number Word)
+{
+#ifndef CMS_USE_BIG_ENDIAN
+
+    cmsUInt8Number* pByte = (cmsUInt8Number*) &Word;
+    cmsUInt8Number tmp;
+
+    tmp = pByte[0];
+    pByte[0] = pByte[1];
+    pByte[1] = tmp;
+#endif
+
+    return Word;
+}
+
+
+// Transports to properly encoded values - note that icc profiles does use big endian notation.
+
+// 1 2 3 4
+// 4 3 2 1
+
+cmsUInt32Number CMSEXPORT  _cmsAdjustEndianess32(cmsUInt32Number DWord)
+{
+#ifndef CMS_USE_BIG_ENDIAN
+
+    cmsUInt8Number* pByte = (cmsUInt8Number*) &DWord;
+    cmsUInt8Number temp1;
+    cmsUInt8Number temp2;
+
+    temp1 = *pByte++;
+    temp2 = *pByte++;
+    *(pByte-1) = *pByte;
+    *pByte++ = temp2;
+    *(pByte-3) = *pByte;
+    *pByte = temp1;
+#endif
+    return DWord;
+}
+
+// 1 2 3 4 5 6 7 8
+// 8 7 6 5 4 3 2 1
+
+void CMSEXPORT  _cmsAdjustEndianess64(cmsUInt64Number* Result, cmsUInt64Number QWord)
+{
+
+#ifndef CMS_USE_BIG_ENDIAN
+
+    cmsUInt8Number* pIn  = (cmsUInt8Number*) &QWord;
+    cmsUInt8Number* pOut = (cmsUInt8Number*) Result;
+
+    _cmsAssert(Result != NULL);
+
+    pOut[7] = pIn[0];
+    pOut[6] = pIn[1];
+    pOut[5] = pIn[2];
+    pOut[4] = pIn[3];
+    pOut[3] = pIn[4];
+    pOut[2] = pIn[5];
+    pOut[1] = pIn[6];
+    pOut[0] = pIn[7];
+
+#else
+
+    _cmsAssert(Result != NULL);
+
+    *Result = QWord;
+#endif
+}
+
+// Auxiliar -- read 8, 16 and 32-bit numbers
+cmsBool CMSEXPORT  _cmsReadUInt8Number(cmsIOHANDLER* io, cmsUInt8Number* n)
+{
+    cmsUInt8Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    if (io -> Read(io, &tmp, sizeof(cmsUInt8Number), 1) != 1)
+            return FALSE;
+
+    if (n != NULL) *n = tmp;
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsReadUInt16Number(cmsIOHANDLER* io, cmsUInt16Number* n)
+{
+    cmsUInt16Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    if (io -> Read(io, &tmp, sizeof(cmsUInt16Number), 1) != 1)
+            return FALSE;
+
+    if (n != NULL) *n = _cmsAdjustEndianess16(tmp);
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsReadUInt16Array(cmsIOHANDLER* io, cmsUInt32Number n, cmsUInt16Number* Array)
+{
+    cmsUInt32Number i;
+
+    _cmsAssert(io != NULL);
+
+    for (i=0; i < n; i++) {
+
+        if (Array != NULL) {
+            if (!_cmsReadUInt16Number(io, Array + i)) return FALSE;
+        }
+        else {
+            if (!_cmsReadUInt16Number(io, NULL)) return FALSE;
+        }
+
+    }
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsReadUInt32Number(cmsIOHANDLER* io, cmsUInt32Number* n)
+{
+    cmsUInt32Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    if (io -> Read(io, &tmp, sizeof(cmsUInt32Number), 1) != 1)
+            return FALSE;
+
+    if (n != NULL) *n = _cmsAdjustEndianess32(tmp);
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsReadFloat32Number(cmsIOHANDLER* io, cmsFloat32Number* n)
+{
+    cmsUInt32Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    if (io -> Read(io, &tmp, sizeof(cmsFloat32Number), 1) != 1)
+            return FALSE;
+
+    if (n != NULL) {
+
+        tmp = _cmsAdjustEndianess32(tmp);
+        *n = *(cmsFloat32Number*) &tmp;
+    }
+    return TRUE;
+}
+
+
+cmsBool CMSEXPORT   _cmsReadUInt64Number(cmsIOHANDLER* io, cmsUInt64Number* n)
+{
+    cmsUInt64Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    if (io -> Read(io, &tmp, sizeof(cmsUInt64Number), 1) != 1)
+            return FALSE;
+
+    if (n != NULL) _cmsAdjustEndianess64(n, tmp);
+    return TRUE;
+}
+
+
+cmsBool CMSEXPORT  _cmsRead15Fixed16Number(cmsIOHANDLER* io, cmsFloat64Number* n)
+{
+    cmsUInt32Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    if (io -> Read(io, &tmp, sizeof(cmsUInt32Number), 1) != 1)
+            return FALSE;
+
+    if (n != NULL) {
+        *n = _cms15Fixed16toDouble(_cmsAdjustEndianess32(tmp));
+    }
+
+    return TRUE;
+}
+
+
+// Jun-21-2000: Some profiles (those that comes with W2K) comes
+// with the media white (media black?) x 100. Add a sanity check
+
+static
+void NormalizeXYZ(cmsCIEXYZ* Dest)
+{
+    while (Dest -> X > 2. &&
+           Dest -> Y > 2. &&
+           Dest -> Z > 2.) {
+
+               Dest -> X /= 10.;
+               Dest -> Y /= 10.;
+               Dest -> Z /= 10.;
+       }
+}
+
+cmsBool CMSEXPORT  _cmsReadXYZNumber(cmsIOHANDLER* io, cmsCIEXYZ* XYZ)
+{
+    cmsEncodedXYZNumber xyz;
+
+    _cmsAssert(io != NULL);
+
+    if (io ->Read(io, &xyz, sizeof(cmsEncodedXYZNumber), 1) != 1) return FALSE;
+
+    if (XYZ != NULL) {
+
+        XYZ->X = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.X));
+        XYZ->Y = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.Y));
+        XYZ->Z = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.Z));
+
+        NormalizeXYZ(XYZ);
+    }
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsWriteUInt8Number(cmsIOHANDLER* io, cmsUInt8Number n)
+{
+    _cmsAssert(io != NULL);
+
+    if (io -> Write(io, sizeof(cmsUInt8Number), &n) != 1)
+            return FALSE;
+
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsWriteUInt16Number(cmsIOHANDLER* io, cmsUInt16Number n)
+{
+    cmsUInt16Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    tmp = _cmsAdjustEndianess16(n);
+    if (io -> Write(io, sizeof(cmsUInt16Number), &tmp) != 1)
+            return FALSE;
+
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsWriteUInt16Array(cmsIOHANDLER* io, cmsUInt32Number n, const cmsUInt16Number* Array)
+{
+    cmsUInt32Number i;
+
+    _cmsAssert(io != NULL);
+    _cmsAssert(Array != NULL);
+
+    for (i=0; i < n; i++) {
+        if (!_cmsWriteUInt16Number(io, Array[i])) return FALSE;
+    }
+
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsWriteUInt32Number(cmsIOHANDLER* io, cmsUInt32Number n)
+{
+    cmsUInt32Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    tmp = _cmsAdjustEndianess32(n);
+    if (io -> Write(io, sizeof(cmsUInt32Number), &tmp) != 1)
+            return FALSE;
+
+    return TRUE;
+}
+
+
+cmsBool CMSEXPORT  _cmsWriteFloat32Number(cmsIOHANDLER* io, cmsFloat32Number n)
+{
+    cmsUInt32Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    tmp = *(cmsUInt32Number*) &n;
+    tmp = _cmsAdjustEndianess32(tmp);
+    if (io -> Write(io, sizeof(cmsUInt32Number), &tmp) != 1)
+            return FALSE;
+
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsWriteUInt64Number(cmsIOHANDLER* io, cmsUInt64Number n)
+{
+    cmsUInt64Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    _cmsAdjustEndianess64(&tmp, n);
+    if (io -> Write(io, sizeof(cmsUInt64Number), &tmp) != 1)
+            return FALSE;
+
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsWrite15Fixed16Number(cmsIOHANDLER* io, cmsFloat64Number n)
+{
+    cmsUInt32Number tmp;
+
+    _cmsAssert(io != NULL);
+
+    tmp = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(n));
+    if (io -> Write(io, sizeof(cmsUInt32Number), &tmp) != 1)
+            return FALSE;
+
+    return TRUE;
+}
+
+cmsBool CMSEXPORT  _cmsWriteXYZNumber(cmsIOHANDLER* io, const cmsCIEXYZ* XYZ)
+{
+    cmsEncodedXYZNumber xyz;
+
+    _cmsAssert(io != NULL);
+    _cmsAssert(XYZ != NULL);
+
+    xyz.X = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(XYZ->X));
+    xyz.Y = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(XYZ->Y));
+    xyz.Z = _cmsAdjustEndianess32(_cmsDoubleTo15Fixed16(XYZ->Z));
+
+    return io -> Write(io,  sizeof(cmsEncodedXYZNumber), &xyz);
+}
+
+// from Fixed point 8.8 to double
+cmsFloat64Number CMSEXPORT _cms8Fixed8toDouble(cmsUInt16Number fixed8)
+{
+       cmsUInt8Number  msb, lsb;
+
+       lsb = (cmsUInt8Number) (fixed8 & 0xff);
+       msb = (cmsUInt8Number) (((cmsUInt16Number) fixed8 >> 8) & 0xff);
+
+       return (cmsFloat64Number) ((cmsFloat64Number) msb + ((cmsFloat64Number) lsb / 256.0));
+}
+
+cmsUInt16Number CMSEXPORT _cmsDoubleTo8Fixed8(cmsFloat64Number val)
+{
+    cmsS15Fixed16Number GammaFixed32 = _cmsDoubleTo15Fixed16(val);
+    return  (cmsUInt16Number) ((GammaFixed32 >> 8) & 0xFFFF);
+}
+
+// from Fixed point 15.16 to double
+cmsFloat64Number CMSEXPORT _cms15Fixed16toDouble(cmsS15Fixed16Number fix32)
+{
+    cmsFloat64Number floater, sign, mid;
+    int Whole, FracPart;
+
+    sign  = (fix32 < 0 ? -1 : 1);
+    fix32 = abs(fix32);
+
+    Whole     = (cmsUInt16Number)(fix32 >> 16) & 0xffff;
+    FracPart  = (cmsUInt16Number)(fix32 & 0xffff);
+
+    mid     = (cmsFloat64Number) FracPart / 65536.0;
+    floater = (cmsFloat64Number) Whole + mid;
+
+    return sign * floater;
+}
+
+// from double to Fixed point 15.16
+cmsS15Fixed16Number CMSEXPORT _cmsDoubleTo15Fixed16(cmsFloat64Number v)
+{
+    return ((cmsS15Fixed16Number) floor((v)*65536.0 + 0.5));
+}
+
+// Date/Time functions
+
+void CMSEXPORT _cmsDecodeDateTimeNumber(const cmsDateTimeNumber *Source, struct tm *Dest)
+{
+
+    _cmsAssert(Dest != NULL);
+    _cmsAssert(Source != NULL);
+
+    Dest->tm_sec   = _cmsAdjustEndianess16(Source->seconds);
+    Dest->tm_min   = _cmsAdjustEndianess16(Source->minutes);
+    Dest->tm_hour  = _cmsAdjustEndianess16(Source->hours);
+    Dest->tm_mday  = _cmsAdjustEndianess16(Source->day);
+    Dest->tm_mon   = _cmsAdjustEndianess16(Source->month) - 1;
+    Dest->tm_year  = _cmsAdjustEndianess16(Source->year) - 1900;
+    Dest->tm_wday  = -1;
+    Dest->tm_yday  = -1;
+    Dest->tm_isdst = 0;
+}
+
+void CMSEXPORT _cmsEncodeDateTimeNumber(cmsDateTimeNumber *Dest, const struct tm *Source)
+{
+    _cmsAssert(Dest != NULL);
+    _cmsAssert(Source != NULL);
+
+    Dest->seconds = _cmsAdjustEndianess16((cmsUInt16Number) Source->tm_sec);
+    Dest->minutes = _cmsAdjustEndianess16((cmsUInt16Number) Source->tm_min);
+    Dest->hours   = _cmsAdjustEndianess16((cmsUInt16Number) Source->tm_hour);
+    Dest->day     = _cmsAdjustEndianess16((cmsUInt16Number) Source->tm_mday);
+    Dest->month   = _cmsAdjustEndianess16((cmsUInt16Number) (Source->tm_mon + 1));
+    Dest->year    = _cmsAdjustEndianess16((cmsUInt16Number) (Source->tm_year + 1900));
+}
+
+// Read base and return type base
+cmsTagTypeSignature CMSEXPORT _cmsReadTypeBase(cmsIOHANDLER* io)
+{
+    _cmsTagBase Base;
+
+    _cmsAssert(io != NULL);
+
+    if (io -> Read(io, &Base, sizeof(_cmsTagBase), 1) != 1)
+        return (cmsTagTypeSignature) 0;
+
+    return (cmsTagTypeSignature) _cmsAdjustEndianess32(Base.sig);
+}
+
+// Setup base marker
+cmsBool  CMSEXPORT _cmsWriteTypeBase(cmsIOHANDLER* io, cmsTagTypeSignature sig)
+{
+    _cmsTagBase  Base;
+
+    _cmsAssert(io != NULL);
+
+    Base.sig = (cmsTagTypeSignature) _cmsAdjustEndianess32(sig);
+    memset(&Base.reserved, 0, sizeof(Base.reserved));
+    return io -> Write(io, sizeof(_cmsTagBase), &Base);
+}
+
+cmsBool CMSEXPORT _cmsReadAlignment(cmsIOHANDLER* io)
+{
+    cmsUInt8Number  Buffer[4];
+    cmsUInt32Number NextAligned, At;
+    cmsUInt32Number BytesToNextAlignedPos;
+
+    _cmsAssert(io != NULL);
+
+    At = io -> Tell(io);
+    NextAligned = _cmsALIGNLONG(At);
+    BytesToNextAlignedPos = NextAligned - At;
+    if (BytesToNextAlignedPos == 0) return TRUE;
+    if (BytesToNextAlignedPos > 4)  return FALSE;
+
+    return (io ->Read(io, Buffer, BytesToNextAlignedPos, 1) == 1);
+}
+
+cmsBool CMSEXPORT _cmsWriteAlignment(cmsIOHANDLER* io)
+{
+    cmsUInt8Number  Buffer[4];
+    cmsUInt32Number NextAligned, At;
+    cmsUInt32Number BytesToNextAlignedPos;
+
+    _cmsAssert(io != NULL);
+
+    At = io -> Tell(io);
+    NextAligned = _cmsALIGNLONG(At);
+    BytesToNextAlignedPos = NextAligned - At;
+    if (BytesToNextAlignedPos == 0) return TRUE;
+    if (BytesToNextAlignedPos > 4)  return FALSE;
+
+    memset(Buffer, 0, BytesToNextAlignedPos);
+    return io -> Write(io, BytesToNextAlignedPos, Buffer);
+}
+
+
+// To deal with text streams. 2K at most
+cmsBool CMSEXPORT _cmsIOPrintf(cmsIOHANDLER* io, const char* frm, ...)
+{
+    va_list args;
+    int len;
+    cmsUInt8Number Buffer[2048];
+    cmsBool rc;
+
+    _cmsAssert(io != NULL);
+    _cmsAssert(frm != NULL);
+
+    va_start(args, frm);
+
+    len = vsnprintf((char*) Buffer, 2047, frm, args);
+    if (len < 0) return FALSE;   // Truncated, which is a fatal error for us
+
+    rc = io ->Write(io, len, Buffer);
+
+    va_end(args);
+
+    return rc;
+}
+
+
+// Plugin memory management -------------------------------------------------------------------------------------------------
+
+static _cmsSubAllocator* PluginPool = NULL;
+
+// Specialized malloc for plug-ins, that is freed upon exit.
+void* _cmsPluginMalloc(cmsUInt32Number size)
+{
+    if (PluginPool == NULL)
+        PluginPool = _cmsCreateSubAlloc(0, 4*1024);
+
+    return _cmsSubAlloc(PluginPool, size);
+}
+
+
+// Main plug-in dispatcher
+cmsBool CMSEXPORT cmsPlugin(void* Plug_in)
+{
+    cmsPluginBase* Plugin;
+
+    for (Plugin = (cmsPluginBase*) Plug_in;
+         Plugin != NULL;
+         Plugin = Plugin -> Next) {
+
+            if (Plugin -> Magic != cmsPluginMagicNumber) {
+                cmsSignalError(0, cmsERROR_UNKNOWN_EXTENSION, "Unrecognized plugin");
+                return FALSE;
+            }
+
+            if (Plugin ->ExpectedVersion > LCMS_VERSION) {
+                cmsSignalError(0, cmsERROR_UNKNOWN_EXTENSION, "plugin needs Little CMS %d, current  version is %d",
+                               Plugin ->ExpectedVersion, LCMS_VERSION);
+                return FALSE;
+            }
+
+            switch (Plugin -> Type) {
+
+                case cmsPluginMemHandlerSig:
+                    if (!_cmsRegisterMemHandlerPlugin(Plugin)) return FALSE;
+                    break;
+
+                case cmsPluginInterpolationSig:
+                    if (!_cmsRegisterInterpPlugin(Plugin)) return FALSE;
+                    break;
+
+                case cmsPluginTagTypeSig:
+                    if (!_cmsRegisterTagTypePlugin(Plugin)) return FALSE;
+                    break;
+
+                case cmsPluginTagSig:
+                    if (!_cmsRegisterTagPlugin(Plugin)) return FALSE;
+                    break;
+
+                case cmsPluginFormattersSig:
+                    if (!_cmsRegisterFormattersPlugin(Plugin)) return FALSE;
+                    break;
+
+                case cmsPluginRenderingIntentSig:
+                    if (!_cmsRegisterRenderingIntentPlugin(Plugin)) return FALSE;
+                    break;
+
+                case cmsPluginParametricCurveSig:
+                    if (!_cmsRegisterParametricCurvesPlugin(Plugin)) return FALSE;
+                    break;
+
+                case cmsPluginMultiProcessElementSig:
+                    if (!_cmsRegisterMultiProcessElementPlugin(Plugin)) return FALSE;
+                    break;
+
+                case cmsPluginOptimizationSig:
+                    if (!_cmsRegisterOptimizationPlugin(Plugin)) return FALSE;
+                    break;
+
+                default:
+                    cmsSignalError(0, cmsERROR_UNKNOWN_EXTENSION, "Unrecognized plugin type '%X'", Plugin -> Type);
+                    return FALSE;
+            }
+    }
+
+    // Keep a reference to the plug-in
+    return TRUE;
+}
+
+
+// Revert all plug-ins to default
+void CMSEXPORT cmsUnregisterPlugins(void)
+{
+    _cmsRegisterMemHandlerPlugin(NULL);
+    _cmsRegisterInterpPlugin(NULL);
+    _cmsRegisterTagTypePlugin(NULL);
+    _cmsRegisterTagPlugin(NULL);
+    _cmsRegisterFormattersPlugin(NULL);
+    _cmsRegisterRenderingIntentPlugin(NULL);
+    _cmsRegisterParametricCurvesPlugin(NULL);
+    _cmsRegisterMultiProcessElementPlugin(NULL);
+    _cmsRegisterOptimizationPlugin(NULL);
+
+    if (PluginPool != NULL)
+        _cmsSubAllocDestroy(PluginPool);
+
+    PluginPool = NULL;
+}
--- a/src/share/native/sun/java2d/cmm/lcms/cmsps2.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsps2.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2008 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,22 +49,14 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-// Postscript level 2 operators
-
+//
+//---------------------------------------------------------------------------------
+//
 
-
-#include "lcms.h"
-#include <time.h>
-#include <stdarg.h>
+#include "lcms2_internal.h"
 
 // PostScript ColorRenderingDictionary and ColorSpaceArray
 
-LCMSAPI DWORD LCMSEXPORT cmsGetPostScriptCSA(cmsHPROFILE hProfile, int Intent, LPVOID Buffer, DWORD dwBufferLen);
-LCMSAPI DWORD LCMSEXPORT cmsGetPostScriptCRD(cmsHPROFILE hProfile, int Intent, LPVOID Buffer, DWORD dwBufferLen);
-LCMSAPI DWORD LCMSEXPORT cmsGetPostScriptCRDEx(cmsHPROFILE hProfile, int Intent, DWORD dwFlags, LPVOID Buffer, DWORD dwBufferLen);
-// -------------------------------------------------------------------- Implementation
 
 #define MAXPSCOLS   60      // Columns on tables
 
@@ -83,9 +76,9 @@
   Color Space Arrays (CSA)
   ==================================================================================
 
-  In order to obtain precission, code chooses between three ways to implement
+  In order to obtain precision, code chooses between three ways to implement
   the device -> XYZ transform. These cases identifies monochrome profiles (often
-  implemented as a set of curves), matrix-shaper and LUT-based.
+  implemented as a set of curves), matrix-shaper and Pipeline-based.
 
   Monochrome
   -----------
@@ -101,7 +94,7 @@
       <<
             /DecodeA { transfer function } bind
             /MatrixA [D50]
-            /RangeLMN [ 0.0 D50X 0.0 D50Y 0.0 D50Z ]
+            /RangeLMN [ 0.0 cmsD50X 0.0 cmsD50Y 0.0 cmsD50Z ]
             /WhitePoint [D50]
             /BlackPoint [BP]
             /RenderingIntent (intent)
@@ -115,7 +108,7 @@
    -------------------
 
    This is implemented both with /CIEBasedABC or /CIEBasedDEF on dependig
-   of profile implementation. Since here is no interpolation tables, I do
+   of profile implementation. Since here there are no interpolation tables, I do
    the conversion directly to XYZ
 
 
@@ -124,7 +117,7 @@
             <<
                 /DecodeABC [ {transfer1} {transfer2} {transfer3} ]
                 /MatrixABC [Matrix]
-                /RangeLMN [ 0.0 D50X 0.0 D50Y 0.0 D50Z ]
+                /RangeLMN [ 0.0 cmsD50X 0.0 cmsD50Y 0.0 cmsD50Z ]
                 /DecodeLMN [ { / 2} dup dup ]
                 /WhitePoint [D50]
                 /BlackPoint [BP]
@@ -299,153 +292,66 @@
 
 */
 
-static icTagSignature Device2PCSTab[] = {icSigAToB0Tag,       // Perceptual
-                                         icSigAToB1Tag,       // Relative colorimetric
-                                         icSigAToB2Tag,       // Saturation
-                                         icSigAToB1Tag };     // Absolute colorimetric
-                                                           // (Relative/WhitePoint)
 
-
-// --------------------------------------------------------------- Memory Stream
-//
 // This struct holds the memory block currently being write
-//
+typedef struct {
+    _cmsStageCLutData* Pipeline;
+    cmsIOHANDLER* m;
+
+    int FirstComponent;
+    int SecondComponent;
 
-typedef struct {
-                LPBYTE Block;
-                LPBYTE Ptr;
-                DWORD  dwMax;
-                DWORD  dwUsed;
-                int    MaxCols;
-                int    Col;
-                int    HasError;
+    const char* PreMaj;
+    const char* PostMaj;
+    const char* PreMin;
+    const char* PostMin;
 
-            } MEMSTREAM, FAR* LPMEMSTREAM;
+    int  FixWhite;    // Force mapping of pure white
+
+    cmsColorSpaceSignature  ColorSpace;  // ColorSpace of profile
 
 
-typedef struct {
-                LPLUT Lut;
-                LPMEMSTREAM m;
-
-                int FirstComponent;
-                int SecondComponent;
-
-                int   bps;
-                const char* PreMaj;
-                const char* PostMaj;
-                const char* PreMin;
-                const char* PostMin;
-
-                int  lIsInput;    // Handle L* encoding
-                int  FixWhite;    // Force mapping of pure white
-
-                icColorSpaceSignature  ColorSpace;  // ColorSpace of profile
-
-
-            } SAMPLERCARGO, FAR* LPSAMPLERCARGO;
+} cmsPsSamplerCargo;
 
-
-// Creates a ready to use memory stream
-static
-LPMEMSTREAM CreateMemStream(LPBYTE Buffer, DWORD dwMax, int MaxCols)
-{
-    LPMEMSTREAM m = (LPMEMSTREAM) _cmsMalloc(sizeof(MEMSTREAM));
-    if (m == NULL) return NULL;
-
-    ZeroMemory(m, sizeof(MEMSTREAM));
-
-    m -> Block   = m -> Ptr = Buffer;
-    m -> dwMax   = dwMax;
-    m -> dwUsed  = 0;
-    m -> MaxCols = MaxCols;
-    m -> Col     = 0;
-    m -> HasError = 0;
-
-    return m;
-}
-
+static int _cmsPSActualColumn = 0;
 
 
 // Convert to byte
 static
-BYTE Word2Byte(WORD w)
+cmsUInt8Number Word2Byte(cmsUInt16Number w)
 {
-    return (BYTE) floor((double) w / 257.0 + 0.5);
+    return (cmsUInt8Number) floor((cmsFloat64Number) w / 257.0 + 0.5);
 }
 
 
 // Convert to byte (using ICC2 notation)
-
-static
-BYTE L2Byte(WORD w)
-{
-    int ww = w + 0x0080;
-
-    if (ww > 0xFFFF) return 0xFF;
-
-    return (BYTE) ((WORD) (ww >> 8) & 0xFF);
-}
-
-// Write a raw, uncooked byte. Check for space
+/*
 static
-void WriteRawByte(LPMEMSTREAM m, BYTE b)
+cmsUInt8Number L2Byte(cmsUInt16Number w)
 {
-    if (m -> dwUsed + 1 > m -> dwMax) {
-        m -> HasError = 1;
-    }
+        int ww = w + 0x0080;
 
-    if (!m ->HasError && m ->Block) {
-        *m ->Ptr++ = b;
-    }
+        if (ww > 0xFFFF) return 0xFF;
 
-    m -> dwUsed++;
+    return (cmsUInt8Number) ((cmsUInt16Number) (ww >> 8) & 0xFF);
 }
+*/
 
 // Write a cooked byte
+
 static
-void WriteByte(LPMEMSTREAM m, BYTE b)
+void WriteByte(cmsIOHANDLER* m, cmsUInt8Number b)
 {
-    static const BYTE Hex[] = "0123456789ABCDEF";
-    BYTE c;
-
-        c = Hex[(b >> 4) & 0x0f];
-        WriteRawByte(m, c);
-
-        c = Hex[b & 0x0f];
-        WriteRawByte(m, c);
-
-        m -> Col += 2;
-
-        if (m -> Col > m -> MaxCols) {
-
-            WriteRawByte(m, '\n');
-            m -> Col = 0;
-        }
-
-}
+    _cmsIOPrintf(m, "%02x", b);
+    _cmsPSActualColumn += 2;
 
-// Does write a formatted string. Guaranteed to be 2048 bytes at most.
-static
-void Writef(LPMEMSTREAM m, const char *frm, ...)
-{
-        va_list args;
-        LPBYTE pt;
-        BYTE Buffer[2048];
-
-        va_start(args, frm);
+    if (_cmsPSActualColumn > MAXPSCOLS) {
 
-        vsnprintf((char*) Buffer, 2048, frm, args);
-
-        for (pt = Buffer; *pt; pt++)  {
-
-            WriteRawByte(m, *pt);
-        }
-
-        va_end(args);
+        _cmsIOPrintf(m, "\n");
+        _cmsPSActualColumn = 0;
+    }
 }
 
-
-
 // ----------------------------------------------------------------- PostScript generation
 
 
@@ -466,21 +372,31 @@
 }
 
 static
-void EmitHeader(LPMEMSTREAM m, const char* Title, cmsHPROFILE hProfile)
+void EmitHeader(cmsIOHANDLER* m, const char* Title, cmsHPROFILE hProfile)
 {
-
     time_t timer;
+    cmsMLU *Description, *Copyright;
+    char DescASCII[256], CopyrightASCII[256];
 
     time(&timer);
 
-    Writef(m, "%%!PS-Adobe-3.0\n");
-    Writef(m, "%%\n");
-    Writef(m, "%% %s\n", Title);
-    Writef(m, "%% Source: %s\n", RemoveCR(cmsTakeProductName(hProfile)));
-    Writef(m, "%% Description: %s\n", RemoveCR(cmsTakeProductDesc(hProfile)));
-    Writef(m, "%% Created: %s", ctime(&timer)); // ctime appends a \n!!!
-    Writef(m, "%%\n");
-    Writef(m, "%%%%BeginResource\n");
+    Description = (cmsMLU*) cmsReadTag(hProfile, cmsSigProfileDescriptionTag);
+    Copyright   = (cmsMLU*) cmsReadTag(hProfile, cmsSigCopyrightTag);
+
+    DescASCII[0] = DescASCII[255] = 0;
+    CopyrightASCII[0] = CopyrightASCII[255] = 0;
+
+    if (Description != NULL) cmsMLUgetASCII(Description,  cmsNoLanguage, cmsNoCountry, DescASCII,       255);
+    if (Copyright != NULL)   cmsMLUgetASCII(Copyright,    cmsNoLanguage, cmsNoCountry, CopyrightASCII,  255);
+
+    _cmsIOPrintf(m, "%%!PS-Adobe-3.0\n");
+    _cmsIOPrintf(m, "%%\n");
+    _cmsIOPrintf(m, "%% %s\n", Title);
+    _cmsIOPrintf(m, "%% Source: %s\n", RemoveCR(DescASCII));
+    _cmsIOPrintf(m, "%%         %s\n", RemoveCR(CopyrightASCII));
+    _cmsIOPrintf(m, "%% Created: %s", ctime(&timer)); // ctime appends a \n!!!
+    _cmsIOPrintf(m, "%%\n");
+    _cmsIOPrintf(m, "%%%%BeginResource\n");
 
 }
 
@@ -489,31 +405,31 @@
 // Black point adapted to D50.
 
 static
-void EmitWhiteBlackD50(LPMEMSTREAM m, LPcmsCIEXYZ BlackPoint)
+void EmitWhiteBlackD50(cmsIOHANDLER* m, cmsCIEXYZ* BlackPoint)
 {
 
-    Writef(m, "/BlackPoint [%f %f %f]\n", BlackPoint -> X,
+    _cmsIOPrintf(m, "/BlackPoint [%f %f %f]\n", BlackPoint -> X,
                                           BlackPoint -> Y,
                                           BlackPoint -> Z);
 
-    Writef(m, "/WhitePoint [%f %f %f]\n", cmsD50_XYZ()->X,
+    _cmsIOPrintf(m, "/WhitePoint [%f %f %f]\n", cmsD50_XYZ()->X,
                                           cmsD50_XYZ()->Y,
                                           cmsD50_XYZ()->Z);
 }
 
 
 static
-void EmitRangeCheck(LPMEMSTREAM m)
+void EmitRangeCheck(cmsIOHANDLER* m)
 {
-    Writef(m, "dup 0.0 lt { pop 0.0 } if "
-              "dup 1.0 gt { pop 1.0 } if ");
+    _cmsIOPrintf(m, "dup 0.0 lt { pop 0.0 } if "
+                    "dup 1.0 gt { pop 1.0 } if ");
 
 }
 
 // Does write the intent
 
 static
-void EmitIntent(LPMEMSTREAM m, int RenderingIntent)
+void EmitIntent(cmsIOHANDLER* m, int RenderingIntent)
 {
     const char *intent;
 
@@ -527,7 +443,7 @@
         default: intent = "Undefined"; break;
     }
 
-    Writef(m, "/RenderingIntent (%s)\n", intent );
+    _cmsIOPrintf(m, "/RenderingIntent (%s)\n", intent );
 }
 
 //
@@ -539,9 +455,9 @@
 
 /*
 static
-void EmitL2Y(LPMEMSTREAM m)
+void EmitL2Y(cmsIOHANDLER* m)
 {
-    Writef(m,
+    _cmsIOPrintf(m,
             "{ "
                 "100 mul 16 add 116 div "               // (L * 100 + 16) / 116
                  "dup 6 29 div ge "                     // >= 6 / 29 ?
@@ -555,21 +471,21 @@
 // Lab -> XYZ, see the discussion above
 
 static
-void EmitLab2XYZ(LPMEMSTREAM m)
+void EmitLab2XYZ(cmsIOHANDLER* m)
 {
-    Writef(m, "/RangeABC [ 0 1 0 1 0 1]\n");
-    Writef(m, "/DecodeABC [\n");
-    Writef(m, "{100 mul  16 add 116 div } bind\n");
-    Writef(m, "{255 mul 128 sub 500 div } bind\n");
-    Writef(m, "{255 mul 128 sub 200 div } bind\n");
-    Writef(m, "]\n");
-    Writef(m, "/MatrixABC [ 1 1 1 1 0 0 0 0 -1]\n");
-    Writef(m, "/RangeLMN [ -0.236 1.254 0 1 -0.635 1.640 ]\n");
-    Writef(m, "/DecodeLMN [\n");
-    Writef(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.964200 mul} bind\n");
-    Writef(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse } bind\n");
-    Writef(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.824900 mul} bind\n");
-    Writef(m, "]\n");
+    _cmsIOPrintf(m, "/RangeABC [ 0 1 0 1 0 1]\n");
+    _cmsIOPrintf(m, "/DecodeABC [\n");
+    _cmsIOPrintf(m, "{100 mul  16 add 116 div } bind\n");
+    _cmsIOPrintf(m, "{255 mul 128 sub 500 div } bind\n");
+    _cmsIOPrintf(m, "{255 mul 128 sub 200 div } bind\n");
+    _cmsIOPrintf(m, "]\n");
+    _cmsIOPrintf(m, "/MatrixABC [ 1 1 1 1 0 0 0 0 -1]\n");
+    _cmsIOPrintf(m, "/RangeLMN [ -0.236 1.254 0 1 -0.635 1.640 ]\n");
+    _cmsIOPrintf(m, "/DecodeLMN [\n");
+    _cmsIOPrintf(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.964200 mul} bind\n");
+    _cmsIOPrintf(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse } bind\n");
+    _cmsIOPrintf(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.824900 mul} bind\n");
+    _cmsIOPrintf(m, "]\n");
 }
 
 
@@ -577,29 +493,25 @@
 // Outputs a table of words. It does use 16 bits
 
 static
-void Emit1Gamma(LPMEMSTREAM m, LPWORD Table, int nEntries)
+void Emit1Gamma(cmsIOHANDLER* m, cmsToneCurve* Table)
 {
-    int i;
-    double gamma;
+    cmsUInt32Number i;
+    cmsFloat64Number gamma;
 
 
-    if (nEntries <= 0) return;  // Empty table
+    if (Table ->nEntries <= 0) return;  // Empty table
 
     // Suppress whole if identity
-    if (cmsIsLinear(Table, nEntries)) {
-            Writef(m, "{} ");
-            return;
-    }
-
+    if (cmsIsToneCurveLinear(Table)) return;
 
     // Check if is really an exponential. If so, emit "exp"
-     gamma = cmsEstimateGammaEx(Table, nEntries, 0.001);
+    gamma = cmsEstimateGamma(Table, 0.001);
      if (gamma > 0) {
-            Writef(m, "{ %g exp } bind ", gamma);
+            _cmsIOPrintf(m, "{ %g exp } bind ", gamma);
             return;
      }
 
-    Writef(m, "{ ");
+    _cmsIOPrintf(m, "{ ");
 
     // Bounds check
     EmitRangeCheck(m);
@@ -609,94 +521,74 @@
     // PostScript code                      Stack
     // ===============                      ========================
                                             // v
-    Writef(m, " [");
+    _cmsIOPrintf(m, " [");
 
-    // TODO: Check for endianess!!!
-
-    for (i=0; i < nEntries; i++) {
-            Writef(m, "%d ", Table[i]);
+    for (i=0; i < Table->nEntries; i++) {
+        _cmsIOPrintf(m, "%d ", Table->Table16[i]);
     }
 
-    Writef(m, "] ");                        // v tab
+    _cmsIOPrintf(m, "] ");                        // v tab
 
-    Writef(m, "dup ");                      // v tab tab
-    Writef(m, "length 1 sub ");             // v tab dom
-    Writef(m, "3 -1 roll ");                // tab dom v
-    Writef(m, "mul ");                      // tab val2
-    Writef(m, "dup ");                      // tab val2 val2
-    Writef(m, "dup ");                      // tab val2 val2 val2
-    Writef(m, "floor cvi ");                // tab val2 val2 cell0
-    Writef(m, "exch ");                     // tab val2 cell0 val2
-    Writef(m, "ceiling cvi ");              // tab val2 cell0 cell1
-    Writef(m, "3 index ");                  // tab val2 cell0 cell1 tab
-    Writef(m, "exch ");                     // tab val2 cell0 tab cell1
-    Writef(m, "get ");                      // tab val2 cell0 y1
-    Writef(m, "4 -1 roll ");                // val2 cell0 y1 tab
-    Writef(m, "3 -1 roll ");                // val2 y1 tab cell0
-    Writef(m, "get ");                      // val2 y1 y0
-    Writef(m, "dup ");                      // val2 y1 y0 y0
-    Writef(m, "3 1 roll ");                 // val2 y0 y1 y0
-    Writef(m, "sub ");                      // val2 y0 (y1-y0)
-    Writef(m, "3 -1 roll ");                // y0 (y1-y0) val2
-    Writef(m, "dup ");                      // y0 (y1-y0) val2 val2
-    Writef(m, "floor cvi ");                // y0 (y1-y0) val2 floor(val2)
-    Writef(m, "sub ");                      // y0 (y1-y0) rest
-    Writef(m, "mul ");                      // y0 t1
-    Writef(m, "add ");                      // y
-    Writef(m, "65535 div ");                // result
+    _cmsIOPrintf(m, "dup ");                      // v tab tab
+    _cmsIOPrintf(m, "length 1 sub ");             // v tab dom
+    _cmsIOPrintf(m, "3 -1 roll ");                // tab dom v
+    _cmsIOPrintf(m, "mul ");                      // tab val2
+    _cmsIOPrintf(m, "dup ");                      // tab val2 val2
+    _cmsIOPrintf(m, "dup ");                      // tab val2 val2 val2
+    _cmsIOPrintf(m, "floor cvi ");                // tab val2 val2 cell0
+    _cmsIOPrintf(m, "exch ");                     // tab val2 cell0 val2
+    _cmsIOPrintf(m, "ceiling cvi ");              // tab val2 cell0 cell1
+    _cmsIOPrintf(m, "3 index ");                  // tab val2 cell0 cell1 tab
+    _cmsIOPrintf(m, "exch ");                     // tab val2 cell0 tab cell1
+    _cmsIOPrintf(m, "get ");                      // tab val2 cell0 y1
+    _cmsIOPrintf(m, "4 -1 roll ");                // val2 cell0 y1 tab
+    _cmsIOPrintf(m, "3 -1 roll ");                // val2 y1 tab cell0
+    _cmsIOPrintf(m, "get ");                      // val2 y1 y0
+    _cmsIOPrintf(m, "dup ");                      // val2 y1 y0 y0
+    _cmsIOPrintf(m, "3 1 roll ");                 // val2 y0 y1 y0
+    _cmsIOPrintf(m, "sub ");                      // val2 y0 (y1-y0)
+    _cmsIOPrintf(m, "3 -1 roll ");                // y0 (y1-y0) val2
+    _cmsIOPrintf(m, "dup ");                      // y0 (y1-y0) val2 val2
+    _cmsIOPrintf(m, "floor cvi ");                // y0 (y1-y0) val2 floor(val2)
+    _cmsIOPrintf(m, "sub ");                      // y0 (y1-y0) rest
+    _cmsIOPrintf(m, "mul ");                      // y0 t1
+    _cmsIOPrintf(m, "add ");                      // y
+    _cmsIOPrintf(m, "65535 div ");                // result
 
-    Writef(m, " } bind ");
+    _cmsIOPrintf(m, " } bind ");
 }
 
 
 // Compare gamma table
 
 static
-LCMSBOOL GammaTableEquals(LPWORD g1, LPWORD g2, int nEntries)
+cmsBool GammaTableEquals(cmsUInt16Number* g1, cmsUInt16Number* g2, int nEntries)
 {
-    return memcmp(g1, g2, nEntries* sizeof(WORD)) == 0;
+    return memcmp(g1, g2, nEntries* sizeof(cmsUInt16Number)) == 0;
 }
 
 
 // Does write a set of gamma curves
 
 static
-void EmitNGamma(LPMEMSTREAM m, int n, LPWORD g[], int nEntries)
+void EmitNGamma(cmsIOHANDLER* m, int n, cmsToneCurve* g[])
 {
     int i;
 
     for( i=0; i < n; i++ )
     {
-        if (i > 0 && GammaTableEquals(g[i-1], g[i], nEntries)) {
+        if (i > 0 && GammaTableEquals(g[i-1]->Table16, g[i]->Table16, g[i]->nEntries)) {
 
-            Writef(m, "dup ");
+            _cmsIOPrintf(m, "dup ");
         }
         else {
-            Emit1Gamma(m, g[i], nEntries);
+            Emit1Gamma(m, g[i]);
         }
     }
 
 }
 
 
-// Check whatever a profile has CLUT tables (only on input)
-
-static
-LCMSBOOL IsLUTbased(cmsHPROFILE hProfile, int Intent)
-{
-    icTagSignature Tag;
-
-    // Check if adequate tag is present
-    Tag = Device2PCSTab[Intent];
-
-    if (cmsIsTag(hProfile, Tag)) return 1;
-
-    // If not present, revert to default (perceptual)
-    Tag = icSigAToB0Tag;
-
-    // If no tag present, try matrix-shaper
-    return cmsIsTag(hProfile, Tag);
-}
 
 
 
@@ -707,19 +599,19 @@
 // that is, the callback will be called for each knot with
 //
 //          In[]  The grid location coordinates, normalized to 0..ffff
-//          Out[] The LUT values, normalized to 0..ffff
+//          Out[] The Pipeline values, normalized to 0..ffff
 //
 //  Returning a value other than 0 does terminate the sampling process
 //
-//  Each row contains LUT values for all but first component. So, I
+//  Each row contains Pipeline values for all but first component. So, I
 //  detect row changing by keeping a copy of last value of first
 //  component. -1 is used to mark begining of whole block.
 
 static
-int OutputValueSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
+int OutputValueSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
 {
-    LPSAMPLERCARGO sc = (LPSAMPLERCARGO) Cargo;
-    unsigned int i;
+    cmsPsSamplerCargo* sc = (cmsPsSamplerCargo*) Cargo;
+    cmsUInt32Number i;
 
 
     if (sc -> FixWhite) {
@@ -729,14 +621,14 @@
             if ((In[1] >= 0x7800 && In[1] <= 0x8800) &&
                 (In[2] >= 0x7800 && In[2] <= 0x8800)) {
 
-                WORD* Black;
-                WORD* White;
-                int nOutputs;
+                cmsUInt16Number* Black;
+                cmsUInt16Number* White;
+                cmsUInt32Number nOutputs;
 
                 if (!_cmsEndPointsBySpace(sc ->ColorSpace, &White, &Black, &nOutputs))
                         return 0;
 
-                for (i=0; i < (unsigned int) nOutputs; i++)
+                for (i=0; i < nOutputs; i++)
                         Out[i] = White[i];
             }
 
@@ -751,15 +643,15 @@
 
             if (sc ->FirstComponent != -1) {
 
-                    Writef(sc ->m, sc ->PostMin);
+                    _cmsIOPrintf(sc ->m, sc ->PostMin);
                     sc ->SecondComponent = -1;
-                    Writef(sc ->m, sc ->PostMaj);
+                    _cmsIOPrintf(sc ->m, sc ->PostMaj);
             }
 
             // Begin block
-            sc->m->Col = 0;
+            _cmsPSActualColumn = 0;
 
-            Writef(sc ->m, sc ->PreMaj);
+            _cmsIOPrintf(sc ->m, sc ->PreMaj);
             sc ->FirstComponent = In[0];
     }
 
@@ -768,96 +660,66 @@
 
             if (sc ->SecondComponent != -1) {
 
-                    Writef(sc ->m, sc ->PostMin);
+                    _cmsIOPrintf(sc ->m, sc ->PostMin);
             }
 
-            Writef(sc ->m, sc ->PreMin);
+            _cmsIOPrintf(sc ->m, sc ->PreMin);
             sc ->SecondComponent = In[1];
     }
 
-
-
-    // Dump table. Could be Word or byte based on
-    // depending on bps member (16 bps mode is not currently
-    // being used at all, but is here for future ampliations)
-
-    for (i=0; i < sc -> Lut ->OutputChan; i++) {
+      // Dump table.
 
-        WORD wWordOut = Out[i];
-
-        if (sc ->bps == 8) {
+      for (i=0; i < sc -> Pipeline ->Params->nOutputs; i++) {
 
-            // Value as byte
-            BYTE wByteOut;
-
-            // If is input, convert from Lab2 to Lab4 (just divide by 256)
+          cmsUInt16Number wWordOut = Out[i];
+          cmsUInt8Number wByteOut;           // Value as byte
 
-            if (sc ->lIsInput) {
-
-
-                wByteOut = L2Byte(wWordOut);
-            }
-            else
-                wByteOut = Word2Byte(wWordOut);
+          // We always deal with Lab4
 
-            WriteByte(sc -> m, wByteOut);
-        }
-        else {
+          wByteOut = Word2Byte(wWordOut);
+          WriteByte(sc -> m, wByteOut);
+      }
 
-            // Value as word
-            WriteByte(sc -> m, (BYTE) (wWordOut & 0xFF));
-            WriteByte(sc -> m, (BYTE) ((wWordOut >> 8) & 0xFF));
-        }
-     }
-
-    return 1;
+      return 1;
 }
 
-// Writes a LUT on memstream. Could be 8 or 16 bits based
+// Writes a Pipeline on memstream. Could be 8 or 16 bits based
 
 static
-void WriteCLUT(LPMEMSTREAM m, LPLUT Lut, int bps, const char* PreMaj,
-                                                  const char* PostMaj,
-                                                  const char* PreMin,
-                                                  const char* PostMin,
-                                                  int lIsInput,
-                                                  int FixWhite,
-                                                  icColorSpaceSignature ColorSpace)
+void WriteCLUT(cmsIOHANDLER* m, cmsStage* mpe, const char* PreMaj,
+                                             const char* PostMaj,
+                                             const char* PreMin,
+                                             const char* PostMin,
+                                             int FixWhite,
+                                             cmsColorSpaceSignature ColorSpace)
 {
-    unsigned int i;
-    SAMPLERCARGO sc;
+    cmsUInt32Number i;
+    cmsPsSamplerCargo sc;
 
     sc.FirstComponent = -1;
     sc.SecondComponent = -1;
-    sc.Lut = Lut;
+    sc.Pipeline = (_cmsStageCLutData *) mpe ->Data;
     sc.m   = m;
-    sc.bps = bps;
     sc.PreMaj = PreMaj;
     sc.PostMaj= PostMaj;
 
     sc.PreMin   = PreMin;
     sc.PostMin  = PostMin;
-    sc.lIsInput = lIsInput;
     sc.FixWhite = FixWhite;
     sc.ColorSpace = ColorSpace;
 
-    Writef(m, "[");
+    _cmsIOPrintf(m, "[");
 
-    for (i=0; i < Lut ->InputChan; i++)
-            Writef(m, " %d ", Lut ->cLutPoints);
-
-    Writef(m, " [\n");
-
-
+    for (i=0; i < sc.Pipeline->Params->nInputs; i++)
+        _cmsIOPrintf(m, " %d ", sc.Pipeline->Params->nSamples[i]);
 
-    cmsSample3DGrid(Lut, OutputValueSampler, (LPVOID) &sc, SAMPLER_INSPECT);
+    _cmsIOPrintf(m, " [\n");
 
+    cmsStageSampleCLut16bit(mpe, OutputValueSampler, (void*) &sc, SAMPLER_INSPECT);
 
-    Writef(m, PostMin);
-    Writef(m, PostMaj);
-    Writef(m, "] ");
-
-
+    _cmsIOPrintf(m, PostMin);
+    _cmsIOPrintf(m, PostMaj);
+    _cmsIOPrintf(m, "] ");
 
 }
 
@@ -865,89 +727,92 @@
 // Dumps CIEBasedA Color Space Array
 
 static
-int EmitCIEBasedA(LPMEMSTREAM m, LPWORD Tab, int nEntries, LPcmsCIEXYZ BlackPoint)
+int EmitCIEBasedA(cmsIOHANDLER* m, cmsToneCurve* Curve, cmsCIEXYZ* BlackPoint)
 {
 
-        Writef(m, "[ /CIEBasedA\n");
-        Writef(m, "  <<\n");
+    _cmsIOPrintf(m, "[ /CIEBasedA\n");
+    _cmsIOPrintf(m, "  <<\n");
 
-        Writef(m, "/DecodeA ");
+    _cmsIOPrintf(m, "/DecodeA ");
 
-        Emit1Gamma(m,Tab, nEntries);
+    Emit1Gamma(m, Curve);
 
-        Writef(m, " \n");
+    _cmsIOPrintf(m, " \n");
 
-        Writef(m, "/MatrixA [ 0.9642 1.0000 0.8249 ]\n");
-        Writef(m, "/RangeLMN [ 0.0 0.9642 0.0 1.0000 0.0 0.8249 ]\n");
+    _cmsIOPrintf(m, "/MatrixA [ 0.9642 1.0000 0.8249 ]\n");
+    _cmsIOPrintf(m, "/RangeLMN [ 0.0 0.9642 0.0 1.0000 0.0 0.8249 ]\n");
 
-        EmitWhiteBlackD50(m, BlackPoint);
-        EmitIntent(m, INTENT_PERCEPTUAL);
+    EmitWhiteBlackD50(m, BlackPoint);
+    EmitIntent(m, INTENT_PERCEPTUAL);
 
-        Writef(m, ">>\n");
-        Writef(m, "]\n");
+    _cmsIOPrintf(m, ">>\n");
+    _cmsIOPrintf(m, "]\n");
 
-        return 1;
+    return 1;
 }
 
 
 // Dumps CIEBasedABC Color Space Array
 
 static
-int EmitCIEBasedABC(LPMEMSTREAM m, LPWORD L[], int nEntries, LPWMAT3 Matrix, LPcmsCIEXYZ BlackPoint)
+int EmitCIEBasedABC(cmsIOHANDLER* m, cmsFloat64Number* Matrix, cmsToneCurve** CurveSet, cmsCIEXYZ* BlackPoint)
 {
     int i;
 
-        Writef(m, "[ /CIEBasedABC\n");
-        Writef(m, "<<\n");
-        Writef(m, "/DecodeABC [ ");
+    _cmsIOPrintf(m, "[ /CIEBasedABC\n");
+    _cmsIOPrintf(m, "<<\n");
+    _cmsIOPrintf(m, "/DecodeABC [ ");
 
-        EmitNGamma(m, 3, L, nEntries);
+    EmitNGamma(m, 3, CurveSet);
 
-        Writef(m, "]\n");
+    _cmsIOPrintf(m, "]\n");
 
-        Writef(m, "/MatrixABC [ " );
+    _cmsIOPrintf(m, "/MatrixABC [ " );
 
-        for( i=0; i < 3; i++ ) {
+    for( i=0; i < 3; i++ ) {
 
-            Writef(m, "%.6f %.6f %.6f ",
-                        FIXED_TO_DOUBLE(Matrix->v[0].n[i]),
-                        FIXED_TO_DOUBLE(Matrix->v[1].n[i]),
-                        FIXED_TO_DOUBLE(Matrix->v[2].n[i]));
-        }
+        _cmsIOPrintf(m, "%.6f %.6f %.6f ", Matrix[0 + 3*i],
+                     Matrix[1 + 3*i],
+                     Matrix[2 + 3*i]);
+    }
 
 
-        Writef(m, "]\n");
+    _cmsIOPrintf(m, "]\n");
 
-        Writef(m, "/RangeLMN [ 0.0 0.9642 0.0 1.0000 0.0 0.8249 ]\n");
+    _cmsIOPrintf(m, "/RangeLMN [ 0.0 0.9642 0.0 1.0000 0.0 0.8249 ]\n");
 
-        EmitWhiteBlackD50(m, BlackPoint);
-        EmitIntent(m, INTENT_PERCEPTUAL);
+    EmitWhiteBlackD50(m, BlackPoint);
+    EmitIntent(m, INTENT_PERCEPTUAL);
 
-        Writef(m, ">>\n");
-        Writef(m, "]\n");
+    _cmsIOPrintf(m, ">>\n");
+    _cmsIOPrintf(m, "]\n");
 
 
-        return 1;
+    return 1;
 }
 
 
 static
-int EmitCIEBasedDEF(LPMEMSTREAM m, LPLUT Lut, int Intent, LPcmsCIEXYZ BlackPoint)
+int EmitCIEBasedDEF(cmsIOHANDLER* m, cmsPipeline* Pipeline, int Intent, cmsCIEXYZ* BlackPoint)
 {
     const char* PreMaj;
     const char* PostMaj;
     const char* PreMin, *PostMin;
+    cmsStage* mpe;
 
-    switch (Lut ->InputChan) {
+    mpe = Pipeline ->Elements;
+
+
+    switch (cmsStageInputChannels(mpe)) {
     case 3:
 
-            Writef(m, "[ /CIEBasedDEF\n");
+            _cmsIOPrintf(m, "[ /CIEBasedDEF\n");
             PreMaj ="<";
             PostMaj= ">\n";
             PreMin = PostMin = "";
             break;
     case 4:
-            Writef(m, "[ /CIEBasedDEFG\n");
+            _cmsIOPrintf(m, "[ /CIEBasedDEFG\n");
             PreMaj = "[";
             PostMaj = "]\n";
             PreMin = "<";
@@ -958,30 +823,32 @@
 
     }
 
-    Writef(m, "<<\n");
+    _cmsIOPrintf(m, "<<\n");
 
-    if (Lut ->wFlags & LUT_HASTL1) {
+    if (cmsStageType(mpe) == cmsSigCurveSetElemType) {
 
-        Writef(m, "/DecodeDEF [ ");
-        EmitNGamma(m, Lut ->InputChan, Lut ->L1, Lut ->CLut16params.nSamples);
-        Writef(m, "]\n");
+        _cmsIOPrintf(m, "/DecodeDEF [ ");
+        EmitNGamma(m, cmsStageOutputChannels(mpe), _cmsStageGetPtrToCurveSet(mpe));
+        _cmsIOPrintf(m, "]\n");
+
+        mpe = mpe ->Next;
     }
 
 
 
-    if (Lut ->wFlags & LUT_HAS3DGRID) {
+    if (cmsStageType(mpe) == cmsSigCLutElemType) {
 
-            Writef(m, "/Table ");
-            WriteCLUT(m, Lut, 8, PreMaj, PostMaj, PreMin, PostMin, TRUE, FALSE, (icColorSpaceSignature) 0);
-            Writef(m, "]\n");
+            _cmsIOPrintf(m, "/Table ");
+            WriteCLUT(m, mpe, PreMaj, PostMaj, PreMin, PostMin, FALSE, (cmsColorSpaceSignature) 0);
+            _cmsIOPrintf(m, "]\n");
     }
 
     EmitLab2XYZ(m);
     EmitWhiteBlackD50(m, BlackPoint);
     EmitIntent(m, Intent);
 
-    Writef(m, "   >>\n");
-    Writef(m, "]\n");
+    _cmsIOPrintf(m, "   >>\n");
+    _cmsIOPrintf(m, "]\n");
 
 
     return 1;
@@ -990,21 +857,21 @@
 // Generates a curve from a gray profile
 
 static
-LPGAMMATABLE ExtractGray2Y(cmsHPROFILE hProfile, int Intent)
+cmsToneCurve* ExtractGray2Y(cmsContext ContextID, cmsHPROFILE hProfile, int Intent)
 {
-    LPGAMMATABLE Out = cmsAllocGamma(256);
-    cmsHPROFILE hXYZ = cmsCreateXYZProfile();
-    cmsHTRANSFORM xform = cmsCreateTransform(hProfile, TYPE_GRAY_8, hXYZ, TYPE_XYZ_DBL, Intent, cmsFLAGS_NOTPRECALC);
+    cmsToneCurve* Out = cmsBuildTabulatedToneCurve16(ContextID, 256, NULL);
+    cmsHPROFILE hXYZ  = cmsCreateXYZProfile();
+    cmsHTRANSFORM xform = cmsCreateTransformTHR(ContextID, hProfile, TYPE_GRAY_8, hXYZ, TYPE_XYZ_DBL, Intent, cmsFLAGS_NOOPTIMIZE);
     int i;
 
     for (i=0; i < 256; i++) {
 
-      BYTE Gray = (BYTE) i;
+      cmsUInt8Number Gray = (cmsUInt8Number) i;
       cmsCIEXYZ XYZ;
 
         cmsDoTransform(xform, &Gray, &XYZ, 1);
 
-        Out ->GammaTable[i] =_cmsClampWord((int) floor(XYZ.Y * 65535.0 + 0.5));
+        Out ->Table16[i] =_cmsQuickSaturateWord(XYZ.Y * 65535.0);
     }
 
     cmsDeleteTransform(xform);
@@ -1014,17 +881,16 @@
 
 
 
-// Because PostScrip has only 8 bits in /Table, we should use
+// Because PostScript has only 8 bits in /Table, we should use
 // a more perceptually uniform space... I do choose Lab.
 
 static
-int WriteInputLUT(LPMEMSTREAM m, cmsHPROFILE hProfile, int Intent)
+int WriteInputLUT(cmsIOHANDLER* m, cmsHPROFILE hProfile, int Intent, cmsUInt32Number dwFlags)
 {
     cmsHPROFILE hLab;
     cmsHTRANSFORM xform;
-    icColorSpaceSignature ColorSpace;
-    int nChannels;
-    DWORD InputFormat;
+    cmsUInt32Number nChannels;
+    cmsUInt32Number InputFormat;
     int rc;
     cmsHPROFILE Profiles[2];
     cmsCIEXYZ BlackPointAdaptedToD50;
@@ -1032,49 +898,25 @@
     // Does create a device-link based transform.
     // The DeviceLink is next dumped as working CSA.
 
-    hLab        = cmsCreateLabProfile(NULL);
-    ColorSpace  =  cmsGetColorSpace(hProfile);
-    nChannels   = _cmsChannelsOf(ColorSpace);
-    InputFormat = CHANNELS_SH(nChannels) | BYTES_SH(2);
-
-    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, Intent,LCMS_BPFLAGS_D50_ADAPTED);
-
-    // Is a devicelink profile?
-    if (cmsGetDeviceClass(hProfile) == icSigLinkClass) {
-
-        // if devicelink output already Lab, use it directly
-
-        if (cmsGetPCS(hProfile) == icSigLabData) {
-
-            xform = cmsCreateTransform(hProfile, InputFormat, NULL,
-                            TYPE_Lab_DBL, Intent, 0);
-        }
-        else {
-
-            // Nope, adjust output to Lab if possible
-
-            Profiles[0] = hProfile;
-            Profiles[1] = hLab;
-
-            xform = cmsCreateMultiprofileTransform(Profiles, 2,  InputFormat,
-                                    TYPE_Lab_DBL, Intent, 0);
-        }
+    InputFormat = cmsFormatterForColorspaceOfProfile(hProfile, 2, FALSE);
+    nChannels   = T_CHANNELS(InputFormat);
 
 
-    }
-    else {
+    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, Intent, 0);
+
+    // Adjust output to Lab4
+    hLab = cmsCreateLab4ProfileTHR(m ->ContextID, NULL);
 
-        // This is a normal profile
-        xform = cmsCreateTransform(hProfile, InputFormat, hLab,
-                            TYPE_Lab_DBL, Intent, 0);
-    }
+    Profiles[0] = hProfile;
+    Profiles[1] = hLab;
 
-
+    xform = cmsCreateMultiprofileTransform(Profiles, 2,  InputFormat, TYPE_Lab_DBL, Intent, 0);
+    cmsCloseProfile(hLab);
 
     if (xform == NULL) {
 
-            cmsSignalError(LCMS_ERRC_ABORTED, "Cannot create transform Profile -> Lab");
-            return 0;
+        cmsSignalError(m ->ContextID, cmsERROR_COLORSPACE_CHECK, "Cannot create transform Profile -> Lab");
+        return 0;
     }
 
     // Only 1, 3 and 4 channels are allowed
@@ -1082,86 +924,82 @@
     switch (nChannels) {
 
     case 1: {
-            LPGAMMATABLE Gray2Y = ExtractGray2Y(hProfile, Intent);
-            EmitCIEBasedA(m, Gray2Y->GammaTable, Gray2Y ->nEntries, &BlackPointAdaptedToD50);
-            cmsFreeGamma(Gray2Y);
+        cmsToneCurve* Gray2Y = ExtractGray2Y(m ->ContextID, hProfile, Intent);
+            EmitCIEBasedA(m, Gray2Y, &BlackPointAdaptedToD50);
+            cmsFreeToneCurve(Gray2Y);
             }
             break;
 
     case 3:
     case 4: {
-            LPLUT DeviceLink;
-            _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
+        cmsUInt32Number OutFrm = TYPE_Lab_16;
+            cmsPipeline* DeviceLink;
+            _cmsTRANSFORM* v = (_cmsTRANSFORM*) xform;
 
-            if (v ->DeviceLink)
-                rc = EmitCIEBasedDEF(m, v->DeviceLink, Intent, &BlackPointAdaptedToD50);
-            else {
-                DeviceLink = _cmsPrecalculateDeviceLink(xform, 0);
-                rc = EmitCIEBasedDEF(m, DeviceLink, Intent, &BlackPointAdaptedToD50);
-                cmsFreeLUT(DeviceLink);
-            }
+            DeviceLink = cmsPipelineDup(v ->Lut);
+            if (DeviceLink == NULL) return 0;
+
+            dwFlags |= cmsFLAGS_FORCE_CLUT;
+            _cmsOptimizePipeline(&DeviceLink, Intent, &InputFormat, &OutFrm, &dwFlags);
+
+            rc = EmitCIEBasedDEF(m, DeviceLink, Intent, &BlackPointAdaptedToD50);
+            cmsPipelineFree(DeviceLink);
             }
             break;
 
     default:
 
-            cmsSignalError(LCMS_ERRC_ABORTED, "Only 3, 4 channels supported for CSA. This profile has %d channels.", nChannels);
-            return 0;
+        cmsSignalError(m ->ContextID, cmsERROR_COLORSPACE_CHECK, "Only 3, 4 channels supported for CSA. This profile has %d channels.", nChannels);
+        return 0;
     }
 
 
     cmsDeleteTransform(xform);
-    cmsCloseProfile(hLab);
+
     return 1;
 }
 
+static
+cmsFloat64Number* GetPtrToMatrix(const cmsStage* mpe)
+{
+    _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
+
+    return Data -> Double;
+}
 
 
 // Does create CSA based on matrix-shaper. Allowed types are gray and RGB based
 
 static
-int WriteInputMatrixShaper(LPMEMSTREAM m, cmsHPROFILE hProfile)
+int WriteInputMatrixShaper(cmsIOHANDLER* m, cmsHPROFILE hProfile, cmsStage* Matrix, cmsStage* Shaper)
 {
-    icColorSpaceSignature ColorSpace;
-    LPMATSHAPER MatShaper;
+    cmsColorSpaceSignature ColorSpace;
     int rc;
     cmsCIEXYZ BlackPointAdaptedToD50;
 
-
     ColorSpace = cmsGetColorSpace(hProfile);
-    MatShaper  = cmsBuildInputMatrixShaper(hProfile);
 
-    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, INTENT_RELATIVE_COLORIMETRIC, LCMS_BPFLAGS_D50_ADAPTED);
-
-    if (MatShaper == NULL) {
+    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, INTENT_RELATIVE_COLORIMETRIC, 0);
 
-                cmsSignalError(LCMS_ERRC_ABORTED, "This profile is not suitable for input");
-                return 0;
-    }
+    if (ColorSpace == cmsSigGrayData) {
 
-    if (ColorSpace == icSigGrayData) {
-
-            rc = EmitCIEBasedA(m, MatShaper ->L[0],
-                                  MatShaper ->p16.nSamples,
-                                  &BlackPointAdaptedToD50);
+        cmsToneCurve** ShaperCurve = _cmsStageGetPtrToCurveSet(Shaper);
+            rc = EmitCIEBasedA(m, ShaperCurve[0], &BlackPointAdaptedToD50);
 
     }
     else
-        if (ColorSpace == icSigRgbData) {
-
+        if (ColorSpace == cmsSigRgbData) {
 
-            rc = EmitCIEBasedABC(m, MatShaper->L,
-                                        MatShaper ->p16.nSamples,
-                                        &MatShaper ->Matrix,
-                                        &BlackPointAdaptedToD50);
+            rc = EmitCIEBasedABC(m,  GetPtrToMatrix(Matrix),
+                                 _cmsStageGetPtrToCurveSet(Shaper),
+                                 &BlackPointAdaptedToD50);
         }
         else  {
 
-            cmsSignalError(LCMS_ERRC_ABORTED, "Profile is not suitable for CSA. Unsupported colorspace.");
+            cmsSignalError(m ->ContextID, cmsERROR_COLORSPACE_CHECK, "Profile is not suitable for CSA. Unsupported colorspace.");
             return 0;
         }
 
-    cmsFreeMatShaper(MatShaper);
     return rc;
 }
 
@@ -1171,45 +1009,46 @@
 // This is a HP extension, and it works in Lab instead of XYZ
 
 static
-int WriteNamedColorCSA(LPMEMSTREAM m, cmsHPROFILE hNamedColor, int Intent)
+int WriteNamedColorCSA(cmsIOHANDLER* m, cmsHPROFILE hNamedColor, int Intent)
 {
     cmsHTRANSFORM xform;
     cmsHPROFILE   hLab;
     int i, nColors;
     char ColorName[32];
-
+    cmsNAMEDCOLORLIST* NamedColorList;
 
-    hLab  = cmsCreateLabProfile(NULL);
-    xform = cmsCreateTransform(hNamedColor, TYPE_NAMED_COLOR_INDEX,
-                        hLab, TYPE_Lab_DBL, Intent, cmsFLAGS_NOTPRECALC);
+    hLab  = cmsCreateLab4ProfileTHR(m ->ContextID, NULL);
+    xform = cmsCreateTransform(hNamedColor, TYPE_NAMED_COLOR_INDEX, hLab, TYPE_Lab_DBL, Intent, 0);
     if (xform == NULL) return 0;
 
+    NamedColorList = cmsGetNamedColorList(xform);
+    if (NamedColorList == NULL) return 0;
 
-    Writef(m, "<<\n");
-    Writef(m, "(colorlistcomment) (%s)\n", "Named color CSA");
-    Writef(m, "(Prefix) [ (Pantone ) (PANTONE ) ]\n");
-    Writef(m, "(Suffix) [ ( CV) ( CVC) ( C) ]\n");
+    _cmsIOPrintf(m, "<<\n");
+    _cmsIOPrintf(m, "(colorlistcomment) (%s)\n", "Named color CSA");
+    _cmsIOPrintf(m, "(Prefix) [ (Pantone ) (PANTONE ) ]\n");
+    _cmsIOPrintf(m, "(Suffix) [ ( CV) ( CVC) ( C) ]\n");
 
-    nColors   = cmsNamedColorCount(xform);
+    nColors   = cmsNamedColorCount(NamedColorList);
 
 
     for (i=0; i < nColors; i++) {
 
-        WORD In[1];
+        cmsUInt16Number In[1];
         cmsCIELab Lab;
 
-        In[0] = (WORD) i;
+        In[0] = (cmsUInt16Number) i;
 
-        if (!cmsNamedColorInfo(xform, i, ColorName, NULL, NULL))
+        if (!cmsNamedColorInfo(NamedColorList, i, ColorName, NULL, NULL, NULL, NULL))
                 continue;
 
         cmsDoTransform(xform, In, &Lab, 1);
-        Writef(m, "  (%s) [ %.3f %.3f %.3f ]\n", ColorName, Lab.L, Lab.a, Lab.b);
+        _cmsIOPrintf(m, "  (%s) [ %.3f %.3f %.3f ]\n", ColorName, Lab.L, Lab.a, Lab.b);
     }
 
 
 
-    Writef(m, ">>\n");
+    _cmsIOPrintf(m, ">>\n");
 
     cmsDeleteTransform(xform);
     cmsCloseProfile(hLab);
@@ -1218,75 +1057,68 @@
 
 
 // Does create a Color Space Array on XYZ colorspace for PostScript usage
-
-DWORD LCMSEXPORT cmsGetPostScriptCSA(cmsHPROFILE hProfile,
-                              int Intent,
-                              LPVOID Buffer, DWORD dwBufferLen)
+static
+cmsUInt32Number GenerateCSA(cmsContext ContextID,
+                            cmsHPROFILE hProfile,
+                            cmsUInt32Number Intent,
+                            cmsUInt32Number dwFlags,
+                            cmsIOHANDLER* mem)
 {
-
-    LPMEMSTREAM mem;
-    DWORD dwBytesUsed;
-
-    // Set up the serialization engine
-    mem = CreateMemStream((LPBYTE) Buffer, dwBufferLen, MAXPSCOLS);
-    if (!mem) return 0;
+    cmsUInt32Number dwBytesUsed;
+    cmsPipeline* lut = NULL;
+    cmsStage* Matrix, *Shaper;
 
 
     // Is a named color profile?
-    if (cmsGetDeviceClass(hProfile) == icSigNamedColorClass) {
-
-        if (!WriteNamedColorCSA(mem, hProfile, Intent)) {
+    if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
 
-                    _cmsFree((void*) mem);
-                    return 0;
-        }
+        if (!WriteNamedColorCSA(mem, hProfile, Intent)) goto Error;
     }
     else {
 
 
-    // Any profile class are allowed (including devicelink), but
-    // output (PCS) colorspace must be XYZ or Lab
-    icColorSpaceSignature ColorSpace = cmsGetPCS(hProfile);
-
-    if (ColorSpace != icSigXYZData &&
-        ColorSpace != icSigLabData) {
+        // Any profile class are allowed (including devicelink), but
+        // output (PCS) colorspace must be XYZ or Lab
+        cmsColorSpaceSignature ColorSpace = cmsGetPCS(hProfile);
 
-            cmsSignalError(LCMS_ERRC_ABORTED, "Invalid output color space");
-            _cmsFree((void*) mem);
-            return 0;
-    }
+        if (ColorSpace != cmsSigXYZData &&
+            ColorSpace != cmsSigLabData) {
 
-    // Is there any CLUT?
-    if (IsLUTbased(hProfile, Intent)) {
+            cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "Invalid output color space");
+            goto Error;
+        }
+
 
-        // Yes, so handle as LUT-based
-        if (!WriteInputLUT(mem, hProfile, Intent)) {
+        // Read the lut with all necessary conversion stages
+        lut = _cmsReadInputLUT(hProfile, Intent);
+        if (lut == NULL) goto Error;
 
-                    _cmsFree((void*) mem);
-                    return 0;
-        }
-    }
-    else {
+
+        // Tone curves + matrix can be implemented without any LUT
+        if (cmsPipelineCheckAndRetreiveStages(lut, 2, cmsSigCurveSetElemType, cmsSigMatrixElemType, &Shaper, &Matrix)) {
 
-        // No, try Matrix-shaper (this only works on XYZ)
-
-        if (!WriteInputMatrixShaper(mem, hProfile)) {
+            if (!WriteInputMatrixShaper(mem, hProfile, Matrix, Shaper)) goto Error;
 
-                    _cmsFree((void*) mem);  // Something went wrong
-                    return 0;
         }
-    }
+        else {
+            // We need a LUT for the rest
+            if (!WriteInputLUT(mem, hProfile, Intent, dwFlags)) goto Error;
+        }
     }
 
 
     // Done, keep memory usage
-    dwBytesUsed = mem ->dwUsed;
+    dwBytesUsed = mem ->UsedSpace;
 
-    // Get rid of memory stream
-    _cmsFree((void*) mem);
+    // Get rid of LUT
+    if (lut != NULL) cmsPipelineFree(lut);
 
     // Finally, return used byte count
     return dwBytesUsed;
+
+Error:
+    if (lut != NULL) cmsPipelineFree(lut);
+    return 0;
 }
 
 // ------------------------------------------------------ Color Rendering Dictionary (CRD)
@@ -1356,45 +1188,45 @@
 
 
 static
-void EmitPQRStage(LPMEMSTREAM m, cmsHPROFILE hProfile, int DoBPC, int lIsAbsolute)
+void EmitPQRStage(cmsIOHANDLER* m, cmsHPROFILE hProfile, int DoBPC, int lIsAbsolute)
 {
 
 
         if (lIsAbsolute) {
 
             // For absolute colorimetric intent, encode back to relative
-            // and generate a relative LUT
+            // and generate a relative Pipeline
 
             // Relative encoding is obtained across XYZpcs*(D50/WhitePoint)
 
             cmsCIEXYZ White;
 
-            cmsTakeMediaWhitePoint(&White, hProfile);
+            _cmsReadMediaWhitePoint(&White, hProfile);
 
-            Writef(m,"/MatrixPQR [1 0 0 0 1 0 0 0 1 ]\n");
-            Writef(m,"/RangePQR [ -0.5 2 -0.5 2 -0.5 2 ]\n");
+            _cmsIOPrintf(m,"/MatrixPQR [1 0 0 0 1 0 0 0 1 ]\n");
+            _cmsIOPrintf(m,"/RangePQR [ -0.5 2 -0.5 2 -0.5 2 ]\n");
 
-            Writef(m, "%% Absolute colorimetric -- encode to relative to maximize LUT usage\n"
+            _cmsIOPrintf(m, "%% Absolute colorimetric -- encode to relative to maximize LUT usage\n"
                       "/TransformPQR [\n"
                       "{0.9642 mul %g div exch pop exch pop exch pop exch pop} bind\n"
                       "{1.0000 mul %g div exch pop exch pop exch pop exch pop} bind\n"
                       "{0.8249 mul %g div exch pop exch pop exch pop exch pop} bind\n]\n",
-                      White.X, White.Y, White.Z);
+                         White.X, White.Y, White.Z);
             return;
         }
 
 
-        Writef(m,"%% Bradford Cone Space\n"
+        _cmsIOPrintf(m,"%% Bradford Cone Space\n"
                  "/MatrixPQR [0.8951 -0.7502 0.0389 0.2664 1.7135 -0.0685 -0.1614 0.0367 1.0296 ] \n");
 
-        Writef(m, "/RangePQR [ -0.5 2 -0.5 2 -0.5 2 ]\n");
+        _cmsIOPrintf(m, "/RangePQR [ -0.5 2 -0.5 2 -0.5 2 ]\n");
 
 
         // No BPC
 
         if (!DoBPC) {
 
-            Writef(m, "%% VonKries-like transform in Bradford Cone Space\n"
+            _cmsIOPrintf(m, "%% VonKries-like transform in Bradford Cone Space\n"
                       "/TransformPQR [\n"
                       "{exch pop exch 3 get mul exch pop exch 3 get div} bind\n"
                       "{exch pop exch 4 get mul exch pop exch 4 get div} bind\n"
@@ -1403,22 +1235,22 @@
 
             // BPC
 
-            Writef(m, "%% VonKries-like transform in Bradford Cone Space plus BPC\n"
+            _cmsIOPrintf(m, "%% VonKries-like transform in Bradford Cone Space plus BPC\n"
                       "/TransformPQR [\n");
 
-            Writef(m, "{4 index 3 get div 2 index 3 get mul "
+            _cmsIOPrintf(m, "{4 index 3 get div 2 index 3 get mul "
                     "2 index 3 get 2 index 3 get sub mul "
                     "2 index 3 get 4 index 3 get 3 index 3 get sub mul sub "
                     "3 index 3 get 3 index 3 get exch sub div "
                     "exch pop exch pop exch pop exch pop } bind\n");
 
-            Writef(m, "{4 index 4 get div 2 index 4 get mul "
+            _cmsIOPrintf(m, "{4 index 4 get div 2 index 4 get mul "
                     "2 index 4 get 2 index 4 get sub mul "
                     "2 index 4 get 4 index 4 get 3 index 4 get sub mul sub "
                     "3 index 4 get 3 index 4 get exch sub div "
                     "exch pop exch pop exch pop exch pop } bind\n");
 
-            Writef(m, "{4 index 5 get div 2 index 5 get mul "
+            _cmsIOPrintf(m, "{4 index 5 get div 2 index 5 get mul "
                     "2 index 5 get 2 index 5 get sub mul "
                     "2 index 5 get 4 index 5 get 3 index 5 get sub mul sub "
                     "3 index 5 get 3 index 5 get exch sub div "
@@ -1431,24 +1263,24 @@
 
 
 static
-void EmitXYZ2Lab(LPMEMSTREAM m)
+void EmitXYZ2Lab(cmsIOHANDLER* m)
 {
-    Writef(m, "/RangeLMN [ -0.635 2.0 0 2 -0.635 2.0 ]\n");
-    Writef(m, "/EncodeLMN [\n");
-    Writef(m, "{ 0.964200  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
-    Writef(m, "{ 1.000000  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
-    Writef(m, "{ 0.824900  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
-    Writef(m, "]\n");
-    Writef(m, "/MatrixABC [ 0 1 0 1 -1 1 0 0 -1 ]\n");
-    Writef(m, "/EncodeABC [\n");
+    _cmsIOPrintf(m, "/RangeLMN [ -0.635 2.0 0 2 -0.635 2.0 ]\n");
+    _cmsIOPrintf(m, "/EncodeLMN [\n");
+    _cmsIOPrintf(m, "{ 0.964200  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
+    _cmsIOPrintf(m, "{ 1.000000  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
+    _cmsIOPrintf(m, "{ 0.824900  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
+    _cmsIOPrintf(m, "]\n");
+    _cmsIOPrintf(m, "/MatrixABC [ 0 1 0 1 -1 1 0 0 -1 ]\n");
+    _cmsIOPrintf(m, "/EncodeABC [\n");
 
 
-    Writef(m, "{ 116 mul  16 sub 100 div  } bind\n");
-    Writef(m, "{ 500 mul 128 add 256 div  } bind\n");
-    Writef(m, "{ 200 mul 128 add 256 div  } bind\n");
+    _cmsIOPrintf(m, "{ 116 mul  16 sub 100 div  } bind\n");
+    _cmsIOPrintf(m, "{ 500 mul 128 add 256 div  } bind\n");
+    _cmsIOPrintf(m, "{ 200 mul 128 add 256 div  } bind\n");
 
 
-    Writef(m, "]\n");
+    _cmsIOPrintf(m, "]\n");
 
 
 }
@@ -1460,104 +1292,74 @@
 // 8 bits.
 
 static
-int WriteOutputLUT(LPMEMSTREAM m, cmsHPROFILE hProfile, int Intent, DWORD dwFlags)
+int WriteOutputLUT(cmsIOHANDLER* m, cmsHPROFILE hProfile, int Intent, cmsUInt32Number dwFlags)
 {
     cmsHPROFILE hLab;
     cmsHTRANSFORM xform;
-    icColorSpaceSignature ColorSpace;
     int i, nChannels;
-    DWORD OutputFormat;
-    _LPcmsTRANSFORM v;
-    LPLUT DeviceLink;
+    cmsUInt32Number OutputFormat;
+    _cmsTRANSFORM* v;
+    cmsPipeline* DeviceLink;
     cmsHPROFILE Profiles[3];
     cmsCIEXYZ BlackPointAdaptedToD50;
-    LCMSBOOL lFreeDeviceLink = FALSE;
-    LCMSBOOL lDoBPC = (dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION);
-    LCMSBOOL lFixWhite = !(dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP);
+    cmsBool lDoBPC = (dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION);
+    cmsBool lFixWhite = !(dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP);
+    cmsUInt32Number InFrm = TYPE_Lab_16;
     int RelativeEncodingIntent;
-
+    cmsColorSpaceSignature ColorSpace;
 
 
-    hLab = cmsCreateLabProfile(NULL);
+    hLab = cmsCreateLab4ProfileTHR(m ->ContextID, NULL);
+    if (hLab == NULL) return 0;
 
-    ColorSpace  =  cmsGetColorSpace(hProfile);
-    nChannels   = _cmsChannelsOf(ColorSpace);
-    OutputFormat = CHANNELS_SH(nChannels) | BYTES_SH(2);
+    OutputFormat = cmsFormatterForColorspaceOfProfile(hProfile, 2, FALSE);
+    nChannels    = T_CHANNELS(OutputFormat);
 
-    // For absolute colorimetric, the LUT is encoded as relative
-    // in order to preserve precission.
+    ColorSpace = cmsGetColorSpace(hProfile);
+
+    // For absolute colorimetric, the LUT is encoded as relative in order to preserve precision.
 
     RelativeEncodingIntent = Intent;
     if (RelativeEncodingIntent == INTENT_ABSOLUTE_COLORIMETRIC)
         RelativeEncodingIntent = INTENT_RELATIVE_COLORIMETRIC;
 
 
-    // Is a devicelink profile?
-    if (cmsGetDeviceClass(hProfile) == icSigLinkClass) {
-
-        // if devicelink input already in Lab
-
-        if (ColorSpace == icSigLabData) {
-
-              // adjust input to Lab to our v4
-
-            Profiles[0] = hLab;
-            Profiles[1] = hProfile;
+    // Use V4 Lab always
+    Profiles[0] = hLab;
+    Profiles[1] = hProfile;
 
-            xform = cmsCreateMultiprofileTransform(Profiles, 2, TYPE_Lab_DBL,
-                                                        OutputFormat, RelativeEncodingIntent,
-                                                        dwFlags|cmsFLAGS_NOWHITEONWHITEFIXUP|cmsFLAGS_NOPRELINEARIZATION);
-
-        }
-        else {
-          cmsSignalError(LCMS_ERRC_ABORTED, "Cannot use devicelink profile for CRD creation");
-          return 0;
-        }
-
-
-    }
-    else {
-
-        // This is a normal profile
-        xform = cmsCreateTransform(hLab, TYPE_Lab_DBL, hProfile,
-                            OutputFormat, RelativeEncodingIntent, dwFlags|cmsFLAGS_NOWHITEONWHITEFIXUP|cmsFLAGS_NOPRELINEARIZATION);
-    }
+    xform = cmsCreateMultiprofileTransformTHR(m ->ContextID,
+                                              Profiles, 2, TYPE_Lab_DBL,
+                                              OutputFormat, RelativeEncodingIntent, 0);
+    cmsCloseProfile(hLab);
 
     if (xform == NULL) {
 
-            cmsSignalError(LCMS_ERRC_ABORTED, "Cannot create transform Lab -> Profile in CRD creation");
-            return 0;
+        cmsSignalError(m ->ContextID, cmsERROR_COLORSPACE_CHECK, "Cannot create transform Lab -> Profile in CRD creation");
+        return 0;
     }
 
-    // Get the internal precalculated devicelink
-
-    v = (_LPcmsTRANSFORM) xform;
-    DeviceLink = v ->DeviceLink;
-
-    if (!DeviceLink) {
-
-        DeviceLink = _cmsPrecalculateDeviceLink(xform, cmsFLAGS_NOPRELINEARIZATION);
-        lFreeDeviceLink = TRUE;
-    }
-
-    Writef(m, "<<\n");
-    Writef(m, "/ColorRenderingType 1\n");
+    // Get a copy of the internal devicelink
+    v = (_cmsTRANSFORM*) xform;
+    DeviceLink = cmsPipelineDup(v ->Lut);
+    if (DeviceLink == NULL) return 0;
 
 
-    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, Intent, LCMS_BPFLAGS_D50_ADAPTED);
+    // We need a CLUT
+    dwFlags |= cmsFLAGS_FORCE_CLUT;
+    _cmsOptimizePipeline(&DeviceLink, RelativeEncodingIntent, &InFrm, &OutputFormat, &dwFlags);
+
+    _cmsIOPrintf(m, "<<\n");
+    _cmsIOPrintf(m, "/ColorRenderingType 1\n");
+
+
+    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, Intent, 0);
 
     // Emit headers, etc.
     EmitWhiteBlackD50(m, &BlackPointAdaptedToD50);
     EmitPQRStage(m, hProfile, lDoBPC, Intent == INTENT_ABSOLUTE_COLORIMETRIC);
     EmitXYZ2Lab(m);
 
-    if (DeviceLink ->wFlags & LUT_HASTL1) {
-
-        // Shouldn't happen
-        cmsSignalError(LCMS_ERRC_ABORTED, "Internal error (prelinearization on CRD)");
-        return 0;
-    }
-
 
     // FIXUP: map Lab (100, 0, 0) to perfect white, because the particular encoding for Lab
     // does map a=b=0 not falling into any specific node. Since range a,b goes -128..127,
@@ -1568,31 +1370,30 @@
     if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
             lFixWhite = FALSE;
 
-    Writef(m, "/RenderTable ");
+    _cmsIOPrintf(m, "/RenderTable ");
+
 
-    WriteCLUT(m, DeviceLink, 8, "<", ">\n", "", "", FALSE,
-                lFixWhite, ColorSpace);
+    WriteCLUT(m, cmsPipelineGetPtrToFirstStage(DeviceLink), "<", ">\n", "", "", lFixWhite, ColorSpace);
 
-    Writef(m, " %d {} bind ", nChannels);
+    _cmsIOPrintf(m, " %d {} bind ", nChannels);
 
     for (i=1; i < nChannels; i++)
-            Writef(m, "dup ");
+            _cmsIOPrintf(m, "dup ");
 
-    Writef(m, "]\n");
+    _cmsIOPrintf(m, "]\n");
 
 
     EmitIntent(m, Intent);
 
-    Writef(m, ">>\n");
+    _cmsIOPrintf(m, ">>\n");
 
     if (!(dwFlags & cmsFLAGS_NODEFAULTRESOURCEDEF)) {
 
-        Writef(m, "/Current exch /ColorRendering defineresource pop\n");
+        _cmsIOPrintf(m, "/Current exch /ColorRendering defineresource pop\n");
     }
 
-    if (lFreeDeviceLink) cmsFreeLUT(DeviceLink);
+    cmsPipelineFree(DeviceLink);
     cmsDeleteTransform(xform);
-    cmsCloseProfile(hLab);
 
     return 1;
 }
@@ -1600,14 +1401,14 @@
 
 // Builds a ASCII string containing colorant list in 0..1.0 range
 static
-void BuildColorantList(char *Colorant, int nColorant, WORD Out[])
+void BuildColorantList(char *Colorant, int nColorant, cmsUInt16Number Out[])
 {
     char Buff[32];
     int j;
 
     Colorant[0] = 0;
-    if (nColorant > MAXCHANNELS)
-        nColorant = MAXCHANNELS;
+    if (nColorant > cmsMAXCHANNELS)
+        nColorant = cmsMAXCHANNELS;
 
     for (j=0; j < nColorant; j++) {
 
@@ -1624,50 +1425,54 @@
 // This is a HP extension.
 
 static
-int WriteNamedColorCRD(LPMEMSTREAM m, cmsHPROFILE hNamedColor, int Intent, DWORD dwFlags)
+int WriteNamedColorCRD(cmsIOHANDLER* m, cmsHPROFILE hNamedColor, int Intent, cmsUInt32Number dwFlags)
 {
     cmsHTRANSFORM xform;
     int i, nColors, nColorant;
-    DWORD OutputFormat;
+    cmsUInt32Number OutputFormat;
     char ColorName[32];
     char Colorant[128];
+    cmsNAMEDCOLORLIST* NamedColorList;
 
-    nColorant = _cmsChannelsOf(cmsGetColorSpace(hNamedColor));
-    OutputFormat = CHANNELS_SH(nColorant) | BYTES_SH(2);
 
-    xform = cmsCreateTransform(hNamedColor, TYPE_NAMED_COLOR_INDEX,
-                        NULL, OutputFormat, Intent, cmsFLAGS_NOTPRECALC);
+    OutputFormat = cmsFormatterForColorspaceOfProfile(hNamedColor, 2, FALSE);
+    nColorant    = T_CHANNELS(OutputFormat);
+
+
+    xform = cmsCreateTransform(hNamedColor, TYPE_NAMED_COLOR_INDEX, NULL, OutputFormat, Intent, dwFlags);
     if (xform == NULL) return 0;
 
 
-    Writef(m, "<<\n");
-    Writef(m, "(colorlistcomment) (%s) \n", "Named profile");
-    Writef(m, "(Prefix) [ (Pantone ) (PANTONE ) ]\n");
-    Writef(m, "(Suffix) [ ( CV) ( CVC) ( C) ]\n");
+    NamedColorList = cmsGetNamedColorList(xform);
+    if (NamedColorList == NULL) return 0;
 
-    nColors   = cmsNamedColorCount(xform);
+    _cmsIOPrintf(m, "<<\n");
+    _cmsIOPrintf(m, "(colorlistcomment) (%s) \n", "Named profile");
+    _cmsIOPrintf(m, "(Prefix) [ (Pantone ) (PANTONE ) ]\n");
+    _cmsIOPrintf(m, "(Suffix) [ ( CV) ( CVC) ( C) ]\n");
 
+    nColors   = cmsNamedColorCount(NamedColorList);
 
     for (i=0; i < nColors; i++) {
 
-        WORD In[1];
-        WORD Out[MAXCHANNELS];
+        cmsUInt16Number In[1];
+        cmsUInt16Number Out[cmsMAXCHANNELS];
 
-        In[0] = (WORD) i;
+        In[0] = (cmsUInt16Number) i;
 
-        if (!cmsNamedColorInfo(xform, i, ColorName, NULL, NULL))
+        if (!cmsNamedColorInfo(NamedColorList, i, ColorName, NULL, NULL, NULL, NULL))
                 continue;
 
         cmsDoTransform(xform, In, Out, 1);
         BuildColorantList(Colorant, nColorant, Out);
-        Writef(m, "  (%s) [ %s ]\n", ColorName, Colorant);
+        _cmsIOPrintf(m, "  (%s) [ %s ]\n", ColorName, Colorant);
     }
 
-    Writef(m, "   >>");
+    _cmsIOPrintf(m, "   >>");
 
     if (!(dwFlags & cmsFLAGS_NODEFAULTRESOURCEDEF)) {
 
-    Writef(m, " /Current exch /HPSpotTable defineresource pop\n");
+    _cmsIOPrintf(m, " /Current exch /HPSpotTable defineresource pop\n");
     }
 
     cmsDeleteTransform(xform);
@@ -1680,67 +1485,129 @@
 // CRD are always LUT-Based, no matter if profile is
 // implemented as matrix-shaper.
 
-DWORD LCMSEXPORT cmsGetPostScriptCRDEx(cmsHPROFILE hProfile,
-                              int Intent, DWORD dwFlags,
-                              LPVOID Buffer, DWORD dwBufferLen)
+static
+cmsUInt32Number  GenerateCRD(cmsContext ContextID,
+                             cmsHPROFILE hProfile,
+                             cmsUInt32Number Intent, cmsUInt32Number dwFlags,
+                             cmsIOHANDLER* mem)
 {
-
-    LPMEMSTREAM mem;
-    DWORD dwBytesUsed;
-
-    // Set up the serialization artifact
-    mem = CreateMemStream((LPBYTE) Buffer, dwBufferLen, MAXPSCOLS);
-    if (!mem) return 0;
-
+    cmsUInt32Number dwBytesUsed;
 
     if (!(dwFlags & cmsFLAGS_NODEFAULTRESOURCEDEF)) {
 
-    EmitHeader(mem, "Color Rendering Dictionary (CRD)", hProfile);
+        EmitHeader(mem, "Color Rendering Dictionary (CRD)", hProfile);
     }
 
 
     // Is a named color profile?
-    if (cmsGetDeviceClass(hProfile) == icSigNamedColorClass) {
+    if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
 
         if (!WriteNamedColorCRD(mem, hProfile, Intent, dwFlags)) {
-
-                    _cmsFree((void*) mem);
-                    return 0;
+            return 0;
         }
     }
     else {
 
-    // CRD are always implemented as LUT.
-
+        // CRD are always implemented as LUT
 
-    if (!WriteOutputLUT(mem, hProfile, Intent, dwFlags)) {
-        _cmsFree((void*) mem);
-        return 0;
-    }
+        if (!WriteOutputLUT(mem, hProfile, Intent, dwFlags)) {
+            return 0;
+        }
     }
 
     if (!(dwFlags & cmsFLAGS_NODEFAULTRESOURCEDEF)) {
 
-    Writef(mem, "%%%%EndResource\n");
-    Writef(mem, "\n%% CRD End\n");
+        _cmsIOPrintf(mem, "%%%%EndResource\n");
+        _cmsIOPrintf(mem, "\n%% CRD End\n");
     }
 
     // Done, keep memory usage
-    dwBytesUsed = mem ->dwUsed;
+    dwBytesUsed = mem ->UsedSpace;
+
+    // Finally, return used byte count
+    return dwBytesUsed;
+
+    cmsUNUSED_PARAMETER(ContextID);
+}
+
+
+
+
+cmsUInt32Number CMSEXPORT cmsGetPostScriptColorResource(cmsContext ContextID,
+                                                        cmsPSResourceType Type,
+                                                        cmsHPROFILE hProfile,
+                                                        cmsUInt32Number Intent,
+                                                        cmsUInt32Number dwFlags,
+                                                        cmsIOHANDLER* io)
+{
+    cmsUInt32Number  rc;
+
+
+    switch (Type) {
+
+      case cmsPS_RESOURCE_CSA:
+          rc = GenerateCSA(ContextID, hProfile, Intent, dwFlags, io);
+          break;
+      default:
+      case cmsPS_RESOURCE_CRD:
+          rc = GenerateCRD(ContextID, hProfile, Intent, dwFlags, io);
+          break;
+    }
+
+    return rc;
+}
+
+
+
+cmsUInt32Number CMSEXPORT cmsGetPostScriptCRD(cmsContext ContextID,
+                                              cmsHPROFILE hProfile,
+                              cmsUInt32Number Intent, cmsUInt32Number dwFlags,
+                              void* Buffer, cmsUInt32Number dwBufferLen)
+{
+    cmsIOHANDLER* mem;
+    cmsUInt32Number dwBytesUsed;
+
+    // Set up the serialization engine
+    if (Buffer == NULL)
+        mem = cmsOpenIOhandlerFromNULL(ContextID);
+    else
+        mem = cmsOpenIOhandlerFromMem(ContextID, Buffer, dwBufferLen, "w");
+
+    if (!mem) return 0;
+
+    dwBytesUsed =  cmsGetPostScriptColorResource(ContextID, cmsPS_RESOURCE_CRD, hProfile, Intent, dwFlags, mem);
 
     // Get rid of memory stream
-    _cmsFree((void*) mem);
+    cmsCloseIOhandler(mem);
 
-    // Finally, return used byte count
     return dwBytesUsed;
 }
 
 
-// For compatibility with previous versions
+
+// Does create a Color Space Array on XYZ colorspace for PostScript usage
+cmsUInt32Number CMSEXPORT cmsGetPostScriptCSA(cmsContext ContextID,
+                                              cmsHPROFILE hProfile,
+                                              cmsUInt32Number Intent,
+                                              cmsUInt32Number dwFlags,
+                                              void* Buffer,
+                                              cmsUInt32Number dwBufferLen)
+{
+    cmsIOHANDLER* mem;
+    cmsUInt32Number dwBytesUsed;
 
-DWORD LCMSEXPORT cmsGetPostScriptCRD(cmsHPROFILE hProfile,
-                              int Intent,
-                              LPVOID Buffer, DWORD dwBufferLen)
-{
-    return cmsGetPostScriptCRDEx(hProfile, Intent, 0, Buffer, dwBufferLen);
+    if (Buffer == NULL)
+        mem = cmsOpenIOhandlerFromNULL(ContextID);
+    else
+        mem = cmsOpenIOhandlerFromMem(ContextID, Buffer, dwBufferLen, "w");
+
+    if (!mem) return 0;
+
+    dwBytesUsed =  cmsGetPostScriptColorResource(ContextID, cmsPS_RESOURCE_CSA, hProfile, Intent, dwFlags, mem);
+
+    // Get rid of memory stream
+    cmsCloseIOhandler(mem);
+
+    return dwBytesUsed;
+
 }
--- a/src/share/native/sun/java2d/cmm/lcms/cmssamp.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmssamp.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,650 +49,246 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-#include "lcms.h"
-
-
-// ---------------------------------------------------------------------------------
-
-static volatile int GlobalBlackPreservationStrategy = 0;
-
-// Quantize a value 0 <= i < MaxSamples
-
-WORD _cmsQuantizeVal(double i, int MaxSamples)
-{
-       double x;
-
-       x = ((double) i * 65535.) / (double) (MaxSamples - 1);
+//
+//---------------------------------------------------------------------------------
+//
 
-       return (WORD) floor(x + .5);
-}
-
-
-// Is a table linear?
-
-int cmsIsLinear(WORD Table[], int nEntries)
-{
-       register int i;
-       int diff;
-
-       for (i=0; i < nEntries; i++) {
-
-           diff = abs((int) Table[i] - (int) _cmsQuantizeVal(i, nEntries));
-           if (diff > 3)
-                     return 0;
-       }
-
-       return 1;
-}
+#include "lcms2_internal.h"
 
 
 
-// pow() restricted to integer
-
-static
-int ipow(int base, int exp)
-{
-        int res = base;
-
-        while (--exp)
-               res *= base;
-
-        return res;
-}
-
+// This file contains routines for resampling and LUT optimization, black point detection
+// and black preservation.
 
-// Given n, 0<=n<=clut^dim, returns the colorant.
-
-static
-int ComponentOf(int n, int clut, int nColorant)
-{
-        if (nColorant <= 0)
-                return (n % clut);
-
-        n /= ipow(clut, nColorant);
-
-        return (n % clut);
-}
-
+// Black point detection -------------------------------------------------------------------------
 
 
-// This routine does a sweep on whole input space, and calls its callback
-// function on knots. returns TRUE if all ok, FALSE otherwise.
-
-LCMSBOOL LCMSEXPORT cmsSample3DGrid(LPLUT Lut, _cmsSAMPLER Sampler, LPVOID Cargo, DWORD dwFlags)
+// PCS -> PCS round trip transform, always uses relative intent on the device -> pcs
+static
+cmsHTRANSFORM CreateRoundtripXForm(cmsHPROFILE hProfile, cmsUInt32Number nIntent)
 {
-   int i, t, nTotalPoints, Colorant, index;
-   WORD In[MAXCHANNELS], Out[MAXCHANNELS];
-
-   nTotalPoints = ipow(Lut->cLutPoints, Lut -> InputChan);
+    cmsHPROFILE hLab = cmsCreateLab4Profile(NULL);
+    cmsHTRANSFORM xform;
+    cmsBool BPC[4] = { FALSE, FALSE, FALSE, FALSE };
+    cmsFloat64Number States[4] = { 1.0, 1.0, 1.0, 1.0 };
+    cmsHPROFILE hProfiles[4];
+    cmsUInt32Number Intents[4];
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
-   index = 0;
-   for (i = 0; i < nTotalPoints; i++) {
+    hProfiles[0] = hLab; hProfiles[1] = hProfile; hProfiles[2] = hProfile; hProfiles[3] = hLab;
+    Intents[0]   = INTENT_RELATIVE_COLORIMETRIC; Intents[1] = nIntent; Intents[2] = INTENT_RELATIVE_COLORIMETRIC; Intents[3] = INTENT_RELATIVE_COLORIMETRIC;
 
-        for (t=0; t < (int) Lut -> InputChan; t++) {
+    xform =  cmsCreateExtendedTransform(ContextID, 4, hProfiles, BPC, Intents,
+        States, NULL, 0, TYPE_Lab_DBL, TYPE_Lab_DBL, cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);
+
+    cmsCloseProfile(hLab);
+    return xform;
+}
 
-                Colorant =  ComponentOf(i, Lut -> cLutPoints, (Lut -> InputChan - t  - 1 ));
-                In[t]    = _cmsQuantizeVal(Colorant, Lut -> cLutPoints);
-        }
+// Use darker colorants to obtain black point. This works in the relative colorimetric intent and
+// assumes more ink results in darker colors. No ink limit is assumed.
+static
+cmsBool  BlackPointAsDarkerColorant(cmsHPROFILE    hInput,
+                                    cmsUInt32Number Intent,
+                                    cmsCIEXYZ* BlackPoint,
+                                    cmsUInt32Number dwFlags)
+{
+    cmsUInt16Number *Black;
+    cmsHTRANSFORM xform;
+    cmsColorSpaceSignature Space;
+    cmsUInt32Number nChannels;
+    cmsUInt32Number dwFormat;
+    cmsHPROFILE hLab;
+    cmsCIELab  Lab;
+    cmsCIEXYZ  BlackXYZ;
+    cmsContext ContextID = cmsGetProfileContextID(hInput);
 
+    // If the profile does not support input direction, assume Black point 0
+    if (!cmsIsIntentSupported(hInput, Intent, LCMS_USED_AS_INPUT)) {
 
-        if (dwFlags & SAMPLER_HASTL1) {
+        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+        return FALSE;
+    }
 
-                 for (t=0; t < (int) Lut -> InputChan; t++)
-                     In[t] = cmsReverseLinearInterpLUT16(In[t],
-                                                Lut -> L1[t],
-                                                &Lut -> In16params);
-        }
+    // Create a formatter which has n channels and floating point
+    dwFormat = cmsFormatterForColorspaceOfProfile(hInput, 2, FALSE);
+
+   // Try to get black by using black colorant
+    Space = cmsGetColorSpace(hInput);
+
+    // This function returns darker colorant in 16 bits for several spaces
+    if (!_cmsEndPointsBySpace(Space, NULL, &Black, &nChannels)) {
 
-        for (t=0; t < (int) Lut -> OutputChan; t++)
-                     Out[t] = Lut->T[index + t];
+        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+        return FALSE;
+    }
+
+    if (nChannels != T_CHANNELS(dwFormat)) {
+       BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+       return FALSE;
+    }
+
+    // Lab will be used as the output space, but lab2 will avoid recursion
+    hLab = cmsCreateLab2ProfileTHR(ContextID, NULL);
+    if (hLab == NULL) {
+       BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+       return FALSE;
+    }
 
-        if (dwFlags & SAMPLER_HASTL2) {
+    // Create the transform
+    xform = cmsCreateTransformTHR(ContextID, hInput, dwFormat,
+                                hLab, TYPE_Lab_DBL, Intent, cmsFLAGS_NOOPTIMIZE|cmsFLAGS_NOCACHE);
+    cmsCloseProfile(hLab);
 
-             for (t=0; t < (int) Lut -> OutputChan; t++)
-                     Out[t] = cmsLinearInterpLUT16(Out[t],
-                                                   Lut -> L2[t],
-                                                   &Lut -> Out16params);
-        }
+    if (xform == NULL) {
+        // Something went wrong. Get rid of open resources and return zero as black
+
+        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+        return FALSE;
+    }
+
+    // Convert black to Lab
+    cmsDoTransform(xform, Black, &Lab, 1);
 
+    // Force it to be neutral, clip to max. L* of 50
+    Lab.a = Lab.b = 0;
+    if (Lab.L > 50) Lab.L = 50;
 
-        if (!Sampler(In, Out, Cargo))
-                return FALSE;
+    // Free the resources
+    cmsDeleteTransform(xform);
 
-        if (!(dwFlags & SAMPLER_INSPECT)) {
+    // Convert from Lab (which is now clipped) to XYZ.
+    cmsLab2XYZ(NULL, &BlackXYZ, &Lab);
 
-            if (dwFlags & SAMPLER_HASTL2) {
+    if (BlackPoint != NULL)
+        *BlackPoint = BlackXYZ;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(dwFlags);
+}
 
-                for (t=0; t < (int) Lut -> OutputChan; t++)
-                     Out[t] = cmsReverseLinearInterpLUT16(Out[t],
-                                                   Lut -> L2[t],
-                                                   &Lut -> Out16params);
-                }
+// Get a black point of output CMYK profile, discounting any ink-limiting embedded
+// in the profile. For doing that, we use perceptual intent in input direction:
+// Lab (0, 0, 0) -> [Perceptual] Profile -> CMYK -> [Rel. colorimetric] Profile -> Lab
+static
+cmsBool BlackPointUsingPerceptualBlack(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile)
 
+{
+    cmsHTRANSFORM hRoundTrip;
+    cmsCIELab LabIn, LabOut;
+    cmsCIEXYZ  BlackXYZ;
+
+     // Is the intent supported by the profile?
+    if (!cmsIsIntentSupported(hProfile, INTENT_PERCEPTUAL, LCMS_USED_AS_INPUT)) {
+
+        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+        return TRUE;
+    }
 
-            for (t=0; t < (int) Lut -> OutputChan; t++)
-                        Lut->T[index + t] = Out[t];
+    hRoundTrip = CreateRoundtripXForm(hProfile, INTENT_PERCEPTUAL);
+    if (hRoundTrip == NULL) {
+        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+        return FALSE;
+    }
+
+    LabIn.L = LabIn.a = LabIn.b = 0;
+    cmsDoTransform(hRoundTrip, &LabIn, &LabOut, 1);
 
-        }
+    // Clip Lab to reasonable limits
+    if (LabOut.L > 50) LabOut.L = 50;
+    LabOut.a = LabOut.b = 0;
+
+    cmsDeleteTransform(hRoundTrip);
 
-        index += Lut -> OutputChan;
+    // Convert it to XYZ
+    cmsLab2XYZ(NULL, &BlackXYZ, &LabOut);
 
-    }
+    if (BlackPoint != NULL)
+        *BlackPoint = BlackXYZ;
 
     return TRUE;
 }
 
-
-
-
-
+// This function shouldn't exist at all -- there is such quantity of broken
+// profiles on black point tag, that we must somehow fix chromaticity to
+// avoid huge tint when doing Black point compensation. This function does
+// just that. There is a special flag for using black point tag, but turned
+// off by default because it is bogus on most profiles. The detection algorithm
+// involves to turn BP to neutral and to use only L component.
 
-// choose reasonable resolution
-int _cmsReasonableGridpointsByColorspace(icColorSpaceSignature Colorspace, DWORD dwFlags)
+cmsBool CMSEXPORT cmsDetectBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags)
 {
-    int nChannels;
 
-    // Already specified?
-    if (dwFlags & 0x00FF0000) {
-            // Yes, grab'em
-            return (dwFlags >> 16) & 0xFF;
+    // Zero for black point
+    if (cmsGetDeviceClass(hProfile) == cmsSigLinkClass) {
+
+        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+        return FALSE;
     }
 
-    nChannels = _cmsChannelsOf(Colorspace);
+    // v4 + perceptual & saturation intents does have its own black point, and it is
+    // well specified enough to use it. Black point tag is deprecated in V4.
 
-    // HighResPrecalc is maximum resolution
-
-    if (dwFlags & cmsFLAGS_HIGHRESPRECALC) {
+    if ((cmsGetEncodedICCversion(hProfile) >= 0x4000000) &&
+        (Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) {
 
-        if (nChannels > 4)
-                return 7;       // 7 for Hifi
+            // Matrix shaper share MRC & perceptual intents
+            if (cmsIsMatrixShaper(hProfile))
+                return BlackPointAsDarkerColorant(hProfile, INTENT_RELATIVE_COLORIMETRIC, BlackPoint, 0);
 
-        if (nChannels == 4)     // 23 for CMYK
-                return 23;
+            // Get Perceptual black out of v4 profiles. That is fixed for perceptual & saturation intents
+            BlackPoint -> X = cmsPERCEPTUAL_BLACK_X;
+            BlackPoint -> Y = cmsPERCEPTUAL_BLACK_Y;
+            BlackPoint -> Z = cmsPERCEPTUAL_BLACK_Z;
 
-        return 49;      // 49 for RGB and others
+            return TRUE;
     }
 
 
-    // LowResPrecal is stripped resolution
-
-    if (dwFlags & cmsFLAGS_LOWRESPRECALC) {
-
-        if (nChannels > 4)
-                return 6;       // 6 for Hifi
-
-        if (nChannels == 1)
-                return 33;      // For monochrome
-
-        return 17;              // 17 for remaining
-    }
-
-    // Default values
-
-    if (nChannels > 4)
-                return 7;       // 7 for Hifi
-
-    if (nChannels == 4)
-                return 17;      // 17 for CMYK
-
-    return 33;                  // 33 for RGB
-
-}
+#ifdef CMS_USE_PROFILE_BLACK_POINT_TAG
 
-// Sampler implemented by another transform. This is a clean way to
-// precalculate the devicelink 3D CLUT for almost any transform
-
-static
-int XFormSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
-{
-        cmsDoTransform((cmsHTRANSFORM) Cargo, In, Out, 1);
-        return TRUE;
-}
-
-// This routine does compute the devicelink CLUT containing whole
-// transform. Handles any channel number.
-
-LPLUT _cmsPrecalculateDeviceLink(cmsHTRANSFORM h, DWORD dwFlags)
-{
-       _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) h;
-       LPLUT Grid;
-       int nGridPoints;
-       DWORD dwFormatIn, dwFormatOut;
-       DWORD SaveFormatIn, SaveFormatOut;
-       int ChannelsIn, ChannelsOut;
-       LPLUT SaveGamutLUT;
-
-
-       // Remove any gamut checking
-       SaveGamutLUT = p ->Gamut;
-       p ->Gamut = NULL;
+    // v2, v4 rel/abs colorimetric
+    if (cmsIsTag(hProfile, cmsSigMediaBlackPointTag) &&
+        Intent == INTENT_RELATIVE_COLORIMETRIC) {
 
-       ChannelsIn   = _cmsChannelsOf(p -> EntryColorSpace);
-       ChannelsOut  = _cmsChannelsOf(p -> ExitColorSpace);
-
-       nGridPoints = _cmsReasonableGridpointsByColorspace(p -> EntryColorSpace, dwFlags);
-
-       Grid =  cmsAllocLUT();
-       if (!Grid) return NULL;
-
-       Grid = cmsAlloc3DGrid(Grid, nGridPoints, ChannelsIn, ChannelsOut);
-
-       // Compute device link on 16-bit basis
-       dwFormatIn   = (CHANNELS_SH(ChannelsIn)|BYTES_SH(2));
-       dwFormatOut  = (CHANNELS_SH(ChannelsOut)|BYTES_SH(2));
-
-       SaveFormatIn  = p ->InputFormat;
-       SaveFormatOut = p ->OutputFormat;
-
-       p -> InputFormat  = dwFormatIn;
-       p -> OutputFormat = dwFormatOut;
-       p -> FromInput    = _cmsIdentifyInputFormat(p, dwFormatIn);
-       p -> ToOutput     = _cmsIdentifyOutputFormat(p, dwFormatOut);
-
-       // Fix gamut & gamma possible mismatches.
-
-       if (!(dwFlags & cmsFLAGS_NOPRELINEARIZATION)) {
+            cmsCIEXYZ *BlackPtr, BlackXYZ, UntrustedBlackPoint, TrustedBlackPoint, MediaWhite;
+            cmsCIELab Lab;
 
-           cmsHTRANSFORM hOne[1];
-           hOne[0] = h;
-
-           _cmsComputePrelinearizationTablesFromXFORM(hOne, 1, Grid);
-       }
-
-       // Attention to this typecast! we can take the luxury to
-       // do this since cmsHTRANSFORM is only an alias to a pointer
-       // to the transform struct.
-
-       if (!cmsSample3DGrid(Grid, XFormSampler, (LPVOID) p, Grid -> wFlags)) {
+            // If black point is specified, then use it,
 
-                cmsFreeLUT(Grid);
-                Grid = NULL;
-       }
-
-       p ->Gamut        = SaveGamutLUT;
-       p ->InputFormat  = SaveFormatIn;
-       p ->OutputFormat = SaveFormatOut;
-
-       return Grid;
-}
-
-
-
-// Sampler for Black-preserving CMYK->CMYK transforms
+            BlackPtr = cmsReadTag(hProfile, cmsSigMediaBlackPointTag);
+            if (BlackPtr != NULL) {
 
-typedef struct {
-                cmsHTRANSFORM cmyk2cmyk;
-                cmsHTRANSFORM cmyk2Lab;
-                LPGAMMATABLE  KTone;
-                L16PARAMS     KToneParams;
-                LPLUT         LabK2cmyk;
-                double        MaxError;
-
-                cmsHTRANSFORM hRoundTrip;
-                int           MaxTAC;
-
-                cmsHTRANSFORM hProofOutput;
-
-    } BPCARGO, *LPBPCARGO;
-
-
-
-// Preserve black only if that is the only ink used
-static
-int BlackPreservingGrayOnlySampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
-{
-    BPCARGO* bp = (LPBPCARGO) Cargo;
-
-    // If going across black only, keep black only
-    if (In[0] == 0 && In[1] == 0 && In[2] == 0) {
+                BlackXYZ = *BlackPtr;
+                _cmsReadMediaWhitePoint(&MediaWhite, hProfile);
 
-        // TAC does not apply because it is black ink!
-        Out[0] = Out[1] = Out[2] = 0;
-        Out[3] = cmsLinearInterpLUT16(In[3], bp->KTone ->GammaTable, &bp->KToneParams);
-        return 1;
-    }
-
-    // Keep normal transform for other colors
-    cmsDoTransform(bp ->cmyk2cmyk, In, Out, 1);
-    return 1;
-}
-
-
-
-// Preserve all K plane.
-static
-int BlackPreservingSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
-{
-
-    WORD LabK[4];
-    double SumCMY, SumCMYK, Error;
-    cmsCIELab ColorimetricLab, BlackPreservingLab;
-    BPCARGO* bp = (LPBPCARGO) Cargo;
-
-    // Get the K across Tone curve
-    LabK[3] = cmsLinearInterpLUT16(In[3], bp->KTone ->GammaTable, &bp->KToneParams);
+                // Black point is absolute XYZ, so adapt to D50 to get PCS value
+                cmsAdaptToIlluminant(&UntrustedBlackPoint, &MediaWhite, cmsD50_XYZ(), &BlackXYZ);
 
-    // If going across black only, keep black only
-    if (In[0] == 0 && In[1] == 0 && In[2] == 0) {
-
-        Out[0] = Out[1] = Out[2] = 0;
-        Out[3] = LabK[3];
-        return 1;
-    }
-
-    // Try the original transform, maybe K is already ok (valid on K=0)
-    cmsDoTransform(bp ->cmyk2cmyk, In, Out, 1);
-    if (Out[3] == LabK[3]) return 1;
-
-
-    // No, mesure and keep Lab measurement for further usage
-    cmsDoTransform(bp->hProofOutput, Out, &ColorimetricLab, 1);
-
-    // Is not black only and the transform doesn't keep black.
-    // Obtain the Lab of CMYK. After that we have Lab + K
-    cmsDoTransform(bp ->cmyk2Lab, In, LabK, 1);
-
-    // Obtain the corresponding CMY using reverse interpolation.
-    // As a seed, we use the colorimetric CMY
-    cmsEvalLUTreverse(bp ->LabK2cmyk, LabK, Out, Out);
+                // Force a=b=0 to get rid of any chroma
+                cmsXYZ2Lab(NULL, &Lab, &UntrustedBlackPoint);
+                Lab.a = Lab.b = 0;
+                if (Lab.L > 50) Lab.L = 50; // Clip to L* <= 50
+                cmsLab2XYZ(NULL, &TrustedBlackPoint, &Lab);
 
-    // Estimate the error
-    cmsDoTransform(bp->hProofOutput, Out, &BlackPreservingLab, 1);
-    Error = cmsDeltaE(&ColorimetricLab, &BlackPreservingLab);
-
-
-    // Apply TAC if needed
-
-    SumCMY   = Out[0]  + Out[1] + Out[2];
-    SumCMYK  = SumCMY + Out[3];
-
-    if (SumCMYK > bp ->MaxTAC) {
+                if (BlackPoint != NULL)
+                    *BlackPoint = TrustedBlackPoint;
 
-        double Ratio = 1 - ((SumCMYK - bp->MaxTAC) / SumCMY);
-        if (Ratio < 0)
-                  Ratio = 0;
-
-        Out[0] = (WORD) floor(Out[0] * Ratio + 0.5);     // C
-        Out[1] = (WORD) floor(Out[1] * Ratio + 0.5);     // M
-        Out[2] = (WORD) floor(Out[2] * Ratio + 0.5);     // Y
+                return TRUE;
+            }
     }
-
-    return 1;
-}
-
-
-// Sample whole gamut to estimate maximum TAC
-
-#ifdef _MSC_VER
-#pragma warning(disable : 4100)
 #endif
 
-static
-int EstimateTAC(register WORD In[], register WORD Out[], register LPVOID Cargo)
-{
-    BPCARGO* bp = (LPBPCARGO) Cargo;
-    WORD RoundTrip[4];
-    int Sum;
+    // That is about v2 profiles.
 
-    cmsDoTransform(bp->hRoundTrip, In, RoundTrip, 1);
-
-    Sum = RoundTrip[0] + RoundTrip[1] + RoundTrip[2] + RoundTrip[3];
+    // If output profile, discount ink-limiting and that's all
+    if (Intent == INTENT_RELATIVE_COLORIMETRIC &&
+        (cmsGetDeviceClass(hProfile) == cmsSigOutputClass) &&
+        (cmsGetColorSpace(hProfile)  == cmsSigCmykData))
+        return BlackPointUsingPerceptualBlack(BlackPoint, hProfile);
 
-    if (Sum > bp ->MaxTAC)
-            bp ->MaxTAC = Sum;
-
-    return 1;
+    // Nope, compute BP using current intent.
+    return BlackPointAsDarkerColorant(hProfile, Intent, BlackPoint, dwFlags);
 }
 
-
-// Estimate the maximum error
-static
-int BlackPreservingEstimateErrorSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
-{
-    BPCARGO* bp = (LPBPCARGO) Cargo;
-    WORD ColorimetricOut[4];
-    cmsCIELab ColorimetricLab, BlackPreservingLab;
-    double Error;
-
-    if (In[0] == 0 && In[1] == 0 && In[2] == 0) return 1;
-
-    cmsDoTransform(bp->cmyk2cmyk, In, ColorimetricOut, 1);
-
-    cmsDoTransform(bp->hProofOutput, ColorimetricOut, &ColorimetricLab, 1);
-    cmsDoTransform(bp->hProofOutput, Out, &BlackPreservingLab, 1);
-
-    Error = cmsDeltaE(&ColorimetricLab, &BlackPreservingLab);
-
-    if (Error > bp ->MaxError)
-        bp ->MaxError = Error;
-
-    return 1;
-}
-
-// Setup the K preservation strategy
-int LCMSEXPORT cmsSetCMYKPreservationStrategy(int n)
-{
-    int OldVal = GlobalBlackPreservationStrategy;
-
-    if (n >= 0)
-            GlobalBlackPreservationStrategy = n;
-
-    return OldVal;
-}
-
-#pragma warning(disable: 4550)
-
-// Get a pointer to callback on depending of strategy
-static
-_cmsSAMPLER _cmsGetBlackPreservationSampler(void)
-{
-    switch (GlobalBlackPreservationStrategy) {
-
-        case 0: return BlackPreservingGrayOnlySampler;
-        default: return BlackPreservingSampler;
-   }
-
-}
-
-// This is the black-preserving devicelink generator
-LPLUT _cmsPrecalculateBlackPreservingDeviceLink(cmsHTRANSFORM hCMYK2CMYK, DWORD dwFlags)
-{
-       _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) hCMYK2CMYK;
-       BPCARGO Cargo;
-       LPLUT Grid;
-       DWORD LocalFlags;
-       cmsHPROFILE hLab = cmsCreateLabProfile(NULL);
-       int nGridPoints;
-       icTagSignature Device2PCS[] = {icSigAToB0Tag,       // Perceptual
-                                      icSigAToB1Tag,       // Relative colorimetric
-                                      icSigAToB2Tag,       // Saturation
-                                      icSigAToB1Tag };     // Absolute colorimetric
-                                                           // (Relative/WhitePoint)
-
-       nGridPoints = _cmsReasonableGridpointsByColorspace(p -> EntryColorSpace, dwFlags);
-
-       // Get a copy of inteserting flags for this kind of xform
-       LocalFlags = cmsFLAGS_NOTPRECALC;
-       if (p -> dwOriginalFlags & cmsFLAGS_BLACKPOINTCOMPENSATION)
-           LocalFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
-
-       // Fill in cargo struct
-       Cargo.cmyk2cmyk = hCMYK2CMYK;
-
-       // Compute tone curve.
-       Cargo.KTone  =  _cmsBuildKToneCurve(hCMYK2CMYK, 256);
-       if (Cargo.KTone == NULL) return NULL;
-       cmsCalcL16Params(Cargo.KTone ->nEntries, &Cargo.KToneParams);
-
-
-       // Create a CMYK->Lab "normal" transform on input, without K-preservation
-       Cargo.cmyk2Lab  = cmsCreateTransform(p ->InputProfile, TYPE_CMYK_16,
-                                            hLab, TYPE_Lab_16, p->Intent, LocalFlags);
-
-       // We are going to use the reverse of proof direction
-       Cargo.LabK2cmyk = cmsReadICCLut(p->OutputProfile, Device2PCS[p->Intent]);
-
-       // Is there any table available?
-       if (Cargo.LabK2cmyk == NULL) {
-
-           Grid = NULL;
-           goto Cleanup;
-       }
-
-       // Setup a roundtrip on output profile for TAC estimation
-       Cargo.hRoundTrip = cmsCreateTransform(p ->OutputProfile, TYPE_CMYK_16,
-                                             p ->OutputProfile, TYPE_CMYK_16, p->Intent, cmsFLAGS_NOTPRECALC);
-
-
-       // Setup a proof CMYK->Lab on output
-       Cargo.hProofOutput  = cmsCreateTransform(p ->OutputProfile, TYPE_CMYK_16,
-                                            hLab, TYPE_Lab_DBL, p->Intent, LocalFlags);
-
-
-       // Create an empty LUT for holding K-preserving xform
-       Grid =  cmsAllocLUT();
-       if (!Grid) goto Cleanup;
-
-       Grid = cmsAlloc3DGrid(Grid, nGridPoints, 4, 4);
-
-       // Setup formatters
-       p -> FromInput = _cmsIdentifyInputFormat(p,  TYPE_CMYK_16);
-       p -> ToOutput  = _cmsIdentifyOutputFormat(p, TYPE_CMYK_16);
-
-
-
-       // Step #1, estimate TAC
-       Cargo.MaxTAC = 0;
-       if (!cmsSample3DGrid(Grid, EstimateTAC, (LPVOID) &Cargo, 0)) {
-
-                cmsFreeLUT(Grid);
-                Grid = NULL;
-                goto Cleanup;
-       }
-
-
-       // Step #2, compute approximation
-       if (!cmsSample3DGrid(Grid, _cmsGetBlackPreservationSampler(), (LPVOID) &Cargo, 0)) {
-
-                cmsFreeLUT(Grid);
-                Grid = NULL;
-                goto Cleanup;
-       }
-
-       // Step #3, estimate error
-        Cargo.MaxError = 0;
-        cmsSample3DGrid(Grid, BlackPreservingEstimateErrorSampler, (LPVOID) &Cargo, SAMPLER_INSPECT);
-
-
-Cleanup:
-
-       if (Cargo.cmyk2Lab) cmsDeleteTransform(Cargo.cmyk2Lab);
-       if (Cargo.hRoundTrip) cmsDeleteTransform(Cargo.hRoundTrip);
-       if (Cargo.hProofOutput) cmsDeleteTransform(Cargo.hProofOutput);
-
-       if (hLab) cmsCloseProfile(hLab);
-       if (Cargo.KTone) cmsFreeGamma(Cargo.KTone);
-       if (Cargo.LabK2cmyk) cmsFreeLUT(Cargo.LabK2cmyk);
-
-       return Grid;
-}
-
-
-
-// Fix broken LUT. just to obtain other CMS compatibility
-
-static
-void PatchLUT(LPLUT Grid, WORD At[], WORD Value[],
-                     int nChannelsOut, int nChannelsIn)
-{
-       LPL16PARAMS p16  = &Grid -> CLut16params;
-       double     px, py, pz, pw;
-       int        x0, y0, z0, w0;
-       int        i, index;
-
-
-       if (Grid ->wFlags & LUT_HASTL1) return;  // There is a prelinearization
-
-       px = ((double) At[0] * (p16->Domain)) / 65535.0;
-       py = ((double) At[1] * (p16->Domain)) / 65535.0;
-       pz = ((double) At[2] * (p16->Domain)) / 65535.0;
-       pw = ((double) At[3] * (p16->Domain)) / 65535.0;
-
-       x0 = (int) floor(px);
-       y0 = (int) floor(py);
-       z0 = (int) floor(pz);
-       w0 = (int) floor(pw);
-
-       if (nChannelsIn == 4) {
-
-              if (((px - x0) != 0) ||
-                  ((py - y0) != 0) ||
-                  ((pz - z0) != 0) ||
-                  ((pw - w0) != 0)) return; // Not on exact node
-
-              index = p16 -> opta4 * x0 +
-                      p16 -> opta3 * y0 +
-                      p16 -> opta2 * z0 +
-                      p16 -> opta1 * w0;
-       }
-       else
-       if (nChannelsIn == 3) {
-
-              if (((px - x0) != 0) ||
-                  ((py - y0) != 0) ||
-                  ((pz - z0) != 0)) return;  // Not on exact node
-
-              index = p16 -> opta3 * x0 +
-                      p16 -> opta2 * y0 +
-                      p16 -> opta1 * z0;
-       }
-       else
-       if (nChannelsIn == 1) {
-
-              if (((px - x0) != 0)) return; // Not on exact node
-
-              index = p16 -> opta1 * x0;
-       }
-       else {
-           cmsSignalError(LCMS_ERRC_ABORTED, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);
-           return;
-       }
-
-       for (i=0; i < nChannelsOut; i++)
-              Grid -> T[index + i] = Value[i];
-
-}
-
-
-
-LCMSBOOL _cmsFixWhiteMisalignment(_LPcmsTRANSFORM p)
-{
-
-       WORD *WhitePointIn, *WhitePointOut, *BlackPointIn, *BlackPointOut;
-       int nOuts, nIns;
-
-
-       if (!p -> DeviceLink) return FALSE;
-
-       if (p ->Intent == INTENT_ABSOLUTE_COLORIMETRIC) return FALSE;
-       if ((p ->PreviewProfile != NULL) &&
-           (p ->ProofIntent == INTENT_ABSOLUTE_COLORIMETRIC)) return FALSE;
-
-
-       if (!_cmsEndPointsBySpace(p -> EntryColorSpace,
-                                 &WhitePointIn, &BlackPointIn, &nIns)) return FALSE;
-
-
-       if (!_cmsEndPointsBySpace(p -> ExitColorSpace,
-                                   &WhitePointOut, &BlackPointOut, &nOuts)) return FALSE;
-
-       // Fix white only
-
-       PatchLUT(p -> DeviceLink, WhitePointIn, WhitePointOut, nOuts, nIns);
-       // PatchLUT(p -> DeviceLink, BlackPointIn, BlackPointOut, nOuts, nIns);
-
-       return TRUE;
-}
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/native/sun/java2d/cmm/lcms/cmssm.c	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,762 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
+
+
+// ------------------------------------------------------------------------
+
+// Gamut boundary description by using Jan Morovic's Segment maxima method
+// Many thanks to Jan for allowing me to use his algorithm.
+
+// r = C*
+// alpha = Hab
+// theta = L*
+
+#define SECTORS 16      // number of divisions in alpha and theta
+
+// Spherical coordinates
+typedef struct {
+
+    cmsFloat64Number r;
+    cmsFloat64Number alpha;
+    cmsFloat64Number theta;
+
+} cmsSpherical;
+
+typedef  enum {
+        GP_EMPTY,
+        GP_SPECIFIED,
+        GP_MODELED
+
+    } GDBPointType;
+
+
+typedef struct {
+
+    GDBPointType Type;
+    cmsSpherical p;         // Keep also alpha & theta of maximum
+
+} cmsGDBPoint;
+
+
+typedef struct {
+
+    cmsContext ContextID;
+    cmsGDBPoint Gamut[SECTORS][SECTORS];
+
+} cmsGDB;
+
+
+// A line using the parametric form
+// P = a + t*u
+typedef struct {
+
+    cmsVEC3 a;
+    cmsVEC3 u;
+
+} cmsLine;
+
+
+// A plane using the parametric form
+// Q = b + r*v + s*w
+typedef struct {
+
+    cmsVEC3 b;
+    cmsVEC3 v;
+    cmsVEC3 w;
+
+} cmsPlane;
+
+
+
+// --------------------------------------------------------------------------------------------
+
+// ATAN2() which always returns degree positive numbers
+
+static
+cmsFloat64Number _cmsAtan2(cmsFloat64Number y, cmsFloat64Number x)
+{
+    cmsFloat64Number a;
+
+    // Deal with undefined case
+    if (x == 0.0 && y == 0.0) return 0;
+
+    a = (atan2(y, x) * 180.0) / M_PI;
+
+    while (a < 0) {
+        a += 360;
+    }
+
+    return a;
+}
+
+// Convert to spherical coordinates
+static
+void ToSpherical(cmsSpherical* sp, const cmsVEC3* v)
+{
+
+    cmsFloat64Number L, a, b;
+
+    L = v ->n[VX];
+    a = v ->n[VY];
+    b = v ->n[VZ];
+
+    sp ->r = sqrt( L*L + a*a + b*b );
+
+   if (sp ->r == 0) {
+        sp ->alpha = sp ->theta = 0;
+        return;
+    }
+
+    sp ->alpha = _cmsAtan2(a, b);
+    sp ->theta = _cmsAtan2(sqrt(a*a + b*b), L);
+}
+
+
+// Convert to cartesian from spherical
+static
+void ToCartesian(cmsVEC3* v, const cmsSpherical* sp)
+{
+    cmsFloat64Number sin_alpha;
+    cmsFloat64Number cos_alpha;
+    cmsFloat64Number sin_theta;
+    cmsFloat64Number cos_theta;
+    cmsFloat64Number L, a, b;
+
+    sin_alpha = sin((M_PI * sp ->alpha) / 180.0);
+    cos_alpha = cos((M_PI * sp ->alpha) / 180.0);
+    sin_theta = sin((M_PI * sp ->theta) / 180.0);
+    cos_theta = cos((M_PI * sp ->theta) / 180.0);
+
+    a = sp ->r * sin_theta * sin_alpha;
+    b = sp ->r * sin_theta * cos_alpha;
+    L = sp ->r * cos_theta;
+
+    v ->n[VX] = L;
+    v ->n[VY] = a;
+    v ->n[VZ] = b;
+}
+
+
+// Quantize sector of a spherical coordinate. Saturate 360, 180 to last sector
+// The limits are the centers of each sector, so
+static
+void QuantizeToSector(const cmsSpherical* sp, int* alpha, int* theta)
+{
+    *alpha = (int) floor(((sp->alpha * (SECTORS)) / 360.0) );
+    *theta = (int) floor(((sp->theta * (SECTORS)) / 180.0) );
+
+    if (*alpha >= SECTORS)
+        *alpha = SECTORS-1;
+    if (*theta >= SECTORS)
+        *theta = SECTORS-1;
+}
+
+
+// Line determined by 2 points
+static
+void LineOf2Points(cmsLine* line, cmsVEC3* a, cmsVEC3* b)
+{
+
+    _cmsVEC3init(&line ->a, a ->n[VX], a ->n[VY], a ->n[VZ]);
+    _cmsVEC3init(&line ->u, b ->n[VX] - a ->n[VX],
+                            b ->n[VY] - a ->n[VY],
+                            b ->n[VZ] - a ->n[VZ]);
+}
+
+
+// Evaluate parametric line
+static
+void GetPointOfLine(cmsVEC3* p, const cmsLine* line, cmsFloat64Number t)
+{
+    p ->n[VX] = line ->a.n[VX] + t * line->u.n[VX];
+    p ->n[VY] = line ->a.n[VY] + t * line->u.n[VY];
+    p ->n[VZ] = line ->a.n[VZ] + t * line->u.n[VZ];
+}
+
+
+
+/*
+    Closest point in sector line1 to sector line2 (both are defined as 0 <=t <= 1)
+    http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm
+
+    Copyright 2001, softSurfer (www.softsurfer.com)
+    This code may be freely used and modified for any purpose
+    providing that this copyright notice is included with it.
+    SoftSurfer makes no warranty for this code, and cannot be held
+    liable for any real or imagined damage resulting from its use.
+    Users of this code must verify correctness for their application.
+
+*/
+
+static
+cmsBool ClosestLineToLine(cmsVEC3* r, const cmsLine* line1, const cmsLine* line2)
+{
+    cmsFloat64Number a, b, c, d, e, D;
+    cmsFloat64Number sc, sN, sD;
+    cmsFloat64Number tc, tN, tD;
+    cmsVEC3 w0;
+
+    _cmsVEC3minus(&w0, &line1 ->a, &line2 ->a);
+
+    a  = _cmsVEC3dot(&line1 ->u, &line1 ->u);
+    b  = _cmsVEC3dot(&line1 ->u, &line2 ->u);
+    c  = _cmsVEC3dot(&line2 ->u, &line2 ->u);
+    d  = _cmsVEC3dot(&line1 ->u, &w0);
+    e  = _cmsVEC3dot(&line2 ->u, &w0);
+
+    D  = a*c - b * b;      // Denominator
+    sD = tD = D;           // default sD = D >= 0
+
+    if (D <  MATRIX_DET_TOLERANCE) {   // the lines are almost parallel
+
+        sN = 0.0;        // force using point P0 on segment S1
+        sD = 1.0;        // to prevent possible division by 0.0 later
+        tN = e;
+        tD = c;
+    }
+    else {                // get the closest points on the infinite lines
+
+        sN = (b*e - c*d);
+        tN = (a*e - b*d);
+
+        if (sN < 0.0) {       // sc < 0 => the s=0 edge is visible
+
+            sN = 0.0;
+            tN = e;
+            tD = c;
+        }
+        else if (sN > sD) {   // sc > 1 => the s=1 edge is visible
+            sN = sD;
+            tN = e + b;
+            tD = c;
+        }
+    }
+
+    if (tN < 0.0) {           // tc < 0 => the t=0 edge is visible
+
+        tN = 0.0;
+        // recompute sc for this edge
+        if (-d < 0.0)
+            sN = 0.0;
+        else if (-d > a)
+            sN = sD;
+        else {
+            sN = -d;
+            sD = a;
+        }
+    }
+    else if (tN > tD) {      // tc > 1 => the t=1 edge is visible
+
+        tN = tD;
+
+        // recompute sc for this edge
+        if ((-d + b) < 0.0)
+            sN = 0;
+        else if ((-d + b) > a)
+            sN = sD;
+        else {
+            sN = (-d + b);
+            sD = a;
+        }
+    }
+    // finally do the division to get sc and tc
+    sc = (fabs(sN) < MATRIX_DET_TOLERANCE ? 0.0 : sN / sD);
+    tc = (fabs(tN) < MATRIX_DET_TOLERANCE ? 0.0 : tN / tD);
+
+    GetPointOfLine(r, line1, sc);
+    return TRUE;
+}
+
+
+
+// ------------------------------------------------------------------ Wrapper
+
+
+// Allocate & free structure
+cmsHANDLE  CMSEXPORT cmsGBDAlloc(cmsContext ContextID)
+{
+    cmsGDB* gbd = (cmsGDB*) _cmsMallocZero(ContextID, sizeof(cmsGDB));
+    if (gbd == NULL) return NULL;
+
+    gbd -> ContextID = ContextID;
+
+    return (cmsHANDLE) gbd;
+}
+
+
+void CMSEXPORT cmsGBDFree(cmsHANDLE hGBD)
+{
+    cmsGDB* gbd = (cmsGDB*) hGBD;
+    if (hGBD != NULL)
+        _cmsFree(gbd->ContextID, (void*) gbd);
+}
+
+
+// Auxiliar to retrieve a pointer to the segmentr containing the Lab value
+static
+cmsGDBPoint* GetPoint(cmsGDB* gbd, const cmsCIELab* Lab, cmsSpherical* sp)
+{
+    cmsVEC3 v;
+    int alpha, theta;
+
+    // Housekeeping
+    _cmsAssert(gbd != NULL);
+    _cmsAssert(Lab != NULL);
+    _cmsAssert(sp != NULL);
+
+    // Center L* by substracting half of its domain, that's 50
+    _cmsVEC3init(&v, Lab ->L - 50.0, Lab ->a, Lab ->b);
+
+    // Convert to spherical coordinates
+    ToSpherical(sp, &v);
+
+    if (sp ->r < 0 || sp ->alpha < 0 || sp->theta < 0) {
+         cmsSignalError(gbd ->ContextID, cmsERROR_RANGE, "spherical value out of range");
+         return NULL;
+    }
+
+    // On which sector it falls?
+    QuantizeToSector(sp, &alpha, &theta);
+
+    if (alpha < 0 || theta < 0 || alpha >= SECTORS || theta >= SECTORS) {
+         cmsSignalError(gbd ->ContextID, cmsERROR_RANGE, " quadrant out of range");
+         return NULL;
+    }
+
+    // Get pointer to the sector
+    return &gbd ->Gamut[theta][alpha];
+}
+
+// Add a point to gamut descriptor. Point to add is in Lab color space.
+// GBD is centered on a=b=0 and L*=50
+cmsBool CMSEXPORT cmsGDBAddPoint(cmsHANDLE hGBD, const cmsCIELab* Lab)
+{
+    cmsGDB* gbd = (cmsGDB*) hGBD;
+    cmsGDBPoint* ptr;
+    cmsSpherical sp;
+
+
+    // Get pointer to the sector
+    ptr = GetPoint(gbd, Lab, &sp);
+    if (ptr == NULL) return FALSE;
+
+    // If no samples at this sector, add it
+    if (ptr ->Type == GP_EMPTY) {
+
+        ptr -> Type = GP_SPECIFIED;
+        ptr -> p    = sp;
+    }
+    else {
+
+
+        // Substitute only if radius is greater
+        if (sp.r > ptr -> p.r) {
+
+                ptr -> Type = GP_SPECIFIED;
+                ptr -> p    = sp;
+        }
+    }
+
+    return TRUE;
+}
+
+// Check if a given point falls inside gamut
+cmsBool CMSEXPORT cmsGDBCheckPoint(cmsHANDLE hGBD, const cmsCIELab* Lab)
+{
+    cmsGDB* gbd = (cmsGDB*) hGBD;
+    cmsGDBPoint* ptr;
+    cmsSpherical sp;
+
+    // Get pointer to the sector
+    ptr = GetPoint(gbd, Lab, &sp);
+    if (ptr == NULL) return FALSE;
+
+    // If no samples at this sector, return no data
+    if (ptr ->Type == GP_EMPTY) return FALSE;
+
+    // In gamut only if radius is greater
+
+    return (sp.r <= ptr -> p.r);
+}
+
+// -----------------------------------------------------------------------------------------------------------------------
+
+// Find near sectors. The list of sectors found is returned on Close[].
+// The function returns the number of sectors as well.
+
+// 24   9  10  11  12
+// 23   8   1   2  13
+// 22   7   *   3  14
+// 21   6   5   4  15
+// 20  19  18  17  16
+//
+// Those are the relative movements
+// {-2,-2}, {-1, -2}, {0, -2}, {+1, -2}, {+2,  -2},
+// {-2,-1}, {-1, -1}, {0, -1}, {+1, -1}, {+2,  -1},
+// {-2, 0}, {-1,  0}, {0,  0}, {+1,  0}, {+2,   0},
+// {-2,+1}, {-1, +1}, {0, +1}, {+1,  +1}, {+2,  +1},
+// {-2,+2}, {-1, +2}, {0, +2}, {+1,  +2}, {+2,  +2}};
+
+
+static
+const struct _spiral {
+
+    int AdvX, AdvY;
+
+    } Spiral[] = { {0,  -1}, {+1, -1}, {+1,  0}, {+1, +1}, {0,  +1}, {-1, +1},
+                   {-1,  0}, {-1, -1}, {-1, -2}, {0,  -2}, {+1, -2}, {+2, -2},
+                   {+2, -1}, {+2,  0}, {+2, +1}, {+2, +2}, {+1, +2}, {0,  +2},
+                   {-1, +2}, {-2, +2}, {-2, +1}, {-2, 0},  {-2, -1}, {-2, -2} };
+
+#define NSTEPS (sizeof(Spiral) / sizeof(struct _spiral))
+
+static
+int FindNearSectors(cmsGDB* gbd, int alpha, int theta, cmsGDBPoint* Close[])
+{
+    int nSectors = 0;
+    int i, a, t;
+    cmsGDBPoint* pt;
+
+    for (i=0; i < NSTEPS; i++) {
+
+        a = alpha + Spiral[i].AdvX;
+        t = theta + Spiral[i].AdvY;
+
+        // Cycle at the end
+        a %= SECTORS;
+        t %= SECTORS;
+
+        // Cycle at the begin
+        if (a < 0) a = SECTORS + a;
+        if (t < 0) t = SECTORS + t;
+
+        pt = &gbd ->Gamut[t][a];
+
+        if (pt -> Type != GP_EMPTY) {
+
+            Close[nSectors++] = pt;
+        }
+    }
+
+    return nSectors;
+}
+
+
+// Interpolate a missing sector. Method identifies whatever this is top, bottom or mid
+static
+cmsBool InterpolateMissingSector(cmsGDB* gbd, int alpha, int theta)
+{
+    cmsSpherical sp;
+    cmsVEC3 Lab;
+    cmsVEC3 Centre;
+    cmsLine ray;
+    int nCloseSectors;
+    cmsGDBPoint* Close[NSTEPS];
+    cmsSpherical closel, templ;
+    cmsLine edge;
+    int k, m;
+
+    // Is that point already specified?
+    if (gbd ->Gamut[theta][alpha].Type != GP_EMPTY) return TRUE;
+
+    // Fill close points
+    nCloseSectors = FindNearSectors(gbd, alpha, theta, Close);
+
+
+    // Find a central point on the sector
+    sp.alpha = (cmsFloat64Number) ((alpha + 0.5) * 360.0) / (SECTORS);
+    sp.theta = (cmsFloat64Number) ((theta + 0.5) * 180.0) / (SECTORS);
+    sp.r     = 50.0;
+
+    // Convert to Cartesian
+    ToCartesian(&Lab, &sp);
+
+    // Create a ray line from centre to this point
+    _cmsVEC3init(&Centre, 50.0, 0, 0);
+    LineOf2Points(&ray, &Lab, &Centre);
+
+    // For all close sectors
+    closel.r = 0.0;
+    closel.alpha = 0;
+    closel.theta = 0;
+
+    for (k=0; k < nCloseSectors; k++) {
+
+        for(m = k+1; m < nCloseSectors; m++) {
+
+            cmsVEC3 temp, a1, a2;
+
+            // A line from sector to sector
+            ToCartesian(&a1, &Close[k]->p);
+            ToCartesian(&a2, &Close[m]->p);
+
+            LineOf2Points(&edge, &a1, &a2);
+
+            // Find a line
+            ClosestLineToLine(&temp, &ray, &edge);
+
+            // Convert to spherical
+            ToSpherical(&templ, &temp);
+
+
+            if ( templ.r > closel.r &&
+                 templ.theta >= (theta*180.0/SECTORS) &&
+                 templ.theta <= ((theta+1)*180.0/SECTORS) &&
+                 templ.alpha >= (alpha*360.0/SECTORS) &&
+                 templ.alpha <= ((alpha+1)*360.0/SECTORS)) {
+
+                closel = templ;
+            }
+        }
+    }
+
+    gbd ->Gamut[theta][alpha].p = closel;
+    gbd ->Gamut[theta][alpha].Type = GP_MODELED;
+
+    return TRUE;
+
+}
+
+
+// Interpolate missing parts. The algorithm fist computes slices at
+// theta=0 and theta=Max.
+cmsBool CMSEXPORT cmsGDBCompute(cmsHANDLE hGBD, cmsUInt32Number dwFlags)
+{
+    int alpha, theta;
+    cmsGDB* gbd = (cmsGDB*) hGBD;
+
+    _cmsAssert(hGBD != NULL);
+
+    // Interpolate black
+    for (alpha = 0; alpha <= SECTORS; alpha++) {
+
+        if (!InterpolateMissingSector(gbd, alpha, 0)) return FALSE;
+    }
+
+    // Interpolate white
+    for (alpha = 0; alpha <= SECTORS; alpha++) {
+
+        if (!InterpolateMissingSector(gbd, alpha, SECTORS-1)) return FALSE;
+    }
+
+
+    // Interpolate Mid
+    for (theta = 1; theta < SECTORS; theta++) {
+        for (alpha = 0; alpha <= SECTORS; alpha++) {
+
+            if (!InterpolateMissingSector(gbd, alpha, theta)) return FALSE;
+        }
+    }
+
+    // Done
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(dwFlags);
+}
+
+
+
+
+// --------------------------------------------------------------------------------------------------------
+
+// Great for debug, but not suitable for real use
+
+#if 0
+cmsBool cmsGBDdumpVRML(cmsHANDLE hGBD, const char* fname)
+{
+    FILE* fp;
+    int   i, j;
+    cmsGDB* gbd = (cmsGDB*) hGBD;
+    cmsGDBPoint* pt;
+
+    fp = fopen (fname, "wt");
+    if (fp == NULL)
+        return FALSE;
+
+    fprintf (fp, "#VRML V2.0 utf8\n");
+
+    // set the viewing orientation and distance
+    fprintf (fp, "DEF CamTest Group {\n");
+    fprintf (fp, "\tchildren [\n");
+    fprintf (fp, "\t\tDEF Cameras Group {\n");
+    fprintf (fp, "\t\t\tchildren [\n");
+    fprintf (fp, "\t\t\t\tDEF DefaultView Viewpoint {\n");
+    fprintf (fp, "\t\t\t\t\tposition 0 0 340\n");
+    fprintf (fp, "\t\t\t\t\torientation 0 0 1 0\n");
+    fprintf (fp, "\t\t\t\t\tdescription \"default view\"\n");
+    fprintf (fp, "\t\t\t\t}\n");
+    fprintf (fp, "\t\t\t]\n");
+    fprintf (fp, "\t\t},\n");
+    fprintf (fp, "\t]\n");
+    fprintf (fp, "}\n");
+
+    // Output the background stuff
+    fprintf (fp, "Background {\n");
+    fprintf (fp, "\tskyColor [\n");
+    fprintf (fp, "\t\t.5 .5 .5\n");
+    fprintf (fp, "\t]\n");
+    fprintf (fp, "}\n");
+
+    // Output the shape stuff
+    fprintf (fp, "Transform {\n");
+    fprintf (fp, "\tscale .3 .3 .3\n");
+    fprintf (fp, "\tchildren [\n");
+
+    // Draw the axes as a shape:
+    fprintf (fp, "\t\tShape {\n");
+    fprintf (fp, "\t\t\tappearance Appearance {\n");
+    fprintf (fp, "\t\t\t\tmaterial Material {\n");
+    fprintf (fp, "\t\t\t\t\tdiffuseColor 0 0.8 0\n");
+    fprintf (fp, "\t\t\t\t\temissiveColor 1.0 1.0 1.0\n");
+    fprintf (fp, "\t\t\t\t\tshininess 0.8\n");
+    fprintf (fp, "\t\t\t\t}\n");
+    fprintf (fp, "\t\t\t}\n");
+    fprintf (fp, "\t\t\tgeometry IndexedLineSet {\n");
+    fprintf (fp, "\t\t\t\tcoord Coordinate {\n");
+    fprintf (fp, "\t\t\t\t\tpoint [\n");
+    fprintf (fp, "\t\t\t\t\t0.0 0.0 0.0,\n");
+    fprintf (fp, "\t\t\t\t\t%f 0.0 0.0,\n",  255.0);
+    fprintf (fp, "\t\t\t\t\t0.0 %f 0.0,\n",  255.0);
+    fprintf (fp, "\t\t\t\t\t0.0 0.0 %f]\n",  255.0);
+    fprintf (fp, "\t\t\t\t}\n");
+    fprintf (fp, "\t\t\t\tcoordIndex [\n");
+    fprintf (fp, "\t\t\t\t\t0, 1, -1\n");
+    fprintf (fp, "\t\t\t\t\t0, 2, -1\n");
+    fprintf (fp, "\t\t\t\t\t0, 3, -1]\n");
+    fprintf (fp, "\t\t\t}\n");
+    fprintf (fp, "\t\t}\n");
+
+
+    fprintf (fp, "\t\tShape {\n");
+    fprintf (fp, "\t\t\tappearance Appearance {\n");
+    fprintf (fp, "\t\t\t\tmaterial Material {\n");
+    fprintf (fp, "\t\t\t\t\tdiffuseColor 0 0.8 0\n");
+    fprintf (fp, "\t\t\t\t\temissiveColor 1 1 1\n");
+    fprintf (fp, "\t\t\t\t\tshininess 0.8\n");
+    fprintf (fp, "\t\t\t\t}\n");
+    fprintf (fp, "\t\t\t}\n");
+    fprintf (fp, "\t\t\tgeometry PointSet {\n");
+
+    // fill in the points here
+    fprintf (fp, "\t\t\t\tcoord Coordinate {\n");
+    fprintf (fp, "\t\t\t\t\tpoint [\n");
+
+    // We need to transverse all gamut hull.
+    for (i=0; i < SECTORS; i++)
+        for (j=0; j < SECTORS; j++) {
+
+            cmsVEC3 v;
+
+            pt = &gbd ->Gamut[i][j];
+            ToCartesian(&v, &pt ->p);
+
+            fprintf (fp, "\t\t\t\t\t%g %g %g", v.n[0]+50, v.n[1], v.n[2]);
+
+            if ((j == SECTORS - 1) && (i == SECTORS - 1))
+                fprintf (fp, "]\n");
+            else
+                fprintf (fp, ",\n");
+
+        }
+
+        fprintf (fp, "\t\t\t\t}\n");
+
+
+
+    // fill in the face colors
+    fprintf (fp, "\t\t\t\tcolor Color {\n");
+    fprintf (fp, "\t\t\t\t\tcolor [\n");
+
+    for (i=0; i < SECTORS; i++)
+        for (j=0; j < SECTORS; j++) {
+
+           cmsVEC3 v;
+
+            pt = &gbd ->Gamut[i][j];
+
+
+            ToCartesian(&v, &pt ->p);
+
+
+        if (pt ->Type == GP_EMPTY)
+            fprintf (fp, "\t\t\t\t\t%g %g %g", 0.0, 0.0, 0.0);
+        else
+            if (pt ->Type == GP_MODELED)
+                fprintf (fp, "\t\t\t\t\t%g %g %g", 1.0, .5, .5);
+            else {
+                fprintf (fp, "\t\t\t\t\t%g %g %g", 1.0, 1.0, 1.0);
+
+            }
+
+        if ((j == SECTORS - 1) && (i == SECTORS - 1))
+                fprintf (fp, "]\n");
+            else
+                fprintf (fp, ",\n");
+    }
+    fprintf (fp, "\t\t\t}\n");
+
+
+    fprintf (fp, "\t\t\t}\n");
+    fprintf (fp, "\t\t}\n");
+    fprintf (fp, "\t]\n");
+    fprintf (fp, "}\n");
+
+    fclose (fp);
+
+    return TRUE;
+}
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/native/sun/java2d/cmm/lcms/cmstypes.c	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,4863 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+
+#include "lcms2_internal.h"
+
+// Tag Serialization  -----------------------------------------------------------------------------
+// This file implements every single tag and tag type as described in the ICC spec. Some types
+// have been deprecated, like ncl and Data. There is no implementation for those types as there
+// are no profiles holding them. The programmer can also extend this list by defining his own types
+// by using the appropiate plug-in. There are three types of plug ins regarding that. First type
+// allows to define new tags using any existing type. Next plug-in type allows to define new types
+// and the third one is very specific: allows to extend the number of elements in the multiprofile
+// elements special type.
+//--------------------------------------------------------------------------------------------------
+
+// Some broken types
+#define cmsCorbisBrokenXYZtype    ((cmsTagTypeSignature) 0x17A505B8)
+#define cmsMonacoBrokenCurveType  ((cmsTagTypeSignature) 0x9478ee00)
+
+// This is the linked list that keeps track of the defined types
+typedef struct _cmsTagTypeLinkedList_st {
+
+    cmsTagTypeHandler Handler;
+    struct _cmsTagTypeLinkedList_st* Next;
+
+} _cmsTagTypeLinkedList;
+
+// Some macros to define callbacks.
+#define READ_FN(x)  Type_##x##_Read
+#define WRITE_FN(x) Type_##x##_Write
+#define FREE_FN(x)  Type_##x##_Free
+#define DUP_FN(x)   Type_##x##_Dup
+
+// Helper macro to define a handler. Callbacks do have a fixed naming convention.
+#define TYPE_HANDLER(t, x)  { (t), READ_FN(x), WRITE_FN(x), DUP_FN(x), FREE_FN(x) }
+
+// Helper macro to define a MPE handler. Callbacks do have a fixed naming convention
+#define TYPE_MPE_HANDLER(t, x)  { (t), READ_FN(x), WRITE_FN(x), GenericMPEdup, GenericMPEfree }
+
+// Register a new type handler. This routine is shared between normal types and MPE
+static
+cmsBool RegisterTypesPlugin(cmsPluginBase* Data, _cmsTagTypeLinkedList* LinkedList, cmsUInt32Number DefaultListCount)
+{
+    cmsPluginTagType* Plugin = (cmsPluginTagType*) Data;
+    _cmsTagTypeLinkedList *pt, *Anterior = NULL;
+
+    // Calling the function with NULL as plug-in would unregister the plug in.
+    if (Data == NULL) {
+
+        LinkedList[DefaultListCount-1].Next = NULL;
+        return TRUE;
+    }
+
+    pt = Anterior = LinkedList;
+    while (pt != NULL) {
+
+        if (Plugin->Handler.Signature == pt -> Handler.Signature) {
+            pt ->Handler = Plugin ->Handler;    // Replace old behaviour.
+            // Note that since no memory is allocated, unregister does not
+            // reset this action.
+            return TRUE;
+        }
+
+        Anterior = pt;
+        pt = pt ->Next;
+    }
+
+    // Registering happens in plug-in memory pool
+    pt = (_cmsTagTypeLinkedList*) _cmsPluginMalloc(sizeof(_cmsTagTypeLinkedList));
+    if (pt == NULL) return FALSE;
+
+    pt ->Handler   = Plugin ->Handler;
+    pt ->Next      = NULL;
+
+    if (Anterior)
+        Anterior -> Next = pt;
+
+    return TRUE;
+}
+
+// Return handler for a given type or NULL if not found. Shared between normal types and MPE
+static
+cmsTagTypeHandler* GetHandler(cmsTagTypeSignature sig, _cmsTagTypeLinkedList* LinkedList)
+{
+    _cmsTagTypeLinkedList* pt;
+
+    for (pt = LinkedList;
+         pt != NULL;
+         pt = pt ->Next) {
+
+            if (sig == pt -> Handler.Signature) return &pt ->Handler;
+    }
+
+    return NULL;
+}
+
+
+// Auxiliar to convert UTF-32 to UTF-16 in some cases
+static
+cmsBool _cmsWriteWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, const wchar_t* Array)
+{
+    cmsUInt32Number i;
+
+    _cmsAssert(io != NULL);
+    _cmsAssert(Array != NULL);
+
+    for (i=0; i < n; i++) {
+        if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) Array[i])) return FALSE;
+    }
+
+    return TRUE;
+}
+
+
+// To deal with position tables
+typedef cmsBool (* PositionTableEntryFn)(struct _cms_typehandler_struct* self,
+                                             cmsIOHANDLER* io,
+                                             void* Cargo,
+                                             cmsUInt32Number n,
+                                             cmsUInt32Number SizeOfTag);
+
+// Helper function to deal with position tables as decribed in several addendums to ICC spec 4.2
+// A table of n elements is written, where first comes n records containing offsets and sizes and
+// then a block containing the data itself. This allows to reuse same data in more than one entry
+static
+cmsBool ReadPositionTable(struct _cms_typehandler_struct* self,
+                              cmsIOHANDLER* io,
+                              cmsUInt32Number Count,
+                              cmsUInt32Number BaseOffset,
+                              void *Cargo,
+                              PositionTableEntryFn ElementFn)
+{
+    cmsUInt32Number i;
+    cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL;
+
+    // Let's take the offsets to each element
+    ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number *));
+    if (ElementOffsets == NULL) goto Error;
+
+    ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number *));
+    if (ElementSizes == NULL) goto Error;
+
+    for (i=0; i < Count; i++) {
+
+        if (!_cmsReadUInt32Number(io, &ElementOffsets[i])) goto Error;
+        if (!_cmsReadUInt32Number(io, &ElementSizes[i])) goto Error;
+
+        ElementOffsets[i] += BaseOffset;
+    }
+
+    // Seek to each element and read it
+    for (i=0; i < Count; i++) {
+
+        if (!io -> Seek(io, ElementOffsets[i])) goto Error;
+
+        // This is the reader callback
+        if (!ElementFn(self, io, Cargo, i, ElementSizes[i])) goto Error;
+    }
+
+    // Success
+    if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets);
+    if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes);
+    return TRUE;
+
+Error:
+    if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets);
+    if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes);
+    return FALSE;
+}
+
+// Same as anterior, but for write position tables
+static
+cmsBool WritePositionTable(struct _cms_typehandler_struct* self,
+                               cmsIOHANDLER* io,
+                                cmsUInt32Number SizeOfTag,
+                               cmsUInt32Number Count,
+                               cmsUInt32Number BaseOffset,
+                               void *Cargo,
+                               PositionTableEntryFn ElementFn)
+{
+    cmsUInt32Number i;
+    cmsUInt32Number DirectoryPos, CurrentPos, Before;
+    cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL;
+
+     // Create table
+    ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number *));
+    if (ElementOffsets == NULL) goto Error;
+
+    ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number *));
+    if (ElementSizes == NULL) goto Error;
+
+    // Keep starting position of curve offsets
+    DirectoryPos = io ->Tell(io);
+
+    // Write a fake directory to be filled latter on
+    for (i=0; i < Count; i++) {
+
+        if (!_cmsWriteUInt32Number(io, 0)) goto Error;  // Offset
+        if (!_cmsWriteUInt32Number(io, 0)) goto Error;  // size
+    }
+
+    // Write each element. Keep track of the size as well.
+    for (i=0; i < Count; i++) {
+
+        Before = io ->Tell(io);
+        ElementOffsets[i] = Before - BaseOffset;
+
+        // Callback to write...
+        if (!ElementFn(self, io, Cargo, i, SizeOfTag)) goto Error;
+
+        // Now the size
+        ElementSizes[i] = io ->Tell(io) - Before;
+    }
+
+    // Write the directory
+    CurrentPos = io ->Tell(io);
+    if (!io ->Seek(io, DirectoryPos)) goto Error;
+
+    for (i=0; i <  Count; i++) {
+        if (!_cmsWriteUInt32Number(io, ElementOffsets[i])) goto Error;
+        if (!_cmsWriteUInt32Number(io, ElementSizes[i])) goto Error;
+    }
+
+    if (!io ->Seek(io, CurrentPos)) goto Error;
+
+    if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets);
+    if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes);
+    return TRUE;
+
+Error:
+    if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets);
+    if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes);
+    return FALSE;
+}
+
+
+// ********************************************************************************
+// Type XYZ. Only one value is allowed
+// ********************************************************************************
+
+//The XYZType contains an array of three encoded values for the XYZ tristimulus
+//values. Tristimulus values must be non-negative. The signed encoding allows for
+//implementation optimizations by minimizing the number of fixed formats.
+
+
+static
+void *Type_XYZ_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsCIEXYZ* xyz;
+
+    *nItems = 0;
+    xyz = (cmsCIEXYZ*) _cmsMallocZero(self ->ContextID, sizeof(cmsCIEXYZ));
+    if (xyz == NULL) return NULL;
+
+    if (!_cmsReadXYZNumber(io, xyz)) {
+        _cmsFree(self ->ContextID, xyz);
+        return NULL;
+    }
+
+    *nItems = 1;
+    return (void*) xyz;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+static
+cmsBool  Type_XYZ_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    return _cmsWriteXYZNumber(io, (cmsCIEXYZ*) Ptr);
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void* Type_XYZ_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsCIEXYZ));
+
+    cmsUNUSED_PARAMETER(n);
+}
+
+static
+void Type_XYZ_Free(struct _cms_typehandler_struct* self, void *Ptr)
+{
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+
+static
+cmsTagTypeSignature DecideXYZtype(cmsFloat64Number ICCVersion, const void *Data)
+{
+    return cmsSigXYZType;
+
+    cmsUNUSED_PARAMETER(ICCVersion);
+    cmsUNUSED_PARAMETER(Data);
+}
+
+
+// ********************************************************************************
+// Type chromaticity. Only one value is allowed
+// ********************************************************************************
+// The chromaticity tag type provides basic chromaticity data and type of
+// phosphors or colorants of a monitor to applications and utilities.
+
+static
+void *Type_Chromaticity_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsCIExyYTRIPLE* chrm;
+    cmsUInt16Number nChans, Table;
+
+    *nItems = 0;
+    chrm =  (cmsCIExyYTRIPLE*) _cmsMallocZero(self ->ContextID, sizeof(cmsCIExyYTRIPLE));
+    if (chrm == NULL) return NULL;
+
+    if (!_cmsReadUInt16Number(io, &nChans)) goto Error;
+
+    // Let's recover from a bug introduced in early versions of lcms1
+    if (nChans == 0 && SizeOfTag == 32) {
+
+        if (!_cmsReadUInt16Number(io, NULL)) goto Error;
+        if (!_cmsReadUInt16Number(io, &nChans)) goto Error;
+    }
+
+    if (nChans != 3) goto Error;
+
+    if (!_cmsReadUInt16Number(io, &Table)) goto Error;
+
+    if (!_cmsRead15Fixed16Number(io, &chrm ->Red.x)) goto Error;
+    if (!_cmsRead15Fixed16Number(io, &chrm ->Red.y)) goto Error;
+
+    chrm ->Red.Y = 1.0;
+
+    if (!_cmsRead15Fixed16Number(io, &chrm ->Green.x)) goto Error;
+    if (!_cmsRead15Fixed16Number(io, &chrm ->Green.y)) goto Error;
+
+    chrm ->Green.Y = 1.0;
+
+    if (!_cmsRead15Fixed16Number(io, &chrm ->Blue.x)) goto Error;
+    if (!_cmsRead15Fixed16Number(io, &chrm ->Blue.y)) goto Error;
+
+    chrm ->Blue.Y = 1.0;
+
+    *nItems = 1;
+    return (void*) chrm;
+
+Error:
+    _cmsFree(self ->ContextID, (void*) chrm);
+    return NULL;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+static
+cmsBool  SaveOneChromaticity(cmsFloat64Number x, cmsFloat64Number y, cmsIOHANDLER* io)
+{
+    if (!_cmsWriteUInt32Number(io, _cmsDoubleTo15Fixed16(x))) return FALSE;
+    if (!_cmsWriteUInt32Number(io, _cmsDoubleTo15Fixed16(y))) return FALSE;
+
+    return TRUE;
+}
+
+static
+cmsBool  Type_Chromaticity_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsCIExyYTRIPLE* chrm = (cmsCIExyYTRIPLE*) Ptr;
+
+    if (!_cmsWriteUInt16Number(io, 3)) return FALSE;        // nChannels
+    if (!_cmsWriteUInt16Number(io, 0)) return FALSE;        // Table
+
+    if (!SaveOneChromaticity(chrm -> Red.x,   chrm -> Red.y, io)) return FALSE;
+    if (!SaveOneChromaticity(chrm -> Green.x, chrm -> Green.y, io)) return FALSE;
+    if (!SaveOneChromaticity(chrm -> Blue.x,  chrm -> Blue.y, io)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void* Type_Chromaticity_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsCIExyYTRIPLE));
+    cmsUNUSED_PARAMETER(n);
+}
+
+static
+void Type_Chromaticity_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+
+// ********************************************************************************
+// Type cmsSigColorantOrderType
+// ********************************************************************************
+
+// This is an optional tag which specifies the laydown order in which colorants will
+// be printed on an n-colorant device. The laydown order may be the same as the
+// channel generation order listed in the colorantTableTag or the channel order of a
+// colour space such as CMYK, in which case this tag is not needed. When this is not
+// the case (for example, ink-towers sometimes use the order KCMY), this tag may be
+// used to specify the laydown order of the colorants.
+
+
+static
+void *Type_ColorantOrderType_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUInt8Number* ColorantOrder;
+    cmsUInt32Number Count;
+
+    *nItems = 0;
+    if (!_cmsReadUInt32Number(io, &Count)) return NULL;
+    if (Count > cmsMAXCHANNELS) return NULL;
+
+    ColorantOrder = (cmsUInt8Number*) _cmsCalloc(self ->ContextID, cmsMAXCHANNELS, sizeof(cmsUInt8Number));
+    if (ColorantOrder == NULL) return NULL;
+
+    // We use FF as end marker
+    memset(ColorantOrder, 0xFF, cmsMAXCHANNELS * sizeof(cmsUInt8Number));
+
+    if (io ->Read(io, ColorantOrder, sizeof(cmsUInt8Number), Count) != Count) {
+
+        _cmsFree(self ->ContextID, (void*) ColorantOrder);
+        return NULL;
+    }
+
+    *nItems = 1;
+    return (void*) ColorantOrder;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+static
+cmsBool Type_ColorantOrderType_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsUInt8Number*  ColorantOrder = (cmsUInt8Number*) Ptr;
+    cmsUInt32Number i, sz, Count;
+
+    // Get the length
+    for (Count=i=0; i < cmsMAXCHANNELS; i++) {
+        if (ColorantOrder[i] != 0xFF) Count++;
+    }
+
+    if (!_cmsWriteUInt32Number(io, Count)) return FALSE;
+
+    sz = Count * sizeof(cmsUInt8Number);
+    if (!io -> Write(io, sz, ColorantOrder)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void* Type_ColorantOrderType_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return _cmsDupMem(self ->ContextID, Ptr, cmsMAXCHANNELS * sizeof(cmsUInt8Number));
+
+    cmsUNUSED_PARAMETER(n);
+}
+
+
+static
+void Type_ColorantOrderType_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+// ********************************************************************************
+// Type cmsSigS15Fixed16ArrayType
+// ********************************************************************************
+// This type represents an array of generic 4-byte/32-bit fixed point quantity.
+// The number of values is determined from the size of the tag.
+
+static
+void *Type_S15Fixed16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsFloat64Number*  array_double;
+    cmsUInt32Number i, n;
+
+    *nItems = 0;
+    n = SizeOfTag / sizeof(cmsUInt32Number);
+    array_double = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, n, sizeof(cmsFloat64Number));
+    if (array_double == NULL) return NULL;
+
+    for (i=0; i < n; i++) {
+
+        if (!_cmsRead15Fixed16Number(io, &array_double[i])) {
+
+            _cmsFree(self ->ContextID, array_double);
+            return NULL;
+        }
+    }
+
+    *nItems = n;
+    return (void*) array_double;
+}
+
+static
+cmsBool Type_S15Fixed16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsFloat64Number* Value = (cmsFloat64Number*) Ptr;
+    cmsUInt32Number i;
+
+    for (i=0; i < nItems; i++) {
+
+        if (!_cmsWrite15Fixed16Number(io, Value[i])) return FALSE;
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void* Type_S15Fixed16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsFloat64Number));
+}
+
+
+static
+void Type_S15Fixed16_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+// ********************************************************************************
+// Type cmsSigU16Fixed16ArrayType
+// ********************************************************************************
+// This type represents an array of generic 4-byte/32-bit quantity.
+// The number of values is determined from the size of the tag.
+
+
+static
+void *Type_U16Fixed16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsFloat64Number*  array_double;
+    cmsUInt32Number v;
+    cmsUInt32Number i, n;
+
+    *nItems = 0;
+    n = SizeOfTag / sizeof(cmsUInt32Number);
+    array_double = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, n, sizeof(cmsFloat64Number));
+    if (array_double == NULL) return NULL;
+
+    for (i=0; i < n; i++) {
+
+        if (!_cmsReadUInt32Number(io, &v)) {
+            _cmsFree(self ->ContextID, (void*) array_double);
+            return NULL;
+        }
+
+        // Convert to cmsFloat64Number
+        array_double[i] =  (cmsFloat64Number) (v / 65536.0);
+    }
+
+    *nItems = n;
+    return (void*) array_double;
+}
+
+static
+cmsBool Type_U16Fixed16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsFloat64Number* Value = (cmsFloat64Number*) Ptr;
+    cmsUInt32Number i;
+
+    for (i=0; i < nItems; i++) {
+
+        cmsUInt32Number v = (cmsUInt32Number) floor(Value[i]*65536.0 + 0.5);
+
+        if (!_cmsWriteUInt32Number(io, v)) return FALSE;
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void* Type_U16Fixed16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsFloat64Number));
+}
+
+static
+void Type_U16Fixed16_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+// ********************************************************************************
+// Type cmsSigSignatureType
+// ********************************************************************************
+//
+// The signatureType contains a four-byte sequence, Sequences of less than four
+// characters are padded at the end with spaces, 20h.
+// Typically this type is used for registered tags that can be displayed on many
+// development systems as a sequence of four characters.
+
+static
+void *Type_Signature_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsSignature* SigPtr = (cmsSignature*) _cmsMalloc(self ->ContextID, sizeof(cmsSignature));
+    if (SigPtr == NULL) return NULL;
+
+     if (!_cmsReadUInt32Number(io, SigPtr)) return NULL;
+     *nItems = 1;
+
+     return SigPtr;
+
+     cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+static
+cmsBool  Type_Signature_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsSignature* SigPtr = (cmsSignature*) Ptr;
+
+    return _cmsWriteUInt32Number(io, *SigPtr);
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void* Type_Signature_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsSignature));
+}
+
+static
+void Type_Signature_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+
+// ********************************************************************************
+// Type cmsSigTextType
+// ********************************************************************************
+//
+// The textType is a simple text structure that contains a 7-bit ASCII text string.
+// The length of the string is obtained by subtracting 8 from the element size portion
+// of the tag itself. This string must be terminated with a 00h byte.
+
+static
+void *Type_Text_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    char* Text = NULL;
+    cmsMLU* mlu = NULL;
+
+    // Create a container
+    mlu = cmsMLUalloc(self ->ContextID, 1);
+    if (mlu == NULL) return NULL;
+
+    *nItems = 0;
+
+    // We need to store the "\0" at the end, so +1
+    Text = (char*) _cmsMalloc(self ->ContextID, SizeOfTag + 1);
+    if (Text == NULL) goto Error;
+
+    if (io -> Read(io, Text, sizeof(char), SizeOfTag) != SizeOfTag) goto Error;
+
+    // Make sure text is properly ended
+    Text[SizeOfTag] = 0;
+    *nItems = 1;
+
+    // Keep the result
+    if (!cmsMLUsetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text)) goto Error;
+
+    _cmsFree(self ->ContextID, Text);
+    return (void*) mlu;
+
+Error:
+    if (mlu != NULL)
+        cmsMLUfree(mlu);
+    if (Text != NULL)
+        _cmsFree(self ->ContextID, Text);
+
+    return NULL;
+}
+
+// The conversion implies to choose a language. So, we choose the actual language.
+static
+cmsBool Type_Text_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsMLU* mlu = (cmsMLU*) Ptr;
+    cmsUInt32Number size;
+    cmsBool  rc;
+    char* Text;
+
+    // Get the size of the string. Note there is an extra "\0" at the end
+    size = cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, NULL, 0);
+    if (size == 0) return FALSE;       // Cannot be zero!
+
+    // Create memory
+    Text = (char*) _cmsMalloc(self ->ContextID, size);
+    cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text, size);
+
+    // Write it, including separator
+    rc = io ->Write(io, size, Text);
+
+    _cmsFree(self ->ContextID, Text);
+    return rc;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+static
+void* Type_Text_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsMLUdup((cmsMLU*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void Type_Text_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsMLU* mlu = (cmsMLU*) Ptr;
+    cmsMLUfree(mlu);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+cmsTagTypeSignature DecideTextType(cmsFloat64Number ICCVersion, const void *Data)
+{
+    if (ICCVersion >= 4.0)
+        return cmsSigMultiLocalizedUnicodeType;
+
+    return cmsSigTextType;
+
+    cmsUNUSED_PARAMETER(Data);
+}
+
+
+// ********************************************************************************
+// Type cmsSigDataType
+// ********************************************************************************
+
+// General purpose data type
+static
+void *Type_Data_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsICCData* BinData;
+    cmsUInt32Number LenOfData;
+
+    *nItems = 0;
+    LenOfData = SizeOfTag - sizeof(cmsUInt32Number);
+
+    BinData = (cmsICCData*) _cmsMalloc(self ->ContextID, sizeof(cmsICCData) + LenOfData - 1);
+    if (BinData == NULL) return NULL;
+
+    BinData ->len = LenOfData;
+    if (!_cmsReadUInt32Number(io, &BinData->flag)) return NULL;
+
+    if (io -> Read(io, BinData ->data, sizeof(cmsUInt8Number), LenOfData) != LenOfData) {
+
+        _cmsFree(self ->ContextID, BinData);
+        return NULL;
+    }
+
+    *nItems = 1;
+
+    return (void*) BinData;
+}
+
+
+static
+cmsBool Type_Data_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+   cmsICCData* BinData = (cmsICCData*) Ptr;
+
+   if (!_cmsWriteUInt32Number(io, BinData ->flag)) return FALSE;
+
+   return io ->Write(io, BinData ->len, BinData ->data);
+
+   cmsUNUSED_PARAMETER(nItems);
+   cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void* Type_Data_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    cmsICCData* BinData = (cmsICCData*) Ptr;
+
+    return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsICCData) + BinData ->len - 1);
+
+    cmsUNUSED_PARAMETER(n);
+}
+
+static
+void Type_Data_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+// ********************************************************************************
+// Type cmsSigTextDescriptionType
+// ********************************************************************************
+
+static
+void *Type_Text_Description_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    char* Text = NULL;
+    cmsMLU* mlu = NULL;
+    cmsUInt32Number  AsciiCount;
+    cmsUInt32Number  i, UnicodeCode, UnicodeCount;
+    cmsUInt16Number  ScriptCodeCode, Dummy;
+    cmsUInt8Number   ScriptCodeCount;
+
+    *nItems = 0;
+
+    //  One dword should be there
+    if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL;
+
+    // Read len of ASCII
+    if (!_cmsReadUInt32Number(io, &AsciiCount)) return NULL;
+    SizeOfTag -= sizeof(cmsUInt32Number);
+
+    // Check for size
+    if (SizeOfTag < AsciiCount) return NULL;
+
+    // All seems Ok, allocate the container
+    mlu = cmsMLUalloc(self ->ContextID, 1);
+    if (mlu == NULL) return NULL;
+
+    // As many memory as size of tag
+    Text = (char*) _cmsMalloc(self ->ContextID, AsciiCount + 1);
+    if (Text == NULL) goto Error;
+
+    // Read it
+    if (io ->Read(io, Text, sizeof(char), AsciiCount) != AsciiCount) goto Error;
+    SizeOfTag -= AsciiCount;
+
+    // Make sure there is a terminator
+    Text[AsciiCount] = 0;
+
+    // Set the MLU entry. From here we can be tolerant to wrong types
+    if (!cmsMLUsetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text)) goto Error;
+    _cmsFree(self ->ContextID, (void*) Text);
+    Text = NULL;
+
+    // Skip Unicode code
+    if (SizeOfTag < 2* sizeof(cmsUInt32Number)) goto Done;
+    if (!_cmsReadUInt32Number(io, &UnicodeCode)) goto Done;
+    if (!_cmsReadUInt32Number(io, &UnicodeCount)) goto Done;
+    SizeOfTag -= 2* sizeof(cmsUInt32Number);
+
+    if (SizeOfTag < UnicodeCount*sizeof(cmsUInt16Number)) goto Done;
+
+    for (i=0; i < UnicodeCount; i++) {
+        if (!io ->Read(io, &Dummy, sizeof(cmsUInt16Number), 1)) goto Done;
+    }
+    SizeOfTag -= UnicodeCount*sizeof(cmsUInt16Number);
+
+    // Skip ScriptCode code if present. Some buggy profiles does have less
+    // data that stricttly required. We need to skip it as this type may come
+    // embedded in other types.
+
+    if (SizeOfTag >= sizeof(cmsUInt16Number) + sizeof(cmsUInt8Number) + 67) {
+
+        if (!_cmsReadUInt16Number(io, &ScriptCodeCode)) goto Done;
+        if (!_cmsReadUInt8Number(io,  &ScriptCodeCount)) goto Done;
+
+        // Skip rest of tag
+        for (i=0; i < 67; i++) {
+            if (!io ->Read(io, &Dummy, sizeof(cmsUInt8Number), 1)) goto Error;
+        }
+    }
+
+Done:
+
+    *nItems = 1;
+    return mlu;
+
+Error:
+    if (Text) _cmsFree(self ->ContextID, (void*) Text);
+    if (mlu) cmsMLUfree(mlu);
+    return NULL;
+}
+
+
+// This tag can come IN UNALIGNED SIZE. In order to prevent issues, we force zeros on description to align it
+static
+cmsBool  Type_Text_Description_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsMLU* mlu = (cmsMLU*) Ptr;
+    char *Text = NULL;
+    wchar_t *Wide = NULL;
+    cmsUInt32Number len, len_aligned, len_filler_alignment;
+    cmsBool  rc = FALSE;
+    char Filler[68];
+
+    // Used below for writting zeroes
+    memset(Filler, 0, sizeof(Filler));
+
+    // Get the len of string
+    len = cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, NULL, 0);
+
+    // From ICC3.4: It has been found that textDescriptionType can contain misaligned data
+    //(see clause 4.1 for the definition of “aligned”). Because the Unicode language
+    // code and Unicode count immediately follow the ASCII description, their
+    // alignment is not correct if the ASCII count is not a multiple of four. The
+    // ScriptCode code is misaligned when the ASCII count is odd. Profile reading and
+    // writing software must be written carefully in order to handle these alignment
+    // problems.
+
+    // Compute an aligned size
+    len_aligned = _cmsALIGNLONG(len);
+    len_filler_alignment = len_aligned - len;
+
+    // Null strings
+    if (len <= 0) {
+
+        Text = (char*)    _cmsDupMem(self ->ContextID, "", sizeof(char));
+        Wide = (wchar_t*) _cmsDupMem(self ->ContextID, L"", sizeof(wchar_t));
+    }
+    else {
+        // Create independent buffers
+        Text = (char*) _cmsCalloc(self ->ContextID, len, sizeof(char));
+        if (Text == NULL) goto Error;
+
+        Wide = (wchar_t*) _cmsCalloc(self ->ContextID, len, sizeof(wchar_t));
+        if (Wide == NULL) goto Error;
+
+        // Get both representations.
+        cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry,  Text, len * sizeof(char));
+        cmsMLUgetWide(mlu,  cmsNoLanguage, cmsNoCountry,  Wide, len * sizeof(wchar_t));
+    }
+
+  // * cmsUInt32Number       count;          * Description length
+  // * cmsInt8Number         desc[count]     * NULL terminated ascii string
+  // * cmsUInt32Number       ucLangCode;     * UniCode language code
+  // * cmsUInt32Number       ucCount;        * UniCode description length
+  // * cmsInt16Number        ucDesc[ucCount];* The UniCode description
+  // * cmsUInt16Number       scCode;         * ScriptCode code
+  // * cmsUInt8Number        scCount;        * ScriptCode count
+  // * cmsInt8Number         scDesc[67];     * ScriptCode Description
+
+    if (!_cmsWriteUInt32Number(io, len_aligned)) goto Error;
+    if (!io ->Write(io, len, Text)) goto Error;
+    if (!io ->Write(io, len_filler_alignment, Filler)) goto Error;
+
+    if (!_cmsWriteUInt32Number(io, 0)) goto Error;  // ucLanguageCode
+
+    // This part is tricky: we need an aligned tag size, and the ScriptCode part
+    // takes 70 bytes, so we need 2 extra bytes to do the alignment
+
+    if (!_cmsWriteUInt32Number(io, len_aligned+1)) goto Error;
+
+    // Note that in some compilers sizeof(cmsUInt16Number) != sizeof(wchar_t)
+    if (!_cmsWriteWCharArray(io, len, Wide)) goto Error;
+    if (!_cmsWriteUInt16Array(io, len_filler_alignment+1, (cmsUInt16Number*) Filler)) goto Error;
+
+    // ScriptCode Code & count (unused)
+    if (!_cmsWriteUInt16Number(io, 0)) goto Error;
+    if (!_cmsWriteUInt8Number(io, 0)) goto Error;
+
+    if (!io ->Write(io, 67, Filler)) goto Error;
+
+    rc = TRUE;
+
+Error:
+    if (Text) _cmsFree(self ->ContextID, Text);
+    if (Wide) _cmsFree(self ->ContextID, Wide);
+
+    return rc;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+
+static
+void* Type_Text_Description_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsMLUdup((cmsMLU*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_Text_Description_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsMLU* mlu = (cmsMLU*) Ptr;
+
+    cmsMLUfree(mlu);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+cmsTagTypeSignature DecideTextDescType(cmsFloat64Number ICCVersion, const void *Data)
+{
+    if (ICCVersion >= 4.0)
+        return cmsSigMultiLocalizedUnicodeType;
+
+    return cmsSigTextDescriptionType;
+
+    cmsUNUSED_PARAMETER(Data);
+}
+
+
+// ********************************************************************************
+// Type cmsSigCurveType
+// ********************************************************************************
+
+static
+void *Type_Curve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUInt32Number Count;
+    cmsToneCurve* NewGamma;
+    cmsUInt16Number Linear[2] = { 0, 0xffff };
+
+
+    *nItems = 0;
+    if (!_cmsReadUInt32Number(io, &Count)) return NULL;
+
+    switch (Count) {
+
+           case 0:   // Linear.
+
+               NewGamma = cmsBuildTabulatedToneCurve16(self ->ContextID, 2, Linear);
+               if (!NewGamma) return NULL;
+               *nItems = 1;
+               return NewGamma;
+
+           case 1:  // Specified as the exponent of gamma function
+               {
+                   cmsUInt16Number SingleGammaFixed;
+                   cmsFloat64Number SingleGamma;
+
+                   if (!_cmsReadUInt16Number(io, &SingleGammaFixed)) return NULL;
+                   SingleGamma = _cms8Fixed8toDouble(SingleGammaFixed);
+
+                   *nItems = 1;
+                   return cmsBuildParametricToneCurve(self ->ContextID, 1, &SingleGamma);
+               }
+
+           default:  // Curve
+
+               NewGamma = cmsBuildTabulatedToneCurve16(self ->ContextID, Count, NULL);
+               if (!NewGamma) return NULL;
+
+               if (!_cmsReadUInt16Array(io, Count, NewGamma -> Table16)) return NULL;
+
+               *nItems = 1;
+               return NewGamma;
+    }
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+static
+cmsBool  Type_Curve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsToneCurve* Curve = (cmsToneCurve*) Ptr;
+
+    if (Curve ->nSegments == 1 && Curve ->Segments[0].Type == 1) {
+
+            // Single gamma, preserve number
+            cmsUInt16Number SingleGammaFixed = _cmsDoubleTo8Fixed8(Curve ->Segments[0].Params[0]);
+
+            if (!_cmsWriteUInt32Number(io, 1)) return FALSE;
+            if (!_cmsWriteUInt16Number(io, SingleGammaFixed)) return FALSE;
+            return TRUE;
+
+    }
+
+    if (!_cmsWriteUInt32Number(io, Curve ->nEntries)) return FALSE;
+    return _cmsWriteUInt16Array(io, Curve ->nEntries, Curve ->Table16);
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void* Type_Curve_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsDupToneCurve((cmsToneCurve*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_Curve_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsToneCurve* gamma = (cmsToneCurve*) Ptr;
+
+    cmsFreeToneCurve(gamma);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigParametricCurveType
+// ********************************************************************************
+
+
+// Decide which curve type to use on writting
+static
+cmsTagTypeSignature DecideCurveType(cmsFloat64Number ICCVersion, const void *Data)
+{
+    cmsToneCurve* Curve = (cmsToneCurve*) Data;
+
+    if (ICCVersion < 4.0) return cmsSigCurveType;
+    if (Curve ->nSegments != 1) return cmsSigCurveType;          // Only 1-segment curves can be saved as parametric
+    if (Curve ->Segments[0].Type < 0) return cmsSigCurveType;    // Only non-inverted curves
+
+    return cmsSigParametricCurveType;
+}
+
+static
+void *Type_ParametricCurve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    static const int ParamsByType[] = { 1, 3, 4, 5, 7 };
+    cmsFloat64Number Params[10];
+    cmsUInt16Number Type;
+    int i, n;
+    cmsToneCurve* NewGamma;
+
+    if (!_cmsReadUInt16Number(io, &Type)) return NULL;
+    if (!_cmsReadUInt16Number(io, NULL)) return NULL;   // Reserved
+
+    if (Type > 4) {
+
+        cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown parametric curve type '%d'", Type);
+        return NULL;
+    }
+
+    memset(Params, 0, sizeof(Params));
+    n = ParamsByType[Type];
+
+    for (i=0; i < n; i++) {
+
+        if (!_cmsRead15Fixed16Number(io, &Params[i])) return NULL;
+    }
+
+    NewGamma = cmsBuildParametricToneCurve(self ->ContextID, Type+1, Params);
+
+    *nItems = 1;
+    return NewGamma;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+static
+cmsBool  Type_ParametricCurve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsToneCurve* Curve = (cmsToneCurve*) Ptr;
+    int i, nParams;
+    static const int ParamsByType[] = { 0, 1, 3, 4, 5, 7 };
+
+
+    if (Curve ->nSegments > 1 || Curve -> Segments[0].Type < 1) {
+
+        cmsSignalError(self->ContextID, 0, "Multisegment or Inverted parametric curves cannot be written");
+        return FALSE;
+    }
+
+    nParams = ParamsByType[Curve ->Segments[0].Type];
+
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) (Curve ->Segments[0].Type - 1))) return FALSE;
+    if (!_cmsWriteUInt16Number(io, 0)) return FALSE;        // Reserved
+
+    for (i=0; i < nParams; i++) {
+
+        if (!_cmsWrite15Fixed16Number(io, Curve -> Segments[0].Params[i])) return FALSE;
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+static
+void* Type_ParametricCurve_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsDupToneCurve((cmsToneCurve*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_ParametricCurve_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsToneCurve* gamma = (cmsToneCurve*) Ptr;
+
+    cmsFreeToneCurve(gamma);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigDateTimeType
+// ********************************************************************************
+
+// A 12-byte value representation of the time and date, where the byte usage is assigned
+// as specified in table 1. The actual values are encoded as 16-bit unsigned integers
+// (uInt16Number - see 5.1.6).
+//
+// All the dateTimeNumber values in a profile shall be in Coordinated Universal Time
+// (UTC, also known as GMT or ZULU Time). Profile writers are required to convert local
+// time to UTC when setting these values. Programmes that display these values may show
+// the dateTimeNumber as UTC, show the equivalent local time (at current locale), or
+// display both UTC and local versions of the dateTimeNumber.
+
+static
+void *Type_DateTime_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsDateTimeNumber timestamp;
+    struct tm * NewDateTime;
+
+    *nItems = 0;
+    NewDateTime = (struct tm*) _cmsMalloc(self ->ContextID, sizeof(struct tm));
+    if (NewDateTime == NULL) return NULL;
+
+    if (io->Read(io, &timestamp, sizeof(cmsDateTimeNumber), 1) != 1) return NULL;
+
+     _cmsDecodeDateTimeNumber(&timestamp, NewDateTime);
+
+     *nItems = 1;
+     return NewDateTime;
+
+     cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+static
+cmsBool  Type_DateTime_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    struct tm * DateTime = (struct tm*) Ptr;
+    cmsDateTimeNumber timestamp;
+
+    _cmsEncodeDateTimeNumber(&timestamp, DateTime);
+    if (!io ->Write(io, sizeof(cmsDateTimeNumber), &timestamp)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void* Type_DateTime_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return _cmsDupMem(self ->ContextID, Ptr, sizeof(struct tm));
+
+    cmsUNUSED_PARAMETER(n);
+}
+
+static
+void Type_DateTime_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+
+
+// ********************************************************************************
+// Type icMeasurementType
+// ********************************************************************************
+
+/*
+The measurementType information refers only to the internal profile data and is
+meant to provide profile makers an alternative to the default measurement
+specifications.
+*/
+
+static
+void *Type_Measurement_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsICCMeasurementConditions mc;
+
+    if (!_cmsReadUInt32Number(io, &mc.Observer)) return NULL;
+    if (!_cmsReadXYZNumber(io,    &mc.Backing)) return NULL;
+    if (!_cmsReadUInt32Number(io, &mc.Geometry)) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &mc.Flare)) return NULL;
+    if (!_cmsReadUInt32Number(io, &mc.IlluminantType)) return NULL;
+
+    *nItems = 1;
+    return _cmsDupMem(self ->ContextID, &mc, sizeof(cmsICCMeasurementConditions));
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+static
+cmsBool  Type_Measurement_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsICCMeasurementConditions* mc =(cmsICCMeasurementConditions*) Ptr;
+
+    if (!_cmsWriteUInt32Number(io, mc->Observer)) return FALSE;
+    if (!_cmsWriteXYZNumber(io,    &mc->Backing)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, mc->Geometry)) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, mc->Flare)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, mc->IlluminantType)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void* Type_Measurement_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+     return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsICCMeasurementConditions));
+
+     cmsUNUSED_PARAMETER(n);
+}
+
+static
+void Type_Measurement_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+   _cmsFree(self ->ContextID, Ptr);
+}
+
+
+// ********************************************************************************
+// Type cmsSigMultiLocalizedUnicodeType
+// ********************************************************************************
+
+//
+//   Do NOT trust SizeOfTag as there is an issue on the definition of profileSequenceDescTag. See the TechNote from
+//   Max Derhak and Rohit Patil about this: basically the size of the string table should be guessed and cannot be
+//   taken from the size of tag if this tag is embedded as part of bigger structures (profileSequenceDescTag, for instance)
+//
+// FIXME: this doesn't work if sizeof(wchat_t) != 2  !!!
+
+static
+void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsMLU* mlu;
+    cmsUInt32Number Count, RecLen, NumOfWchar;
+    cmsUInt32Number SizeOfHeader;
+    cmsUInt32Number  Len, Offset;
+    cmsUInt32Number  i;
+    cmsUInt16Number* Block;
+    cmsUInt32Number  BeginOfThisString, EndOfThisString, LargestPosition;
+
+    *nItems = 0;
+    if (!_cmsReadUInt32Number(io, &Count)) return NULL;
+    if (!_cmsReadUInt32Number(io, &RecLen)) return NULL;
+
+    if (RecLen != 12) {
+
+        cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "multiLocalizedUnicodeType of len != 12 is not supported.");
+        return NULL;
+    }
+
+    mlu = cmsMLUalloc(self ->ContextID, Count);
+    if (mlu == NULL) return NULL;
+
+    mlu ->UsedEntries = Count;
+
+    SizeOfHeader = 12 * Count + sizeof(_cmsTagBase);
+    LargestPosition = 0;
+
+    for (i=0; i < Count; i++) {
+
+        if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error;
+        if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country))  goto Error;
+
+        // Now deal with Len and offset.
+        if (!_cmsReadUInt32Number(io, &Len)) goto Error;
+        mlu ->Entries[i].Len = Len;
+
+        if (!_cmsReadUInt32Number(io, &Offset)) goto Error;
+
+        BeginOfThisString = Offset - SizeOfHeader - 8;
+        mlu ->Entries[i].StrW = BeginOfThisString;
+
+        // To guess maximum size, add offset + len
+        EndOfThisString = BeginOfThisString + Len;
+        if (EndOfThisString > LargestPosition)
+            LargestPosition = EndOfThisString;
+    }
+
+    // Now read the remaining of tag and fill all strings. Substract the directory
+    SizeOfTag   = LargestPosition;
+
+    Block = (cmsUInt16Number*) _cmsMalloc(self ->ContextID, SizeOfTag);
+    if (Block == NULL) goto Error;
+
+    NumOfWchar = SizeOfTag / sizeof(cmsUInt16Number);
+
+    if (!_cmsReadUInt16Array(io, NumOfWchar, Block)) goto Error;
+    mlu ->MemPool = Block;
+    mlu ->PoolSize = SizeOfTag;
+    mlu ->PoolUsed = SizeOfTag;
+
+    *nItems = 1;
+    return (void*) mlu;
+
+Error:
+    if (mlu) cmsMLUfree(mlu);
+    return NULL;
+}
+
+static
+cmsBool  Type_MLU_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsMLU* mlu =(cmsMLU*) Ptr;
+    cmsUInt32Number HeaderSize, Offset;
+    int i;
+
+    if (!_cmsWriteUInt32Number(io, mlu ->UsedEntries)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 12)) return FALSE;
+
+    HeaderSize = 12 * mlu ->UsedEntries + sizeof(_cmsTagBase);
+
+    for (i=0; i < mlu ->UsedEntries; i++) {
+
+        if (!_cmsWriteUInt16Number(io, mlu ->Entries[i].Language)) return FALSE;
+        if (!_cmsWriteUInt16Number(io, mlu ->Entries[i].Country))  return FALSE;
+        if (!_cmsWriteUInt32Number(io, mlu ->Entries[i].Len)) return FALSE;
+
+        Offset =  mlu ->Entries[i].StrW + HeaderSize + 8;
+
+        if (!_cmsWriteUInt32Number(io, Offset)) return FALSE;
+    }
+
+    if (!_cmsWriteUInt16Array(io, mlu ->PoolUsed / sizeof(cmsUInt16Number), (cmsUInt16Number*)  mlu ->MemPool)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void* Type_MLU_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsMLUdup((cmsMLU*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_MLU_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsMLUfree((cmsMLU*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigLut8Type
+// ********************************************************************************
+
+// Decide which LUT type to use on writting
+static
+cmsTagTypeSignature DecideLUTtypeA2B(cmsFloat64Number ICCVersion, const void *Data)
+{
+    cmsPipeline* Lut = (cmsPipeline*) Data;
+
+    if (ICCVersion < 4.0) {
+        if (Lut ->SaveAs8Bits) return cmsSigLut8Type;
+        return cmsSigLut16Type;
+    }
+    else {
+         return cmsSigLutAtoBType;
+    }
+}
+
+static
+cmsTagTypeSignature DecideLUTtypeB2A(cmsFloat64Number ICCVersion, const void *Data)
+{
+    cmsPipeline* Lut = (cmsPipeline*) Data;
+
+    if (ICCVersion < 4.0) {
+        if (Lut ->SaveAs8Bits) return cmsSigLut8Type;
+        return cmsSigLut16Type;
+    }
+    else {
+         return cmsSigLutBtoAType;
+    }
+}
+
+/*
+This structure represents a colour transform using tables of 8-bit precision.
+This type contains four processing elements: a 3 by 3 matrix (which shall be
+the identity matrix unless the input colour space is XYZ), a set of one dimensional
+input tables, a multidimensional lookup table, and a set of one dimensional output
+tables. Data is processed using these elements via the following sequence:
+(matrix) -> (1d input tables)  -> (multidimensional lookup table - CLUT) -> (1d output tables)
+
+Byte Position   Field Length (bytes)  Content Encoded as...
+8                  1          Number of Input Channels (i)    uInt8Number
+9                  1          Number of Output Channels (o)   uInt8Number
+10                 1          Number of CLUT grid points (identical for each side) (g) uInt8Number
+11                 1          Reserved for padding (fill with 00h)
+
+12..15             4          Encoded e00 parameter   s15Fixed16Number
+*/
+
+
+// Read 8 bit tables as gamma functions
+static
+cmsBool  Read8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut, int nChannels)
+{
+    cmsStage* mpe;
+    cmsUInt8Number* Temp = NULL;
+    int i, j;
+    cmsToneCurve* Tables[cmsMAXCHANNELS];
+
+    if (nChannels > cmsMAXCHANNELS) return FALSE;
+
+    memset(Tables, 0, sizeof(Tables));
+
+    Temp = (cmsUInt8Number*) _cmsMalloc(ContextID, 256);
+    if (Temp == NULL) return FALSE;
+
+    for (i=0; i < nChannels; i++) {
+        Tables[i] = cmsBuildTabulatedToneCurve16(ContextID, 256, NULL);
+        if (Tables[i] == NULL) goto Error;
+    }
+
+    for (i=0; i < nChannels; i++) {
+
+        if (io ->Read(io, Temp, 256, 1) != 1) goto Error;
+
+        for (j=0; j < 256; j++)
+            Tables[i]->Table16[j] = (cmsUInt16Number) FROM_8_TO_16(Temp[j]);
+    }
+
+    _cmsFree(ContextID, Temp);
+
+
+    mpe = cmsStageAllocToneCurves(ContextID, nChannels, Tables);
+    if (mpe == NULL) goto Error;
+
+    cmsPipelineInsertStage(lut, cmsAT_END, mpe);
+
+    for (i=0; i < nChannels; i++)
+        cmsFreeToneCurve(Tables[i]);
+
+    return TRUE;
+
+Error:
+    for (i=0; i < nChannels; i++) {
+        if (Tables[i]) cmsFreeToneCurve(Tables[i]);
+    }
+
+    if (Temp) _cmsFree(ContextID, Temp);
+    return FALSE;
+}
+
+
+static
+cmsBool Write8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsUInt32Number n, _cmsStageToneCurvesData* Tables)
+{
+    int j;
+    cmsUInt32Number i;
+    cmsUInt8Number val;
+
+    for (i=0; i < n; i++) {
+
+        if (Tables) {
+
+            if (Tables ->TheCurves[i]->nEntries != 256) {
+                cmsSignalError(ContextID, cmsERROR_RANGE, "LUT8 needs 256 entries on prelinearization");
+                return FALSE;
+            }
+
+        }
+
+        for (j=0; j < 256; j++) {
+
+            if (Tables != NULL)
+                val = (cmsUInt8Number) FROM_16_TO_8(Tables->TheCurves[i]->Table16[j]);
+            else
+                val = (cmsUInt8Number) j;
+
+            if (!_cmsWriteUInt8Number(io, val)) return FALSE;
+        }
+    }
+    return TRUE;
+}
+
+
+static
+unsigned int uipow(cmsUInt32Number a, cmsUInt32Number b) {
+    cmsUInt32Number rv = 1;
+    for (; b > 0; b--)
+        rv *= a;
+    return rv;
+}
+
+
+// That will create a MPE LUT with Matrix, pre tables, CLUT and post tables.
+// 8 bit lut may be scaled easely to v4 PCS, but we need also to properly adjust
+// PCS on BToAxx tags and AtoB if abstract. We need to fix input direction.
+
+static
+void *Type_LUT8_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUInt8Number InputChannels, OutputChannels, CLUTpoints;
+    cmsUInt8Number* Temp = NULL;
+    cmsPipeline* NewLUT = NULL;
+    cmsStage *mpemat, *mpeclut;
+    cmsUInt32Number nTabSize, i;
+    cmsFloat64Number Matrix[3*3];
+
+    *nItems = 0;
+
+    if (!_cmsReadUInt8Number(io, &InputChannels)) goto Error;
+    if (!_cmsReadUInt8Number(io, &OutputChannels)) goto Error;
+    if (!_cmsReadUInt8Number(io, &CLUTpoints)) goto Error;
+
+    // Padding
+    if (!_cmsReadUInt8Number(io, NULL)) goto Error;
+
+    // Do some checking
+
+    if (InputChannels > cmsMAXCHANNELS)  goto Error;
+    if (OutputChannels > cmsMAXCHANNELS) goto Error;
+
+   // Allocates an empty Pipeline
+    NewLUT = cmsPipelineAlloc(self ->ContextID, InputChannels, OutputChannels);
+    if (NewLUT == NULL) goto Error;
+
+    // Read the Matrix
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[0])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[1])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[2])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[3])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[4])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[5])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[6])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[7])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[8])) goto Error;
+
+
+    // Only operates if not identity...
+    if ((InputChannels == 3) && !_cmsMAT3isIdentity((cmsMAT3*) Matrix)) {
+
+        mpemat = cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL);
+        if (mpemat == NULL) goto Error;
+        cmsPipelineInsertStage(NewLUT, cmsAT_BEGIN, mpemat);
+    }
+
+    // Get input tables
+    if (!Read8bitTables(self ->ContextID, io,  NewLUT, InputChannels)) goto Error;
+
+    // Get 3D CLUT
+    nTabSize = (OutputChannels * uipow(CLUTpoints, InputChannels));
+    if (nTabSize > 0) {
+
+        cmsUInt16Number *PtrW, *T;
+        cmsUInt32Number Tsize;
+
+        Tsize = (cmsUInt32Number) nTabSize * sizeof(cmsUInt16Number);
+
+        PtrW = T  = (cmsUInt16Number*) _cmsCalloc(self ->ContextID, nTabSize, sizeof(cmsUInt16Number));
+        if (T  == NULL) goto Error;
+
+        Temp = (cmsUInt8Number*) _cmsMalloc(self ->ContextID, nTabSize);
+        if (Temp == NULL) goto Error;
+
+        if (io ->Read(io, Temp, nTabSize, 1) != 1) goto Error;
+
+        for (i = 0; i < nTabSize; i++) {
+
+            *PtrW++ = FROM_8_TO_16(Temp[i]);
+        }
+        _cmsFree(self ->ContextID, Temp);
+        Temp = NULL;
+
+
+        mpeclut = cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T);
+        if (mpeclut == NULL) goto Error;
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpeclut);
+        _cmsFree(self ->ContextID, T);
+    }
+
+
+    // Get output tables
+    if (!Read8bitTables(self ->ContextID, io,  NewLUT, OutputChannels)) goto Error;
+
+    *nItems = 1;
+    return NewLUT;
+
+Error:
+    if (NewLUT != NULL) cmsPipelineFree(NewLUT);
+    return NULL;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+// We only allow a specific MPE structure: Matrix plus prelin, plus clut, plus post-lin.
+static
+cmsBool  Type_LUT8_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsUInt32Number j, nTabSize;
+    cmsUInt8Number  val;
+    cmsPipeline* NewLUT = (cmsPipeline*) Ptr;
+    cmsStage* mpe;
+    _cmsStageToneCurvesData* PreMPE = NULL, *PostMPE = NULL;
+    _cmsStageMatrixData* MatMPE = NULL;
+    _cmsStageCLutData* clut = NULL;
+    int clutPoints;
+
+    // Disassemble the LUT into components.
+    mpe = NewLUT -> Elements;
+    if (mpe ->Type == cmsSigMatrixElemType) {
+
+        MatMPE = (_cmsStageMatrixData*) mpe ->Data;
+        mpe = mpe -> Next;
+    }
+
+    if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) {
+        PreMPE = (_cmsStageToneCurvesData*) mpe ->Data;
+        mpe = mpe -> Next;
+    }
+
+    if (mpe != NULL && mpe ->Type == cmsSigCLutElemType) {
+        clut  = (_cmsStageCLutData*) mpe -> Data;
+        mpe = mpe ->Next;
+    }
+
+    if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) {
+        PostMPE = (_cmsStageToneCurvesData*) mpe ->Data;
+        mpe = mpe -> Next;
+    }
+
+    // That should be all
+    if (mpe != NULL) {
+        cmsSignalError(mpe->ContextID, cmsERROR_UNKNOWN_EXTENSION, "LUT is not suitable to be saved as LUT8");
+        return FALSE;
+    }
+
+
+    if (clut == NULL)
+        clutPoints = 0;
+    else
+        clutPoints    = clut->Params->nSamples[0];
+
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) NewLUT ->InputChannels)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) NewLUT ->OutputChannels)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) clutPoints)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, 0)) return FALSE; // Padding
+
+
+    if (MatMPE != NULL) {
+
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[0])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[1])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[2])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[3])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[4])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[5])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[6])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[7])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[8])) return FALSE;
+
+    }
+    else {
+
+        if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
+    }
+
+    // The prelinearization table
+    if (!Write8bitTables(self ->ContextID, io, NewLUT ->InputChannels, PreMPE)) return FALSE;
+
+    nTabSize = (NewLUT->OutputChannels * uipow(clutPoints, NewLUT ->InputChannels));
+
+    // The 3D CLUT.
+    if (clut != NULL) {
+
+        for (j=0; j < nTabSize; j++) {
+
+            val = (cmsUInt8Number) FROM_16_TO_8(clut ->Tab.T[j]);
+            if (!_cmsWriteUInt8Number(io, val)) return FALSE;
+        }
+    }
+
+    // The postlinearization table
+    if (!Write8bitTables(self ->ContextID, io, NewLUT ->OutputChannels, PostMPE)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+
+static
+void* Type_LUT8_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_LUT8_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsPipelineFree((cmsPipeline*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+// ********************************************************************************
+// Type cmsSigLut16Type
+// ********************************************************************************
+
+// Read 16 bit tables as gamma functions
+static
+cmsBool  Read16bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut, int nChannels, int nEntries)
+{
+    cmsStage* mpe;
+    int i;
+    cmsToneCurve* Tables[cmsMAXCHANNELS];
+
+    // Maybe an empty table? (this is a lcms extension)
+    if (nEntries <= 0) return TRUE;
+
+    // Check for malicious profiles
+    if (nChannels > cmsMAXCHANNELS) return FALSE;
+
+    // Init table to zero
+    memset(Tables, 0, sizeof(Tables));
+
+    for (i=0; i < nChannels; i++) {
+
+        Tables[i] = cmsBuildTabulatedToneCurve16(ContextID, nEntries, NULL);
+        if (Tables[i] == NULL) goto Error;
+
+        if (!_cmsReadUInt16Array(io, nEntries, Tables[i]->Table16)) goto Error;
+    }
+
+
+    // Add the table (which may certainly be an identity, but this is up to the optimizer, not the reading code)
+    mpe = cmsStageAllocToneCurves(ContextID, nChannels, Tables);
+    if (mpe == NULL) goto Error;
+
+    cmsPipelineInsertStage(lut, cmsAT_END, mpe);
+
+    for (i=0; i < nChannels; i++)
+        cmsFreeToneCurve(Tables[i]);
+
+    return TRUE;
+
+Error:
+    for (i=0; i < nChannels; i++) {
+        if (Tables[i]) cmsFreeToneCurve(Tables[i]);
+    }
+
+    return FALSE;
+}
+
+static
+cmsBool Write16bitTables(cmsContext ContextID, cmsIOHANDLER* io, _cmsStageToneCurvesData* Tables)
+{
+    int j;
+    cmsUInt32Number i;
+    cmsUInt16Number val;
+    int nEntries = 256;
+
+    nEntries = Tables->TheCurves[0]->nEntries;
+
+    for (i=0; i < Tables ->nCurves; i++) {
+
+        for (j=0; j < nEntries; j++) {
+
+            if (Tables != NULL)
+                val = Tables->TheCurves[i]->Table16[j];
+            else
+                val = _cmsQuantizeVal(j, nEntries);
+
+            if (!_cmsWriteUInt16Number(io, val)) return FALSE;
+        }
+    }
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(ContextID);
+}
+
+static
+void *Type_LUT16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUInt8Number InputChannels, OutputChannels, CLUTpoints;
+    cmsPipeline* NewLUT = NULL;
+    cmsStage *mpemat,  *mpeclut;
+    cmsUInt32Number nTabSize;
+    cmsFloat64Number Matrix[3*3];
+    cmsUInt16Number InputEntries, OutputEntries;
+
+    *nItems = 0;
+
+    if (!_cmsReadUInt8Number(io, &InputChannels)) return NULL;
+    if (!_cmsReadUInt8Number(io, &OutputChannels)) return NULL;
+    if (!_cmsReadUInt8Number(io, &CLUTpoints)) return NULL;
+
+    // Padding
+    if (!_cmsReadUInt8Number(io, NULL)) return NULL;
+
+    // Do some checking
+    if (CLUTpoints > 100) goto Error;
+    if (InputChannels > cmsMAXCHANNELS)  goto Error;
+    if (OutputChannels > cmsMAXCHANNELS) goto Error;
+
+    // Allocates an empty LUT
+    NewLUT = cmsPipelineAlloc(self ->ContextID, InputChannels, OutputChannels);
+    if (NewLUT == NULL) goto Error;
+
+    // Read the Matrix
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[0])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[1])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[2])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[3])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[4])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[5])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[6])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[7])) goto Error;
+    if (!_cmsRead15Fixed16Number(io,  &Matrix[8])) goto Error;
+
+
+    // Only operates on 3 channels
+
+    if ((InputChannels == 3) && !_cmsMAT3isIdentity((cmsMAT3*) Matrix)) {
+
+        mpemat = cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL);
+        if (mpemat == NULL) goto Error;
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpemat);
+    }
+
+    if (!_cmsReadUInt16Number(io, &InputEntries)) return NULL;
+    if (!_cmsReadUInt16Number(io, &OutputEntries)) return NULL;
+
+
+    // Get input tables
+    if (!Read16bitTables(self ->ContextID, io,  NewLUT, InputChannels, InputEntries)) goto Error;
+
+    // Get 3D CLUT
+    nTabSize = (OutputChannels * uipow(CLUTpoints, InputChannels));
+    if (nTabSize > 0) {
+
+        cmsUInt16Number *T;
+
+        T  = (cmsUInt16Number*) _cmsCalloc(self ->ContextID, nTabSize, sizeof(cmsUInt16Number));
+        if (T  == NULL) goto Error;
+
+        if (!_cmsReadUInt16Array(io, nTabSize, T)) goto Error;
+
+        mpeclut = cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T);
+        if (mpeclut == NULL) goto Error;
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpeclut);
+        _cmsFree(self ->ContextID, T);
+    }
+
+
+    // Get output tables
+    if (!Read16bitTables(self ->ContextID, io,  NewLUT, OutputChannels, OutputEntries)) goto Error;
+
+    *nItems = 1;
+    return NewLUT;
+
+Error:
+    if (NewLUT != NULL) cmsPipelineFree(NewLUT);
+    return NULL;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+// We only allow some specific MPE structures: Matrix plus prelin, plus clut, plus post-lin.
+// Some empty defaults are created for missing parts
+
+static
+cmsBool  Type_LUT16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsUInt32Number nTabSize;
+    cmsPipeline* NewLUT = (cmsPipeline*) Ptr;
+    cmsStage* mpe;
+    _cmsStageToneCurvesData* PreMPE = NULL, *PostMPE = NULL;
+    _cmsStageMatrixData* MatMPE = NULL;
+    _cmsStageCLutData* clut = NULL;
+    int InputChannels, OutputChannels, clutPoints;
+
+    // Disassemble the LUT into components.
+    mpe = NewLUT -> Elements;
+    if (mpe != NULL && mpe ->Type == cmsSigMatrixElemType) {
+
+        MatMPE = (_cmsStageMatrixData*) mpe ->Data;
+        mpe = mpe -> Next;
+    }
+
+
+    if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) {
+        PreMPE = (_cmsStageToneCurvesData*) mpe ->Data;
+        mpe = mpe -> Next;
+    }
+
+    if (mpe != NULL && mpe ->Type == cmsSigCLutElemType) {
+        clut  = (_cmsStageCLutData*) mpe -> Data;
+        mpe = mpe ->Next;
+    }
+
+    if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) {
+        PostMPE = (_cmsStageToneCurvesData*) mpe ->Data;
+        mpe = mpe -> Next;
+    }
+
+    // That should be all
+    if (mpe != NULL) {
+        cmsSignalError(mpe->ContextID, cmsERROR_UNKNOWN_EXTENSION, "LUT is not suitable to be saved as LUT16");
+        return FALSE;
+    }
+
+    InputChannels  = cmsPipelineInputChannels(NewLUT);
+    OutputChannels = cmsPipelineOutputChannels(NewLUT);
+
+    if (clut == NULL)
+        clutPoints = 0;
+    else
+        clutPoints    = clut->Params->nSamples[0];
+
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) InputChannels)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) OutputChannels)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) clutPoints)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, 0)) return FALSE; // Padding
+
+
+    if (MatMPE != NULL) {
+
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[0])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[1])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[2])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[3])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[4])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[5])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[6])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[7])) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[8])) return FALSE;
+    }
+    else {
+
+        if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE;
+    }
+
+
+    if (PreMPE != NULL) {
+        if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) PreMPE ->TheCurves[0]->nEntries)) return FALSE;
+    } else {
+            if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
+    }
+
+    if (PostMPE != NULL) {
+        if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) PostMPE ->TheCurves[0]->nEntries)) return FALSE;
+    } else {
+        if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
+
+    }
+
+    // The prelinearization table
+
+    if (PreMPE != NULL) {
+        if (!Write16bitTables(self ->ContextID, io, PreMPE)) return FALSE;
+    }
+
+    nTabSize = (OutputChannels * uipow(clutPoints, InputChannels));
+
+    // The 3D CLUT.
+    if (clut != NULL) {
+        if (!_cmsWriteUInt16Array(io, nTabSize, clut->Tab.T)) return FALSE;
+    }
+
+    // The postlinearization table
+    if (PostMPE != NULL) {
+        if (!Write16bitTables(self ->ContextID, io, PostMPE)) return FALSE;
+    }
+
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+static
+void* Type_LUT16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_LUT16_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsPipelineFree((cmsPipeline*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigLutAToBType
+// ********************************************************************************
+
+
+// V4 stuff. Read matrix for LutAtoB and LutBtoA
+
+static
+cmsStage* ReadMatrix(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset)
+{
+    cmsFloat64Number dMat[3*3];
+    cmsFloat64Number dOff[3];
+    cmsStage* Mat;
+
+    // Go to address
+    if (!io -> Seek(io, Offset)) return NULL;
+
+    // Read the Matrix
+    if (!_cmsRead15Fixed16Number(io, &dMat[0])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dMat[1])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dMat[2])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dMat[3])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dMat[4])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dMat[5])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dMat[6])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dMat[7])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dMat[8])) return NULL;
+
+    if (!_cmsRead15Fixed16Number(io, &dOff[0])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dOff[1])) return NULL;
+    if (!_cmsRead15Fixed16Number(io, &dOff[2])) return NULL;
+
+    Mat = cmsStageAllocMatrix(self ->ContextID, 3, 3, dMat, dOff);
+
+     return Mat;
+}
+
+
+
+
+//  V4 stuff. Read CLUT part for LutAtoB and LutBtoA
+
+static
+cmsStage* ReadCLUT(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset, int InputChannels, int OutputChannels)
+{
+    cmsUInt8Number  gridPoints8[cmsMAXCHANNELS]; // Number of grid points in each dimension.
+    cmsUInt32Number GridPoints[cmsMAXCHANNELS], i;
+    cmsUInt8Number  Precision;
+    cmsStage* CLUT;
+    _cmsStageCLutData* Data;
+
+    if (!io -> Seek(io, Offset)) return NULL;
+    if (io -> Read(io, gridPoints8, cmsMAXCHANNELS, 1) != 1) return NULL;
+
+    for (i=0; i < cmsMAXCHANNELS; i++)
+        GridPoints[i] = gridPoints8[i];
+
+    if (!_cmsReadUInt8Number(io, &Precision)) return NULL;
+
+    if (!_cmsReadUInt8Number(io, NULL)) return NULL;
+    if (!_cmsReadUInt8Number(io, NULL)) return NULL;
+    if (!_cmsReadUInt8Number(io, NULL)) return NULL;
+
+    CLUT = cmsStageAllocCLut16bitGranular(self ->ContextID, GridPoints, InputChannels, OutputChannels, NULL);
+    Data = (_cmsStageCLutData*) CLUT ->Data;
+
+    // Precision can be 1 or 2 bytes
+    if (Precision == 1) {
+
+       cmsUInt8Number  v;
+
+        for (i=0; i < Data ->nEntries; i++) {
+
+                if (io ->Read(io, &v, sizeof(cmsUInt8Number), 1) != 1) return NULL;
+                Data ->Tab.T[i] = FROM_8_TO_16(v);
+        }
+
+    }
+    else
+        if (Precision == 2) {
+
+            if (!_cmsReadUInt16Array(io, Data->nEntries, Data ->Tab.T)) return NULL;
+    }
+    else {
+        cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknow precision of '%d'", Precision);
+        return NULL;
+    }
+
+
+    return CLUT;
+}
+
+static
+cmsToneCurve* ReadEmbeddedCurve(struct _cms_typehandler_struct* self, cmsIOHANDLER* io)
+{
+    cmsTagTypeSignature  BaseType;
+    cmsUInt32Number nItems;
+
+    BaseType = _cmsReadTypeBase(io);
+    switch (BaseType) {
+
+            case cmsSigCurveType:
+                return (cmsToneCurve*) Type_Curve_Read(self, io, &nItems, 0);
+
+            case cmsSigParametricCurveType:
+                return (cmsToneCurve*) Type_ParametricCurve_Read(self, io, &nItems, 0);
+
+            default:
+                {
+                    char String[5];
+
+                    _cmsTagSignature2String(String, (cmsTagSignature) BaseType);
+                    cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknow curve type '%s'", String);
+                }
+                return NULL;
+    }
+}
+
+
+// Read a set of curves from specific offset
+static
+cmsStage* ReadSetOfCurves(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset, int nCurves)
+{
+    cmsToneCurve* Curves[cmsMAXCHANNELS];
+   int i;
+    cmsStage* Lin;
+
+
+    if (nCurves > cmsMAXCHANNELS) return FALSE;
+
+    if (!io -> Seek(io, Offset)) return FALSE;
+
+    for (i=0; i < nCurves; i++) {
+
+        Curves[i] = ReadEmbeddedCurve(self, io);
+        if (Curves[i] == NULL) return FALSE;
+        if (!_cmsReadAlignment(io)) return FALSE;
+    }
+
+    Lin = cmsStageAllocToneCurves(self ->ContextID, nCurves, Curves);
+
+    for (i=0; i < nCurves; i++)
+        cmsFreeToneCurve(Curves[i]);
+
+    return Lin;
+}
+
+
+// LutAtoB type
+
+// This structure represents a colour transform. The type contains up to five processing
+// elements which are stored in the AtoBTag tag in the following order: a set of one
+// dimensional curves, a 3 by 3 matrix with offset terms, a set of one dimensional curves,
+// a multidimensional lookup table, and a set of one dimensional output curves.
+// Data are processed using these elements via the following sequence:
+//
+//("A" curves) -> (multidimensional lookup table - CLUT) -> ("M" curves) -> (matrix) -> ("B" curves).
+//
+/*
+It is possible to use any or all of these processing elements. At least one processing element
+must be included.Only the following combinations are allowed:
+
+B
+M - Matrix - B
+A - CLUT - B
+A - CLUT - M - Matrix - B
+
+*/
+
+static
+void* Type_LUTA2B_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUInt32Number      BaseOffset;
+    cmsUInt8Number       inputChan;      // Number of input channels
+    cmsUInt8Number       outputChan;     // Number of output channels
+    cmsUInt32Number      offsetB;        // Offset to first "B" curve
+    cmsUInt32Number      offsetMat;      // Offset to matrix
+    cmsUInt32Number      offsetM;        // Offset to first "M" curve
+    cmsUInt32Number      offsetC;        // Offset to CLUT
+    cmsUInt32Number      offsetA;        // Offset to first "A" curve
+    cmsStage* mpe;
+    cmsPipeline* NewLUT = NULL;
+
+
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    if (!_cmsReadUInt8Number(io, &inputChan)) return NULL;
+    if (!_cmsReadUInt8Number(io, &outputChan)) return NULL;
+
+    if (!_cmsReadUInt16Number(io, NULL)) return NULL;
+
+    if (!_cmsReadUInt32Number(io, &offsetB)) return NULL;
+    if (!_cmsReadUInt32Number(io, &offsetMat)) return NULL;
+    if (!_cmsReadUInt32Number(io, &offsetM)) return NULL;
+    if (!_cmsReadUInt32Number(io, &offsetC)) return NULL;
+    if (!_cmsReadUInt32Number(io, &offsetA)) return NULL;
+
+   // Allocates an empty LUT
+    NewLUT = cmsPipelineAlloc(self ->ContextID, inputChan, outputChan);
+    if (NewLUT == NULL) return NULL;
+
+    if (offsetA!= 0) {
+        mpe = ReadSetOfCurves(self, io, BaseOffset + offsetA, inputChan);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    if (offsetC != 0) {
+        mpe = ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    if (offsetM != 0) {
+        mpe = ReadSetOfCurves(self, io, BaseOffset + offsetM, outputChan);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    if (offsetMat != 0) {
+        mpe = ReadMatrix(self, io, BaseOffset + offsetMat);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    if (offsetB != 0) {
+        mpe = ReadSetOfCurves(self, io, BaseOffset + offsetB, outputChan);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    *nItems = 1;
+    return NewLUT;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+// Write a set of curves
+static
+cmsBool  WriteMatrix(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsStage* mpe)
+{
+    _cmsStageMatrixData* m = (_cmsStageMatrixData*) mpe -> Data;
+
+    // Write the Matrix
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[0])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[1])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[2])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[3])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[4])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[5])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[6])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[7])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Double[8])) return FALSE;
+
+    if (!_cmsWrite15Fixed16Number(io, m -> Offset[0])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Offset[1])) return FALSE;
+    if (!_cmsWrite15Fixed16Number(io, m -> Offset[2])) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// Write a set of curves
+static
+cmsBool WriteSetOfCurves(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsTagTypeSignature Type, cmsStage* mpe)
+{
+    cmsUInt32Number i, n;
+    cmsTagTypeSignature CurrentType;
+    cmsToneCurve** Curves;
+
+
+    n      = cmsStageOutputChannels(mpe);
+    Curves = _cmsStageGetPtrToCurveSet(mpe);
+
+    for (i=0; i < n; i++) {
+
+        // If this is a table-based curve, use curve type even on V4
+        CurrentType = Type;
+
+        if (Curves[i] ->nSegments == 0)
+            CurrentType = cmsSigCurveType;
+        else
+        if (Curves[i] ->Segments[0].Type < 0)
+            CurrentType = cmsSigCurveType;
+
+        if (!_cmsWriteTypeBase(io, CurrentType)) return FALSE;
+
+        switch (CurrentType) {
+
+            case cmsSigCurveType:
+                if (!Type_Curve_Write(self, io, Curves[i], 1)) return FALSE;
+                break;
+
+            case cmsSigParametricCurveType:
+                if (!Type_ParametricCurve_Write(self, io, Curves[i], 1)) return FALSE;
+                break;
+
+            default:
+                {
+                    char String[5];
+
+                    _cmsTagSignature2String(String, (cmsTagSignature) Type);
+                    cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknow curve type '%s'", String);
+                }
+                return FALSE;
+        }
+
+        if (!_cmsWriteAlignment(io)) return FALSE;
+    }
+
+
+    return TRUE;
+}
+
+
+static
+cmsBool WriteCLUT(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt8Number  Precision, cmsStage* mpe)
+{
+    cmsUInt8Number  gridPoints[cmsMAXCHANNELS]; // Number of grid points in each dimension.
+    cmsUInt32Number i;
+    _cmsStageCLutData* CLUT = ( _cmsStageCLutData*) mpe -> Data;
+
+    memset(gridPoints, 0, sizeof(gridPoints));
+    for (i=0; i < (cmsUInt32Number) CLUT ->Params ->nInputs; i++)
+        gridPoints[i] = (cmsUInt8Number) CLUT ->Params ->nSamples[i];
+
+    if (!io -> Write(io, cmsMAXCHANNELS*sizeof(cmsUInt8Number), gridPoints)) return FALSE;
+
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) Precision)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, 0)) return FALSE;
+
+    // Precision can be 1 or 2 bytes
+    if (Precision == 1) {
+
+        for (i=0; i < CLUT->nEntries; i++) {
+
+            if (!_cmsWriteUInt8Number(io, FROM_16_TO_8(CLUT->Tab.T[i]))) return FALSE;
+        }
+    }
+    else
+        if (Precision == 2) {
+
+            if (!_cmsWriteUInt16Array(io, CLUT->nEntries, CLUT ->Tab.T)) return FALSE;
+        }
+        else {
+             cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknow precision of '%d'", Precision);
+            return FALSE;
+        }
+
+        if (!_cmsWriteAlignment(io)) return FALSE;
+
+        return TRUE;
+}
+
+
+
+
+static
+cmsBool Type_LUTA2B_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsPipeline* Lut = (cmsPipeline*) Ptr;
+    int inputChan, outputChan;
+    cmsStage *A = NULL, *B = NULL, *M = NULL;
+    cmsStage * Matrix = NULL;
+    cmsStage * CLUT = NULL;
+    cmsUInt32Number offsetB = 0, offsetMat = 0, offsetM = 0, offsetC = 0, offsetA = 0;
+    cmsUInt32Number BaseOffset, DirectoryPos, CurrentPos;
+
+    // Get the base for all offsets
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    if (Lut ->Elements != NULL)
+        if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCurveSetElemType, &B))
+            if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, &M, &Matrix, &B))
+                if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &A, &CLUT, &B))
+                    if (!cmsPipelineCheckAndRetreiveStages(Lut, 5, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType,
+                        cmsSigMatrixElemType, cmsSigCurveSetElemType, &A, &CLUT, &M, &Matrix, &B)) {
+
+                            cmsSignalError(self->ContextID, cmsERROR_NOT_SUITABLE, "LUT is not suitable to be saved as LutAToB");
+                            return FALSE;
+                    }
+
+    // Get input, output channels
+    inputChan  = cmsPipelineInputChannels(Lut);
+    outputChan = cmsPipelineOutputChannels(Lut);
+
+    // Write channel count
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) inputChan)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) outputChan)) return FALSE;
+    if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
+
+    // Keep directory to be filled latter
+    DirectoryPos = io ->Tell(io);
+
+    // Write the directory
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+
+    if (A != NULL) {
+
+        offsetA = io ->Tell(io) - BaseOffset;
+        if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, A)) return FALSE;
+    }
+
+    if (CLUT != NULL) {
+        offsetC = io ->Tell(io) - BaseOffset;
+        if (!WriteCLUT(self, io, Lut ->SaveAs8Bits ? 1 : 2, CLUT)) return FALSE;
+
+    }
+    if (M != NULL) {
+
+        offsetM = io ->Tell(io) - BaseOffset;
+        if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, M)) return FALSE;
+    }
+
+    if (Matrix != NULL) {
+        offsetMat = io ->Tell(io) - BaseOffset;
+        if (!WriteMatrix(self, io, Matrix)) return FALSE;
+    }
+
+    if (B != NULL) {
+
+        offsetB = io ->Tell(io) - BaseOffset;
+        if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, B)) return FALSE;
+    }
+
+    CurrentPos = io ->Tell(io);
+
+    if (!io ->Seek(io, DirectoryPos)) return FALSE;
+
+    if (!_cmsWriteUInt32Number(io, offsetB)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, offsetMat)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, offsetM)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, offsetC)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, offsetA)) return FALSE;
+
+    if (!io ->Seek(io, CurrentPos)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+
+static
+void* Type_LUTA2B_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_LUTA2B_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsPipelineFree((cmsPipeline*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// LutBToA type
+
+static
+void* Type_LUTB2A_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUInt8Number       inputChan;      // Number of input channels
+    cmsUInt8Number       outputChan;     // Number of output channels
+    cmsUInt32Number      BaseOffset;     // Actual position in file
+    cmsUInt32Number      offsetB;        // Offset to first "B" curve
+    cmsUInt32Number      offsetMat;      // Offset to matrix
+    cmsUInt32Number      offsetM;        // Offset to first "M" curve
+    cmsUInt32Number      offsetC;        // Offset to CLUT
+    cmsUInt32Number      offsetA;        // Offset to first "A" curve
+    cmsStage* mpe;
+    cmsPipeline* NewLUT = NULL;
+
+
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    if (!_cmsReadUInt8Number(io, &inputChan)) return NULL;
+    if (!_cmsReadUInt8Number(io, &outputChan)) return NULL;
+
+    // Padding
+    if (!_cmsReadUInt16Number(io, NULL)) return NULL;
+
+    if (!_cmsReadUInt32Number(io, &offsetB)) return NULL;
+    if (!_cmsReadUInt32Number(io, &offsetMat)) return NULL;
+    if (!_cmsReadUInt32Number(io, &offsetM)) return NULL;
+    if (!_cmsReadUInt32Number(io, &offsetC)) return NULL;
+    if (!_cmsReadUInt32Number(io, &offsetA)) return NULL;
+
+    // Allocates an empty LUT
+    NewLUT = cmsPipelineAlloc(self ->ContextID, inputChan, outputChan);
+    if (NewLUT == NULL) return NULL;
+
+    if (offsetB != 0) {
+        mpe = ReadSetOfCurves(self, io, BaseOffset + offsetB, inputChan);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    if (offsetMat != 0) {
+        mpe = ReadMatrix(self, io, BaseOffset + offsetMat);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    if (offsetM != 0) {
+        mpe = ReadSetOfCurves(self, io, BaseOffset + offsetM, inputChan);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    if (offsetC != 0) {
+        mpe = ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    if (offsetA!= 0) {
+        mpe = ReadSetOfCurves(self, io, BaseOffset + offsetA, outputChan);
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    *nItems = 1;
+    return NewLUT;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+/*
+B
+B - Matrix - M
+B - CLUT - A
+B - Matrix - M - CLUT - A
+*/
+
+static
+cmsBool  Type_LUTB2A_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsPipeline* Lut = (cmsPipeline*) Ptr;
+    int inputChan, outputChan;
+    cmsStage *A = NULL, *B = NULL, *M = NULL;
+    cmsStage *Matrix = NULL;
+    cmsStage *CLUT = NULL;
+    cmsUInt32Number offsetB = 0, offsetMat = 0, offsetM = 0, offsetC = 0, offsetA = 0;
+    cmsUInt32Number BaseOffset, DirectoryPos, CurrentPos;
+
+
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCurveSetElemType, &B))
+        if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, &B, &Matrix, &M))
+            if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &B, &CLUT, &A))
+                if (!cmsPipelineCheckAndRetreiveStages(Lut, 5, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
+                    cmsSigCLutElemType, cmsSigCurveSetElemType, &B, &Matrix, &M, &CLUT, &A)) {
+                        cmsSignalError(self->ContextID, cmsERROR_NOT_SUITABLE, "LUT is not suitable to be saved as LutBToA");
+                        return FALSE;
+                }
+
+    inputChan  = cmsPipelineInputChannels(Lut);
+    outputChan = cmsPipelineOutputChannels(Lut);
+
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) inputChan)) return FALSE;
+    if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) outputChan)) return FALSE;
+    if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
+
+    DirectoryPos = io ->Tell(io);
+
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+
+    if (A != NULL) {
+
+        offsetA = io ->Tell(io) - BaseOffset;
+        if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, A)) return FALSE;
+    }
+
+    if (CLUT != NULL) {
+        offsetC = io ->Tell(io) - BaseOffset;
+        if (!WriteCLUT(self, io, Lut ->SaveAs8Bits ? 1 : 2, CLUT)) return FALSE;
+
+    }
+    if (M != NULL) {
+
+        offsetM = io ->Tell(io) - BaseOffset;
+        if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, M)) return FALSE;
+    }
+
+    if (Matrix != NULL) {
+        offsetMat = io ->Tell(io) - BaseOffset;
+        if (!WriteMatrix(self, io, Matrix)) return FALSE;
+    }
+
+    if (B != NULL) {
+
+        offsetB = io ->Tell(io) - BaseOffset;
+        if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, B)) return FALSE;
+    }
+
+    CurrentPos = io ->Tell(io);
+
+    if (!io ->Seek(io, DirectoryPos)) return FALSE;
+
+    if (!_cmsWriteUInt32Number(io, offsetB)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, offsetMat)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, offsetM)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, offsetC)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, offsetA)) return FALSE;
+
+    if (!io ->Seek(io, CurrentPos)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+
+
+static
+void* Type_LUTB2A_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_LUTB2A_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsPipelineFree((cmsPipeline*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+
+// ********************************************************************************
+// Type cmsSigColorantTableType
+// ********************************************************************************
+/*
+The purpose of this tag is to identify the colorants used in the profile by a
+unique name and set of XYZ or L*a*b* values to give the colorant an unambiguous
+value. The first colorant listed is the colorant of the first device channel of
+a lut tag. The second colorant listed is the colorant of the second device channel
+of a lut tag, and so on.
+*/
+
+static
+void *Type_ColorantTable_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUInt32Number i, Count;
+    cmsNAMEDCOLORLIST* List;
+    char Name[34];
+    cmsUInt16Number PCS[3];
+
+
+    if (!_cmsReadUInt32Number(io, &Count)) return NULL;
+
+    if (Count > cmsMAXCHANNELS) {
+        cmsSignalError(self->ContextID, cmsERROR_RANGE, "Too many colorants '%d'", Count);
+        return NULL;
+    }
+
+    List = cmsAllocNamedColorList(self ->ContextID, Count, 0, "", "");
+    for (i=0; i < Count; i++) {
+
+        if (io ->Read(io, Name, 32, 1) != 1) goto Error;
+        Name[33] = 0;
+
+        if (!_cmsReadUInt16Array(io, 3, PCS)) goto Error;
+
+        if (!cmsAppendNamedColor(List, Name, PCS, NULL)) goto Error;
+
+    }
+
+    *nItems = 1;
+    return List;
+
+Error:
+    *nItems = 0;
+    cmsFreeNamedColorList(List);
+    return NULL;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+
+// Saves a colorant table. It is using the named color structure for simplicity sake
+static
+cmsBool  Type_ColorantTable_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr;
+    int i, nColors;
+
+    nColors = cmsNamedColorCount(NamedColorList);
+
+    if (!_cmsWriteUInt32Number(io, nColors)) return FALSE;
+
+    for (i=0; i < nColors; i++) {
+
+        char root[33];
+        cmsUInt16Number PCS[3];
+
+        if (!cmsNamedColorInfo(NamedColorList, i, root, NULL, NULL, PCS, NULL)) return 0;
+        root[32] = 0;
+
+        if (!io ->Write(io, 32, root)) return FALSE;
+        if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE;
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void* Type_ColorantTable_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n)
+{
+    cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) Ptr;
+    return (void*) cmsDupNamedColorList(nc);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void Type_ColorantTable_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsFreeNamedColorList((cmsNAMEDCOLORLIST*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigNamedColor2Type
+// ********************************************************************************
+//
+//The namedColor2Type is a count value and array of structures that provide color
+//coordinates for 7-bit ASCII color names. For each named color, a PCS and optional
+//device representation of the color are given. Both representations are 16-bit values.
+//The device representation corresponds to the header’s “color space of data” field.
+//This representation should be consistent with the “number of device components”
+//field in the namedColor2Type. If this field is 0, device coordinates are not provided.
+//The PCS representation corresponds to the header’s PCS field. The PCS representation
+//is always provided. Color names are fixed-length, 32-byte fields including null
+//termination. In order to maintain maximum portability, it is strongly recommended
+//that special characters of the 7-bit ASCII set not be used.
+
+static
+void *Type_NamedColor_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+
+    cmsUInt32Number      vendorFlag;     // Bottom 16 bits for ICC use
+    cmsUInt32Number      count;          // Count of named colors
+    cmsUInt32Number      nDeviceCoords;  // Num of device coordinates
+    char                 prefix[32];     // Prefix for each color name
+    char                 suffix[32];     // Suffix for each color name
+    cmsNAMEDCOLORLIST*  v;
+    cmsUInt32Number i;
+
+
+    *nItems = 0;
+    if (!_cmsReadUInt32Number(io, &vendorFlag)) return NULL;
+    if (!_cmsReadUInt32Number(io, &count)) return NULL;
+    if (!_cmsReadUInt32Number(io, &nDeviceCoords)) return NULL;
+
+    if (io -> Read(io, prefix, 32, 1) != 1) return NULL;
+    if (io -> Read(io, suffix, 32, 1) != 1) return NULL;
+
+    prefix[31] = suffix[31] = 0;
+
+    v = cmsAllocNamedColorList(self ->ContextID, count, nDeviceCoords, prefix, suffix);
+    if (v == NULL) return NULL;
+
+    if (nDeviceCoords > cmsMAXCHANNELS) {
+        cmsSignalError(self->ContextID, cmsERROR_RANGE, "Too many device coordinates '%d'", nDeviceCoords);
+        return 0;
+    }
+    for (i=0; i < count; i++) {
+
+        cmsUInt16Number PCS[3];
+        cmsUInt16Number Colorant[cmsMAXCHANNELS];
+        char Root[33];
+
+        memset(Colorant, 0, sizeof(Colorant));
+        if (io -> Read(io, Root, 32, 1) != 1) return NULL;
+        if (!_cmsReadUInt16Array(io, 3, PCS)) goto Error;
+        if (!_cmsReadUInt16Array(io, nDeviceCoords, Colorant)) goto Error;
+
+        if (!cmsAppendNamedColor(v, Root, PCS, Colorant)) goto Error;
+    }
+
+    *nItems = 1;
+    return (void*) v ;
+
+Error:
+    cmsFreeNamedColorList(v);
+    return NULL;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+// Saves a named color list into a named color profile
+static
+cmsBool Type_NamedColor_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr;
+    char                prefix[32];     // Prefix for each color name
+    char                suffix[32];     // Suffix for each color name
+    int i, nColors;
+
+    nColors = cmsNamedColorCount(NamedColorList);
+
+    if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, nColors)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, NamedColorList ->ColorantCount)) return FALSE;
+
+    strncpy(prefix, (const char*) NamedColorList->Prefix, 32);
+    strncpy(suffix, (const char*) NamedColorList->Suffix, 32);
+
+    suffix[31] = prefix[31] = 0;
+
+    if (!io ->Write(io, 32, prefix)) return FALSE;
+    if (!io ->Write(io, 32, suffix)) return FALSE;
+
+    for (i=0; i < nColors; i++) {
+
+       cmsUInt16Number PCS[3];
+       cmsUInt16Number Colorant[cmsMAXCHANNELS];
+       char Root[33];
+
+        if (!cmsNamedColorInfo(NamedColorList, i, Root, NULL, NULL, PCS, Colorant)) return 0;
+        if (!io ->Write(io, 32 , Root)) return FALSE;
+        if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE;
+        if (!_cmsWriteUInt16Array(io, NamedColorList ->ColorantCount, Colorant)) return FALSE;
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void* Type_NamedColor_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n)
+{
+    cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) Ptr;
+
+    return (void*) cmsDupNamedColorList(nc);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void Type_NamedColor_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsFreeNamedColorList((cmsNAMEDCOLORLIST*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigProfileSequenceDescType
+// ********************************************************************************
+
+static
+cmsBool ReadEmbeddedText(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU** mlu, cmsUInt32Number SizeOfTag)
+{
+    cmsTagTypeSignature  BaseType;
+    cmsUInt32Number nItems;
+
+    BaseType = _cmsReadTypeBase(io);
+
+    switch (BaseType) {
+
+       case cmsSigTextType:
+           if (*mlu) cmsMLUfree(*mlu);
+           *mlu = (cmsMLU*)Type_Text_Read(self, io, &nItems, SizeOfTag);
+           return (*mlu != NULL);
+
+       case cmsSigTextDescriptionType:
+           if (*mlu) cmsMLUfree(*mlu);
+           *mlu =  (cmsMLU*) Type_Text_Description_Read(self, io, &nItems, SizeOfTag);
+           return (*mlu != NULL);
+
+           /*
+           TBD: Size is needed for MLU, and we have no idea on which is the available size
+           */
+
+       case cmsSigMultiLocalizedUnicodeType:
+           if (*mlu) cmsMLUfree(*mlu);
+           *mlu =  (cmsMLU*) Type_MLU_Read(self, io, &nItems, SizeOfTag);
+           return (*mlu != NULL);
+
+       default: return FALSE;
+    }
+}
+
+
+static
+void *Type_ProfileSequenceDesc_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsSEQ* OutSeq;
+    cmsUInt32Number i, Count;
+
+    *nItems = 0;
+
+    if (!_cmsReadUInt32Number(io, &Count)) return NULL;
+    SizeOfTag -= sizeof(cmsUInt32Number);
+
+
+    OutSeq = cmsAllocProfileSequenceDescription(self ->ContextID, Count);
+    if (OutSeq == NULL) return NULL;
+
+    OutSeq ->n = Count;
+
+    // Get structures as well
+
+    for (i=0; i < Count; i++) {
+
+        cmsPSEQDESC* sec = &OutSeq -> seq[i];
+
+        if (!_cmsReadUInt32Number(io, &sec ->deviceMfg)) return NULL;
+        SizeOfTag -= sizeof(cmsUInt32Number);
+
+        if (!_cmsReadUInt32Number(io, &sec ->deviceModel)) return NULL;
+        SizeOfTag -= sizeof(cmsUInt32Number);
+
+        if (!_cmsReadUInt64Number(io, &sec ->attributes)) return NULL;
+        SizeOfTag -= sizeof(cmsUInt64Number);
+
+        if (!_cmsReadUInt32Number(io, (cmsUInt32Number *)&sec ->technology)) return NULL;
+        SizeOfTag -= sizeof(cmsUInt32Number);
+
+        if (!ReadEmbeddedText(self, io, &sec ->Manufacturer, SizeOfTag)) return NULL;
+        if (!ReadEmbeddedText(self, io, &sec ->Model, SizeOfTag)) return NULL;
+    }
+
+    *nItems = 1;
+    return OutSeq;
+}
+
+
+// Aux--Embed a text description type. It can be of type text description or multilocalized unicode
+static
+cmsBool  SaveDescription(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* Text)
+{
+    if (Text == NULL) {
+
+        // Placeholder for a null entry
+        if (!_cmsWriteTypeBase(io, cmsSigTextDescriptionType)) return FALSE;
+        return Type_Text_Description_Write(self, io, NULL, 1);
+
+    }
+
+    if (Text->UsedEntries <= 1) {
+        if (!_cmsWriteTypeBase(io, cmsSigTextDescriptionType)) return FALSE;
+        return Type_Text_Description_Write(self, io, Text, 1);
+    }
+    else {
+        if (!_cmsWriteTypeBase(io, cmsSigMultiLocalizedUnicodeType)) return FALSE;
+        return Type_MLU_Write(self, io, Text, 1);
+    }
+}
+
+
+static
+cmsBool  Type_ProfileSequenceDesc_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsSEQ* Seq = (cmsSEQ*) Ptr;
+    cmsUInt32Number i;
+
+    if (!_cmsWriteUInt32Number(io, Seq->n)) return FALSE;
+
+    for (i=0; i < Seq ->n; i++) {
+
+        cmsPSEQDESC* sec = &Seq -> seq[i];
+
+        if (!_cmsWriteUInt32Number(io, sec ->deviceMfg)) return FALSE;
+        if (!_cmsWriteUInt32Number(io, sec ->deviceModel)) return FALSE;
+        if (!_cmsWriteUInt64Number(io, sec ->attributes)) return FALSE;
+        if (!_cmsWriteUInt32Number(io, sec ->technology)) return FALSE;
+
+        if (!SaveDescription(self, io, sec ->Manufacturer)) return FALSE;
+        if (!SaveDescription(self, io, sec ->Model)) return FALSE;
+    }
+
+     return TRUE;
+
+     cmsUNUSED_PARAMETER(nItems);
+}
+
+
+static
+void* Type_ProfileSequenceDesc_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsDupProfileSequenceDescription((cmsSEQ*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_ProfileSequenceDesc_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsFreeProfileSequenceDescription((cmsSEQ*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigProfileSequenceIdType
+// ********************************************************************************
+/*
+In certain workflows using ICC Device Link Profiles, it is necessary to identify the
+original profiles that were combined to create the Device Link Profile.
+This type is an array of structures, each of which contains information for
+identification of a profile used in a sequence
+*/
+
+
+static
+cmsBool ReadSeqID(struct _cms_typehandler_struct* self,
+                                             cmsIOHANDLER* io,
+                                             void* Cargo,
+                                             cmsUInt32Number n,
+                                             cmsUInt32Number SizeOfTag)
+{
+    cmsSEQ* OutSeq = (cmsSEQ*) Cargo;
+    cmsPSEQDESC* seq = &OutSeq ->seq[n];
+
+    if (io -> Read(io, seq ->ProfileID.ID8, 16, 1) != 1) return FALSE;
+    if (!ReadEmbeddedText(self, io, &seq ->Description, SizeOfTag)) return FALSE;
+
+    return TRUE;
+}
+
+
+
+static
+void *Type_ProfileSequenceId_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsSEQ* OutSeq;
+    cmsUInt32Number Count;
+    cmsUInt32Number BaseOffset;
+
+    *nItems = 0;
+
+    // Get actual position as a basis for element offsets
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    // Get table count
+    if (!_cmsReadUInt32Number(io, &Count)) return NULL;
+    SizeOfTag -= sizeof(cmsUInt32Number);
+
+    // Allocate an empty structure
+    OutSeq = cmsAllocProfileSequenceDescription(self ->ContextID, Count);
+    if (OutSeq == NULL) return NULL;
+
+
+    // Read the position table
+    if (!ReadPositionTable(self, io, Count, BaseOffset, OutSeq, ReadSeqID)) {
+
+        cmsFreeProfileSequenceDescription(OutSeq);
+        return NULL;
+    }
+
+    // Success
+    *nItems = 1;
+    return OutSeq;
+
+}
+
+
+static
+cmsBool WriteSeqID(struct _cms_typehandler_struct* self,
+                                             cmsIOHANDLER* io,
+                                             void* Cargo,
+                                             cmsUInt32Number n,
+                                             cmsUInt32Number SizeOfTag)
+{
+    cmsSEQ* Seq = (cmsSEQ*) Cargo;
+
+    if (!io ->Write(io, 16, Seq ->seq[n].ProfileID.ID8)) return FALSE;
+
+    // Store here the MLU
+    if (!SaveDescription(self, io, Seq ->seq[n].Description)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+static
+cmsBool  Type_ProfileSequenceId_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsSEQ* Seq = (cmsSEQ*) Ptr;
+    cmsUInt32Number BaseOffset;
+
+    // Keep the base offset
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    // This is the table count
+    if (!_cmsWriteUInt32Number(io, Seq ->n)) return FALSE;
+
+    // This is the position table and content
+    if (!WritePositionTable(self, io, 0, Seq ->n, BaseOffset, Seq, WriteSeqID)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+static
+void* Type_ProfileSequenceId_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsDupProfileSequenceDescription((cmsSEQ*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_ProfileSequenceId_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsFreeProfileSequenceDescription((cmsSEQ*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigUcrBgType
+// ********************************************************************************
+/*
+This type contains curves representing the under color removal and black
+generation and a text string which is a general description of the method used
+for the ucr/bg.
+*/
+
+static
+void *Type_UcrBg_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUcrBg* n = (cmsUcrBg*) _cmsMallocZero(self ->ContextID, sizeof(cmsUcrBg));
+    cmsUInt32Number CountUcr, CountBg;
+    char* ASCIIString;
+
+    *nItems = 0;
+    if (n == NULL) return NULL;
+
+    // First curve is Under color removal
+    if (!_cmsReadUInt32Number(io, &CountUcr)) return NULL;
+    SizeOfTag -= sizeof(cmsUInt32Number);
+
+    n ->Ucr = cmsBuildTabulatedToneCurve16(self ->ContextID, CountUcr, NULL);
+    if (n ->Ucr == NULL) return NULL;
+
+    if (!_cmsReadUInt16Array(io, CountUcr, n ->Ucr->Table16)) return NULL;
+    SizeOfTag -= CountUcr * sizeof(cmsUInt16Number);
+
+    // Second curve is Black generation
+    if (!_cmsReadUInt32Number(io, &CountBg)) return NULL;
+    SizeOfTag -= sizeof(cmsUInt32Number);
+
+    n ->Bg = cmsBuildTabulatedToneCurve16(self ->ContextID, CountBg, NULL);
+    if (n ->Bg == NULL) return NULL;
+    if (!_cmsReadUInt16Array(io, CountBg, n ->Bg->Table16)) return NULL;
+    SizeOfTag -= CountBg * sizeof(cmsUInt16Number);
+
+    // Now comes the text. The length is specified by the tag size
+    n ->Desc = cmsMLUalloc(self ->ContextID, 1);
+    ASCIIString = (char*) _cmsMalloc(self ->ContextID, sizeof(cmsUInt8Number)*(SizeOfTag + 1));
+    if (io ->Read(io, ASCIIString, sizeof(char), SizeOfTag) != SizeOfTag) return NULL;
+    ASCIIString[SizeOfTag] = 0;
+    cmsMLUsetASCII(n ->Desc, cmsNoLanguage, cmsNoCountry, ASCIIString);
+    _cmsFree(self ->ContextID, ASCIIString);
+
+    *nItems = 1;
+    return (void*) n;
+}
+
+static
+cmsBool  Type_UcrBg_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsUcrBg* Value = (cmsUcrBg*) Ptr;
+    cmsUInt32Number TextSize;
+    char* Text;
+
+    // First curve is Under color removal
+    if (!_cmsWriteUInt32Number(io, Value ->Ucr ->nEntries)) return FALSE;
+    if (!_cmsWriteUInt16Array(io, Value ->Ucr ->nEntries, Value ->Ucr ->Table16)) return FALSE;
+
+    // Then black generation
+    if (!_cmsWriteUInt32Number(io, Value ->Bg ->nEntries)) return FALSE;
+    if (!_cmsWriteUInt16Array(io, Value ->Bg ->nEntries, Value ->Bg ->Table16)) return FALSE;
+
+    // Now comes the text. The length is specified by the tag size
+    TextSize = cmsMLUgetASCII(Value ->Desc, cmsNoLanguage, cmsNoCountry, NULL, 0);
+    Text     = (char*) _cmsMalloc(self ->ContextID, TextSize);
+    if (cmsMLUgetASCII(Value ->Desc, cmsNoLanguage, cmsNoCountry, Text, TextSize) != TextSize) return FALSE;
+
+    if (!io ->Write(io, TextSize, Text)) return FALSE;
+    _cmsFree(self ->ContextID, Text);
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+static
+void* Type_UcrBg_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    cmsUcrBg* Src = (cmsUcrBg*) Ptr;
+    cmsUcrBg* NewUcrBg = (cmsUcrBg*) _cmsMallocZero(self ->ContextID, sizeof(cmsUcrBg));
+
+    if (NewUcrBg == NULL) return NULL;
+
+    NewUcrBg ->Bg   = cmsDupToneCurve(Src ->Bg);
+    NewUcrBg ->Ucr  = cmsDupToneCurve(Src ->Ucr);
+    NewUcrBg ->Desc = cmsMLUdup(Src ->Desc);
+
+    return (void*) NewUcrBg;
+
+    cmsUNUSED_PARAMETER(n);
+}
+
+static
+void Type_UcrBg_Free(struct _cms_typehandler_struct* self, void *Ptr)
+{
+   cmsUcrBg* Src = (cmsUcrBg*) Ptr;
+
+   if (Src ->Ucr) cmsFreeToneCurve(Src ->Ucr);
+   if (Src ->Bg)  cmsFreeToneCurve(Src ->Bg);
+   if (Src ->Desc) cmsMLUfree(Src ->Desc);
+
+   _cmsFree(self ->ContextID, Ptr);
+}
+
+// ********************************************************************************
+// Type cmsSigCrdInfoType
+// ********************************************************************************
+
+/*
+This type contains the PostScript product name to which this profile corresponds
+and the names of the companion CRDs. Recall that a single profile can generate
+multiple CRDs. It is implemented as a MLU being the language code "PS" and then
+country varies for each element:
+
+                nm: PostScript product name
+                #0: Rendering intent 0 CRD name
+                #1: Rendering intent 1 CRD name
+                #2: Rendering intent 2 CRD name
+                #3: Rendering intent 3 CRD name
+*/
+
+
+
+// Auxiliar, read an string specified as count + string
+static
+cmsBool  ReadCountAndSting(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* mlu, cmsUInt32Number* SizeOfTag, const char* Section)
+{
+    cmsUInt32Number Count;
+    char* Text;
+
+    if (*SizeOfTag < sizeof(cmsUInt32Number)) return FALSE;
+
+    if (!_cmsReadUInt32Number(io, &Count)) return FALSE;
+
+    if (*SizeOfTag < Count + sizeof(cmsUInt32Number)) return FALSE;
+    Text     = (char*) _cmsMalloc(self ->ContextID, Count+1);
+    if (Text == NULL) return FALSE;
+
+    if (io ->Read(io, Text, sizeof(cmsUInt8Number), Count) != Count) {
+        _cmsFree(self ->ContextID, Text);
+        return FALSE;
+    }
+
+    Text[Count] = 0;
+
+    cmsMLUsetASCII(mlu, "PS", Section, Text);
+    _cmsFree(self ->ContextID, Text);
+
+    *SizeOfTag -= (Count + sizeof(cmsUInt32Number));
+    return TRUE;
+}
+
+static
+cmsBool  WriteCountAndSting(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* mlu, const char* Section)
+{
+ cmsUInt32Number TextSize;
+ char* Text;
+
+    TextSize = cmsMLUgetASCII(mlu, "PS", Section, NULL, 0);
+    Text     = (char*) _cmsMalloc(self ->ContextID, TextSize);
+
+    if (!_cmsWriteUInt32Number(io, TextSize)) return FALSE;
+
+    if (cmsMLUgetASCII(mlu, "PS", Section, Text, TextSize) == 0) return FALSE;
+
+    if (!io ->Write(io, TextSize, Text)) return FALSE;
+    _cmsFree(self ->ContextID, Text);
+
+    return TRUE;
+}
+
+static
+void *Type_CrdInfo_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsMLU* mlu = cmsMLUalloc(self ->ContextID, 5);
+
+    *nItems = 0;
+    if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "nm")) goto Error;
+    if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#0")) goto Error;
+    if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#1")) goto Error;
+    if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#2")) goto Error;
+    if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#3")) goto Error;
+
+    *nItems = 1;
+    return (void*) mlu;
+
+Error:
+    cmsMLUfree(mlu);
+    return NULL;
+
+}
+
+static
+cmsBool  Type_CrdInfo_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+
+    cmsMLU* mlu = (cmsMLU*) Ptr;
+
+    if (!WriteCountAndSting(self, io, mlu, "nm")) goto Error;
+    if (!WriteCountAndSting(self, io, mlu, "#0")) goto Error;
+    if (!WriteCountAndSting(self, io, mlu, "#1")) goto Error;
+    if (!WriteCountAndSting(self, io, mlu, "#2")) goto Error;
+    if (!WriteCountAndSting(self, io, mlu, "#3")) goto Error;
+
+    return TRUE;
+
+Error:
+    return FALSE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+
+static
+void* Type_CrdInfo_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsMLUdup((cmsMLU*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_CrdInfo_Free(struct _cms_typehandler_struct* self, void *Ptr)
+{
+    cmsMLUfree((cmsMLU*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+// ********************************************************************************
+// Type cmsSigScreeningType
+// ********************************************************************************
+//
+//The screeningType describes various screening parameters including screen
+//frequency, screening angle, and spot shape.
+
+static
+void *Type_Screening_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsScreening* sc = NULL;
+    cmsUInt32Number i;
+
+    sc = (cmsScreening*) _cmsMallocZero(self ->ContextID, sizeof(cmsScreening));
+    if (sc == NULL) return NULL;
+
+    *nItems = 0;
+
+    if (!_cmsReadUInt32Number(io, &sc ->Flag)) goto Error;
+    if (!_cmsReadUInt32Number(io, &sc ->nChannels)) goto Error;
+
+    for (i=0; i < sc ->nChannels; i++) {
+
+        if (!_cmsRead15Fixed16Number(io, &sc ->Channels[i].Frequency)) goto Error;
+        if (!_cmsRead15Fixed16Number(io, &sc ->Channels[i].ScreenAngle)) goto Error;
+        if (!_cmsReadUInt32Number(io, &sc ->Channels[i].SpotShape)) goto Error;
+    }
+
+
+    *nItems = 1;
+
+    return (void*) sc;
+
+Error:
+    if (sc != NULL)
+        _cmsFree(self ->ContextID, sc);
+
+    return NULL;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+static
+cmsBool Type_Screening_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsScreening* sc = (cmsScreening* ) Ptr;
+    cmsUInt32Number i;
+
+    if (!_cmsWriteUInt32Number(io, sc ->Flag)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, sc ->nChannels)) return FALSE;
+
+    for (i=0; i < sc ->nChannels; i++) {
+
+        if (!_cmsWrite15Fixed16Number(io, sc ->Channels[i].Frequency)) return FALSE;
+        if (!_cmsWrite15Fixed16Number(io, sc ->Channels[i].ScreenAngle)) return FALSE;
+        if (!_cmsWriteUInt32Number(io, sc ->Channels[i].SpotShape)) return FALSE;
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void* Type_Screening_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+   return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsScreening));
+
+   cmsUNUSED_PARAMETER(n);
+}
+
+
+static
+void Type_Screening_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+   _cmsFree(self ->ContextID, Ptr);
+}
+
+// ********************************************************************************
+// Type cmsSigViewingConditionsType
+// ********************************************************************************
+//
+//This type represents a set of viewing condition parameters including:
+//CIE ’absolute’ illuminant white point tristimulus values and CIE ’absolute’
+//surround tristimulus values.
+
+static
+void *Type_ViewingConditions_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsICCViewingConditions* vc = NULL;
+
+    vc = (cmsICCViewingConditions*) _cmsMallocZero(self ->ContextID, sizeof(cmsICCViewingConditions));
+    if (vc == NULL) return NULL;
+
+    *nItems = 0;
+
+    if (!_cmsReadXYZNumber(io, &vc ->IlluminantXYZ)) goto Error;
+    if (!_cmsReadXYZNumber(io, &vc ->SurroundXYZ)) goto Error;
+    if (!_cmsReadUInt32Number(io, &vc ->IlluminantType)) goto Error;
+
+    *nItems = 1;
+
+    return (void*) vc;
+
+Error:
+    if (vc != NULL)
+        _cmsFree(self ->ContextID, vc);
+
+    return NULL;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+static
+cmsBool Type_ViewingConditions_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsICCViewingConditions* sc = (cmsICCViewingConditions* ) Ptr;
+
+    if (!_cmsWriteXYZNumber(io, &sc ->IlluminantXYZ)) return FALSE;
+    if (!_cmsWriteXYZNumber(io, &sc ->SurroundXYZ)) return FALSE;
+    if (!_cmsWriteUInt32Number(io, sc ->IlluminantType)) return FALSE;
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+static
+void* Type_ViewingConditions_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+   return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsScreening));
+
+   cmsUNUSED_PARAMETER(n);
+}
+
+
+static
+void Type_ViewingConditions_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+   _cmsFree(self ->ContextID, Ptr);
+}
+
+
+// ********************************************************************************
+// Type cmsSigMultiProcessElementType
+// ********************************************************************************
+
+
+static
+void* GenericMPEdup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsStageDup((cmsStage*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void GenericMPEfree(struct _cms_typehandler_struct* self, void *Ptr)
+{
+    cmsStageFree((cmsStage*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+// Each curve is stored in one or more curve segments, with break-points specified between curve segments.
+// The first curve segment always starts at –Infinity, and the last curve segment always ends at +Infinity. The
+// first and last curve segments shall be specified in terms of a formula, whereas the other segments shall be
+// specified either in terms of a formula, or by a sampled curve.
+
+
+// Read an embedded segmented curve
+static
+cmsToneCurve* ReadSegmentedCurve(struct _cms_typehandler_struct* self, cmsIOHANDLER* io)
+{
+    cmsCurveSegSignature ElementSig;
+    cmsUInt32Number i, j;
+    cmsUInt16Number nSegments;
+    cmsCurveSegment*  Segments;
+    cmsToneCurve* Curve;
+    cmsFloat32Number PrevBreak = -1E22F;    // - infinite
+
+    // Take signature and channels for each element.
+     if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) return NULL;
+
+     // That should be a segmented curve
+     if (ElementSig != cmsSigSegmentedCurve) return NULL;
+
+     if (!_cmsReadUInt32Number(io, NULL)) return NULL;
+     if (!_cmsReadUInt16Number(io, &nSegments)) return NULL;
+     if (!_cmsReadUInt16Number(io, NULL)) return NULL;
+
+     Segments = (cmsCurveSegment*) _cmsCalloc(self ->ContextID, nSegments, sizeof(cmsCurveSegment));
+     if (Segments == NULL) return NULL;
+
+     // Read breakpoints
+     for (i=0; i < (cmsUInt32Number) nSegments - 1; i++) {
+
+         Segments[i].x0 = PrevBreak;
+         if (!_cmsReadFloat32Number(io, &Segments[i].x1)) goto Error;
+         PrevBreak = Segments[i].x1;
+     }
+
+     Segments[nSegments-1].x0 = PrevBreak;
+     Segments[nSegments-1].x1 = 1E22F;     // A big cmsFloat32Number number
+
+     // Read segments
+     for (i=0; i < nSegments; i++) {
+
+          if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) goto Error;
+          if (!_cmsReadUInt32Number(io, NULL)) goto Error;
+
+           switch (ElementSig) {
+
+            case cmsSigFormulaCurveSeg: {
+
+                cmsUInt16Number Type;
+                cmsUInt32Number ParamsByType[] = {4, 5, 5 };
+
+                if (!_cmsReadUInt16Number(io, &Type)) goto Error;
+                if (!_cmsReadUInt16Number(io, NULL)) goto Error;
+
+                Segments[i].Type = Type + 6;
+                if (Type > 2) goto Error;
+
+                for (j=0; j < ParamsByType[Type]; j++) {
+
+                    cmsFloat32Number f;
+                    if (!_cmsReadFloat32Number(io, &f)) goto Error;
+                    Segments[i].Params[j] = f;
+                }
+                }
+                break;
+
+
+            case cmsSigSampledCurveSeg: {
+                cmsUInt32Number Count;
+
+                if (!_cmsReadUInt32Number(io, &Count)) return NULL;
+
+                Segments[i].nGridPoints = Count;
+                Segments[i].SampledPoints = (cmsFloat32Number*) _cmsCalloc(self ->ContextID, Count, sizeof(cmsFloat32Number));
+                if (Segments[i].SampledPoints == NULL) goto Error;
+
+                for (j=0; j < Count; j++) {
+                    if (!_cmsReadFloat32Number(io, &Segments[i].SampledPoints[j])) goto Error;
+                }
+                }
+                break;
+
+            default:
+                {
+                char String[5];
+
+                _cmsTagSignature2String(String, (cmsTagSignature) ElementSig);
+                cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown curve element type '%s' found.", String);
+                }
+                return NULL;
+
+         }
+     }
+
+     Curve = cmsBuildSegmentedToneCurve(self ->ContextID, nSegments, Segments);
+
+     for (i=0; i < nSegments; i++) {
+         if (Segments[i].SampledPoints) _cmsFree(self ->ContextID, Segments[i].SampledPoints);
+     }
+     _cmsFree(self ->ContextID, Segments);
+     return Curve;
+
+Error:
+     if (Segments) _cmsFree(self ->ContextID, Segments);
+     return NULL;
+}
+
+
+static
+cmsBool ReadMPECurve(struct _cms_typehandler_struct* self,
+                     cmsIOHANDLER* io,
+                     void* Cargo,
+                     cmsUInt32Number n,
+                     cmsUInt32Number SizeOfTag)
+{
+      cmsToneCurve** GammaTables = ( cmsToneCurve**) Cargo;
+
+      GammaTables[n] = ReadSegmentedCurve(self, io);
+      return (GammaTables[n] != NULL);
+
+      cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+static
+void *Type_MPEcurve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsStage* mpe = NULL;
+    cmsUInt16Number InputChans, OutputChans;
+    cmsUInt32Number i, BaseOffset;
+    cmsToneCurve** GammaTables;
+
+    *nItems = 0;
+
+    // Get actual position as a basis for element offsets
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
+    if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
+
+    if (InputChans != OutputChans) return NULL;
+
+    GammaTables = (cmsToneCurve**) _cmsCalloc(self ->ContextID, InputChans, sizeof(cmsToneCurve*));
+    if (GammaTables == NULL) return NULL;
+
+    if (ReadPositionTable(self, io, InputChans, BaseOffset, GammaTables, ReadMPECurve)) {
+
+        mpe = cmsStageAllocToneCurves(self ->ContextID, InputChans, GammaTables);
+    }
+    else {
+        mpe = NULL;
+    }
+
+    for (i=0; i < InputChans; i++) {
+        if (GammaTables[i]) cmsFreeToneCurve(GammaTables[i]);
+    }
+
+    _cmsFree(self ->ContextID, GammaTables);
+    *nItems = (mpe != NULL) ? 1 : 0;
+    return mpe;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+// Write a single segmented curve. NO CHECK IS PERFORMED ON VALIDITY
+static
+cmsBool WriteSegmentedCurve(cmsIOHANDLER* io, cmsToneCurve* g)
+{
+    cmsUInt32Number i, j;
+    cmsCurveSegment* Segments = g ->Segments;
+    cmsUInt32Number nSegments = g ->nSegments;
+
+    if (!_cmsWriteUInt32Number(io, cmsSigSegmentedCurve)) goto Error;
+    if (!_cmsWriteUInt32Number(io, 0)) goto Error;
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) nSegments)) goto Error;
+    if (!_cmsWriteUInt16Number(io, 0)) goto Error;
+
+    // Write the break-points
+    for (i=0; i < nSegments - 1; i++) {
+        if (!_cmsWriteFloat32Number(io, Segments[i].x1)) goto Error;
+    }
+
+    // Write the segments
+    for (i=0; i < g ->nSegments; i++) {
+
+        cmsCurveSegment* ActualSeg = Segments + i;
+
+        if (ActualSeg -> Type == 0) {
+
+            // This is a sampled curve
+            if (!_cmsWriteUInt32Number(io, (cmsUInt32Number) cmsSigSampledCurveSeg)) goto Error;
+            if (!_cmsWriteUInt32Number(io, 0)) goto Error;
+            if (!_cmsWriteUInt32Number(io, ActualSeg -> nGridPoints)) goto Error;
+
+            for (j=0; j < g ->Segments[i].nGridPoints; j++) {
+                if (!_cmsWriteFloat32Number(io, ActualSeg -> SampledPoints[j])) goto Error;
+            }
+
+        }
+        else {
+            int Type;
+            cmsUInt32Number ParamsByType[] = { 4, 5, 5 };
+
+            // This is a formula-based
+            if (!_cmsWriteUInt32Number(io, (cmsUInt32Number) cmsSigFormulaCurveSeg)) goto Error;
+            if (!_cmsWriteUInt32Number(io, 0)) goto Error;
+
+            // We only allow 1, 2 and 3 as types
+            Type = ActualSeg ->Type - 6;
+            if (Type > 2 || Type < 0) goto Error;
+
+            if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) Type)) goto Error;
+            if (!_cmsWriteUInt16Number(io, 0)) goto Error;
+
+            for (j=0; j < ParamsByType[Type]; j++) {
+                if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) ActualSeg ->Params[j])) goto Error;
+            }
+        }
+
+        // It seems there is no need to align. Code is here, and for safety commented out
+        // if (!_cmsWriteAlignment(io)) goto Error;
+    }
+
+    return TRUE;
+
+Error:
+    return FALSE;
+}
+
+
+static
+cmsBool WriteMPECurve(struct _cms_typehandler_struct* self,
+                      cmsIOHANDLER* io,
+                      void* Cargo,
+                      cmsUInt32Number n,
+                      cmsUInt32Number SizeOfTag)
+{
+    _cmsStageToneCurvesData* Curves  = (_cmsStageToneCurvesData*) Cargo;
+
+    return WriteSegmentedCurve(io, Curves ->TheCurves[n]);
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+    cmsUNUSED_PARAMETER(self);
+}
+
+// Write a curve, checking first for validity
+static
+cmsBool  Type_MPEcurve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsUInt32Number BaseOffset;
+    cmsStage* mpe = (cmsStage*) Ptr;
+    _cmsStageToneCurvesData* Curves = (_cmsStageToneCurvesData*) mpe ->Data;
+
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    // Write the header. Since those are curves, input and output channels are same
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE;
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE;
+
+    if (!WritePositionTable(self, io, 0,
+                                mpe ->InputChannels, BaseOffset, Curves, WriteMPECurve)) return FALSE;
+
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+
+
+// The matrix is organized as an array of PxQ+Q elements, where P is the number of input channels to the
+// matrix, and Q is the number of output channels. The matrix elements are each float32Numbers. The array
+// is organized as follows:
+// array = [e11, e12, …, e1P, e21, e22, …, e2P, …, eQ1, eQ2, …, eQP, e1, e2, …, eQ]
+
+static
+void *Type_MPEmatrix_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsStage* mpe;
+    cmsUInt16Number   InputChans, OutputChans;
+    cmsUInt32Number   nElems, i;
+    cmsFloat64Number* Matrix;
+    cmsFloat64Number* Offsets;
+
+    if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
+    if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
+
+
+    nElems = InputChans * OutputChans;
+
+    // Input and output chans may be ANY (up to 0xffff)
+    Matrix = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, nElems, sizeof(cmsFloat64Number));
+    if (Matrix == NULL) return NULL;
+
+    Offsets = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, OutputChans, sizeof(cmsFloat64Number));
+    if (Offsets == NULL) {
+
+        _cmsFree(self ->ContextID, Matrix);
+        return NULL;
+    }
+
+    for (i=0; i < nElems; i++) {
+
+        cmsFloat32Number v;
+
+        if (!_cmsReadFloat32Number(io, &v)) return NULL;
+        Matrix[i] = v;
+    }
+
+
+    for (i=0; i < OutputChans; i++) {
+
+        cmsFloat32Number v;
+
+        if (!_cmsReadFloat32Number(io, &v)) return NULL;
+        Offsets[i] = v;
+    }
+
+
+    mpe = cmsStageAllocMatrix(self ->ContextID, OutputChans, InputChans, Matrix, Offsets);
+    _cmsFree(self ->ContextID, Matrix);
+    _cmsFree(self ->ContextID, Offsets);
+
+    *nItems = 1;
+
+    return mpe;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+static
+cmsBool  Type_MPEmatrix_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsUInt32Number i, nElems;
+    cmsStage* mpe = (cmsStage*) Ptr;
+    _cmsStageMatrixData* Matrix = (_cmsStageMatrixData*) mpe ->Data;
+
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE;
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->OutputChannels)) return FALSE;
+
+    nElems = mpe ->InputChannels * mpe ->OutputChannels;
+
+    for (i=0; i < nElems; i++) {
+        if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) Matrix->Double[i])) return FALSE;
+    }
+
+
+    for (i=0; i < mpe ->OutputChannels; i++) {
+
+        if (Matrix ->Offset == NULL) {
+
+               if (!_cmsWriteFloat32Number(io, 0)) return FALSE;
+        }
+        else {
+               if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) Matrix->Offset[i])) return FALSE;
+        }
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+
+static
+void *Type_MPEclut_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsStage* mpe = NULL;
+    cmsUInt16Number InputChans, OutputChans;
+    cmsUInt8Number Dimensions8[16];
+    cmsUInt32Number i, nMaxGrids, GridPoints[MAX_INPUT_DIMENSIONS];
+    _cmsStageCLutData* clut;
+
+    if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
+    if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
+
+    if (io ->Read(io, Dimensions8, sizeof(cmsUInt8Number), 16) != 16)
+        goto Error;
+
+    // Copy MAX_INPUT_DIMENSIONS at most. Expand to cmsUInt32Number
+    nMaxGrids = InputChans > MAX_INPUT_DIMENSIONS ? MAX_INPUT_DIMENSIONS : InputChans;
+    for (i=0; i < nMaxGrids; i++) GridPoints[i] = Dimensions8[i];
+
+    // Allocate the true CLUT
+    mpe = cmsStageAllocCLutFloatGranular(self ->ContextID, GridPoints, InputChans, OutputChans, NULL);
+    if (mpe == NULL) goto Error;
+
+    // Read the data
+    clut = (_cmsStageCLutData*) mpe ->Data;
+    for (i=0; i < clut ->nEntries; i++) {
+
+        if (!_cmsReadFloat32Number(io, &clut ->Tab.TFloat[i])) goto Error;
+    }
+
+    *nItems = 1;
+    return mpe;
+
+Error:
+    *nItems = 0;
+    if (mpe != NULL) cmsStageFree(mpe);
+    return NULL;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+// Write a CLUT in floating point
+static
+cmsBool  Type_MPEclut_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsUInt8Number Dimensions8[16];
+    cmsUInt32Number i;
+    cmsStage* mpe = (cmsStage*) Ptr;
+    _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe ->Data;
+
+    // Check for maximum number of channels
+    if (mpe -> InputChannels > 15) return FALSE;
+
+    // Only floats are supported in MPE
+    if (clut ->HasFloatValues == FALSE) return FALSE;
+
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE;
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->OutputChannels)) return FALSE;
+
+    memset(Dimensions8, 0, sizeof(Dimensions8));
+
+    for (i=0; i < mpe ->InputChannels; i++)
+        Dimensions8[i] = (cmsUInt8Number) clut ->Params ->nSamples[i];
+
+    if (!io ->Write(io, 16, Dimensions8)) return FALSE;
+
+    for (i=0; i < clut ->nEntries; i++) {
+
+        if (!_cmsWriteFloat32Number(io, clut ->Tab.TFloat[i])) return FALSE;
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(nItems);
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+
+// This is the list of built-in MPE types
+static _cmsTagTypeLinkedList SupportedMPEtypes[] = {
+
+{{ (cmsTagTypeSignature) cmsSigBAcsElemType, NULL, NULL, NULL, NULL }, &SupportedMPEtypes[1] },   // Ignore those elements for now
+{{ (cmsTagTypeSignature) cmsSigEAcsElemType, NULL, NULL, NULL, NULL }, &SupportedMPEtypes[2] },   // (That's what the spec says)
+
+{TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigCurveSetElemType,     MPEcurve),      &SupportedMPEtypes[3] },
+{TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigMatrixElemType,       MPEmatrix),     &SupportedMPEtypes[4] },
+{TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigCLutElemType,         MPEclut),        NULL },
+};
+
+#define DEFAULT_MPE_TYPE_COUNT  (sizeof(SupportedMPEtypes) / sizeof(_cmsTagTypeLinkedList))
+
+static
+cmsBool ReadMPEElem(struct _cms_typehandler_struct* self,
+                    cmsIOHANDLER* io,
+                    void* Cargo,
+                    cmsUInt32Number n,
+                    cmsUInt32Number SizeOfTag)
+{
+    cmsStageSignature ElementSig;
+    cmsTagTypeHandler* TypeHandler;
+    cmsStage *mpe = NULL;
+    cmsUInt32Number nItems;
+    cmsPipeline *NewLUT = (cmsPipeline *) Cargo;
+
+    // Take signature and channels for each element.
+    if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) return FALSE;
+
+    // The reserved placeholder
+    if (!_cmsReadUInt32Number(io, NULL)) return FALSE;
+
+    // Read diverse MPE types
+    TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, SupportedMPEtypes);
+    if (TypeHandler == NULL)  {
+
+        char String[5];
+
+        _cmsTagSignature2String(String, (cmsTagSignature) ElementSig);
+
+        // An unknown element was found.
+        cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown MPE type '%s' found.", String);
+        return FALSE;
+    }
+
+    // If no read method, just ignore the element (valid for cmsSigBAcsElemType and cmsSigEAcsElemType)
+    // Read the MPE. No size is given
+    if (TypeHandler ->ReadPtr != NULL) {
+
+        // This is a real element which should be read and processed
+        mpe = (cmsStage*) TypeHandler ->ReadPtr(self, io, &nItems, SizeOfTag);
+        if (mpe == NULL) return FALSE;
+
+        // All seems ok, insert element
+        cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+    cmsUNUSED_PARAMETER(n);
+}
+
+
+// This is the main dispatcher for MPE
+static
+void *Type_MPE_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
+{
+    cmsUInt16Number InputChans, OutputChans;
+    cmsUInt32Number ElementCount;
+    cmsPipeline *NewLUT = NULL;
+    cmsUInt32Number BaseOffset;
+
+    // Get actual position as a basis for element offsets
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    // Read channels and element count
+    if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
+    if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
+
+    // Allocates an empty LUT
+    NewLUT = cmsPipelineAlloc(self ->ContextID, InputChans, OutputChans);
+    if (NewLUT == NULL) return NULL;
+
+    if (!_cmsReadUInt32Number(io, &ElementCount)) return NULL;
+
+    if (!ReadPositionTable(self, io, ElementCount, BaseOffset, NewLUT, ReadMPEElem)) {
+        if (NewLUT != NULL) cmsPipelineFree(NewLUT);
+        *nItems = 0;
+        return NULL;
+    }
+
+    // Success
+    *nItems = 1;
+    return NewLUT;
+
+    cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+
+// This one is a liitle bit more complex, so we don't use position tables this time.
+static
+cmsBool Type_MPE_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsUInt32Number i, BaseOffset, DirectoryPos, CurrentPos;
+    int inputChan, outputChan;
+    cmsUInt32Number ElemCount;
+    cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL, Before;
+    cmsStageSignature ElementSig;
+    cmsPipeline* Lut = (cmsPipeline*) Ptr;
+    cmsStage* Elem = Lut ->Elements;
+    cmsTagTypeHandler* TypeHandler;
+
+    BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase);
+
+    inputChan  = cmsPipelineInputChannels(Lut);
+    outputChan = cmsPipelineOutputChannels(Lut);
+    ElemCount  = cmsPipelineStageCount(Lut);
+
+    ElementOffsets = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number *));
+    if (ElementOffsets == NULL) goto Error;
+
+    ElementSizes = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number *));
+    if (ElementSizes == NULL) goto Error;
+
+    // Write the head
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) inputChan)) goto Error;
+    if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) outputChan)) goto Error;
+    if (!_cmsWriteUInt32Number(io, (cmsUInt16Number) ElemCount)) goto Error;
+
+    DirectoryPos = io ->Tell(io);
+
+    // Write a fake directory to be filled latter on
+    for (i=0; i < ElemCount; i++) {
+        if (!_cmsWriteUInt32Number(io, 0)) goto Error;  // Offset
+        if (!_cmsWriteUInt32Number(io, 0)) goto Error;  // size
+    }
+
+    // Write each single tag. Keep track of the size as well.
+    for (i=0; i < ElemCount; i++) {
+
+        ElementOffsets[i] = io ->Tell(io) - BaseOffset;
+
+        ElementSig = Elem ->Type;
+
+        TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, SupportedMPEtypes);
+        if (TypeHandler == NULL)  {
+
+                char String[5];
+
+                _cmsTagSignature2String(String, (cmsTagSignature) ElementSig);
+
+                 // An unknow element was found.
+                 cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Found unknown MPE type '%s'", String);
+                 goto Error;
+        }
+
+        if (!_cmsWriteUInt32Number(io, ElementSig)) goto Error;
+        if (!_cmsWriteUInt32Number(io, 0)) goto Error;
+        Before = io ->Tell(io);
+        if (!TypeHandler ->WritePtr(self, io, Elem, 1)) goto Error;
+        if (!_cmsWriteAlignment(io)) goto Error;
+
+        ElementSizes[i] = io ->Tell(io) - Before;
+
+        Elem = Elem ->Next;
+    }
+
+    // Write the directory
+    CurrentPos = io ->Tell(io);
+
+    if (!io ->Seek(io, DirectoryPos)) goto Error;
+
+    for (i=0; i < ElemCount; i++) {
+        if (!_cmsWriteUInt32Number(io, ElementOffsets[i])) goto Error;
+        if (!_cmsWriteUInt32Number(io, ElementSizes[i])) goto Error;
+    }
+
+    if (!io ->Seek(io, CurrentPos)) goto Error;
+
+    if (ElementOffsets != NULL) _cmsFree(self ->ContextID, ElementOffsets);
+    if (ElementSizes != NULL) _cmsFree(self ->ContextID, ElementSizes);
+    return TRUE;
+
+Error:
+    if (ElementOffsets != NULL) _cmsFree(self ->ContextID, ElementOffsets);
+    if (ElementSizes != NULL) _cmsFree(self ->ContextID, ElementSizes);
+    return FALSE;
+
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+
+static
+void* Type_MPE_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
+
+    cmsUNUSED_PARAMETER(n);
+    cmsUNUSED_PARAMETER(self);
+}
+
+static
+void Type_MPE_Free(struct _cms_typehandler_struct* self, void *Ptr)
+{
+    cmsPipelineFree((cmsPipeline*) Ptr);
+    return;
+
+    cmsUNUSED_PARAMETER(self);
+}
+
+
+// ********************************************************************************
+// Type cmsSigVcgtType
+// ********************************************************************************
+
+
+#define cmsVideoCardGammaTableType    0
+#define cmsVideoCardGammaFormulaType  1
+
+// Used internally
+typedef struct {
+    double Gamma;
+    double Min;
+    double Max;
+} _cmsVCGTGAMMA;
+
+
+static
+void *Type_vcgt_Read(struct _cms_typehandler_struct* self,
+                     cmsIOHANDLER* io,
+                     cmsUInt32Number* nItems,
+                     cmsUInt32Number SizeOfTag)
+{
+    cmsUInt32Number TagType, n, i;
+    cmsToneCurve** Curves;
+
+    *nItems = 0;
+
+    // Read tag type
+    if (!_cmsReadUInt32Number(io, &TagType)) return NULL;
+
+    // Allocate space for the array
+    Curves = ( cmsToneCurve**) _cmsCalloc(self ->ContextID, 3, sizeof(cmsToneCurve*));
+    if (Curves == NULL) return NULL;
+
+    // There are two possible flavors
+    switch (TagType) {
+
+    // Gamma is stored as a table
+    case cmsVideoCardGammaTableType:
+    {
+       cmsUInt16Number nChannels, nElems, nBytes;
+
+       // Check channel count, which should be 3 (we don't support monochrome this time)
+       if (!_cmsReadUInt16Number(io, &nChannels)) goto Error;
+
+       if (nChannels != 3) {
+           cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported number of channels for VCGT '%d'", nChannels);
+           goto Error;
+       }
+
+       // Get Table element count and bytes per element
+       if (!_cmsReadUInt16Number(io, &nElems)) goto Error;
+       if (!_cmsReadUInt16Number(io, &nBytes)) goto Error;
+
+       // Populate tone curves
+       for (n=0; n < 3; n++) {
+
+           Curves[n] = cmsBuildTabulatedToneCurve16(self ->ContextID, nElems, NULL);
+           if (Curves[n] == NULL) goto Error;
+
+           // On depending on byte depth
+           switch (nBytes) {
+
+           // One byte, 0..255
+           case 1:
+               for (i=0; i < nElems; i++) {
+
+                   cmsUInt8Number v;
+
+                      if (!_cmsReadUInt8Number(io, &v)) goto Error;
+                      Curves[n] ->Table16[i] = FROM_8_TO_16(v);
+               }
+               break;
+
+           // One word 0..65535
+           case 2:
+              if (!_cmsReadUInt16Array(io, nElems, Curves[n]->Table16)) goto Error;
+              break;
+
+          // Unsupported
+           default:
+              cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported bit depth for VCGT '%d'", nBytes * 8);
+              goto Error;
+           }
+       } // For all 3 channels
+    }
+    break;
+
+   // In this case, gamma is stored as a formula
+   case cmsVideoCardGammaFormulaType:
+   {
+       _cmsVCGTGAMMA Colorant[3];
+
+        // Populate tone curves
+       for (n=0; n < 3; n++) {
+
+           double Params[10];
+
+           if (!_cmsRead15Fixed16Number(io, &Colorant[n].Gamma)) goto Error;
+           if (!_cmsRead15Fixed16Number(io, &Colorant[n].Min)) goto Error;
+           if (!_cmsRead15Fixed16Number(io, &Colorant[n].Max)) goto Error;
+
+            // Parametric curve type 5 is:
+            // Y = (aX + b)^Gamma + e | X >= d
+            // Y = cX + f             | X < d
+
+            // vcgt formula is:
+            // Y = (Max – Min) * (X ^ Gamma) + Min
+
+            // So, the translation is
+            // a = (Max – Min) ^ ( 1 / Gamma)
+            // e = Min
+            // b=c=d=f=0
+
+           Params[0] = Colorant[n].Gamma;
+           Params[1] = pow((Colorant[n].Max - Colorant[n].Min), (1.0 / Colorant[n].Gamma));
+           Params[2] = 0;
+           Params[3] = 0;
+           Params[4] = 0;
+           Params[5] = Colorant[n].Min;
+           Params[6] = 0;
+
+           Curves[n] = cmsBuildParametricToneCurve(self ->ContextID, 5, Params);
+           if (Curves[n] == NULL) goto Error;
+       }
+   }
+   break;
+
+   // Unsupported
+   default:
+      cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag type for VCGT '%d'", TagType);
+      goto Error;
+   }
+
+   *nItems = 1;
+   return (void*) Curves;
+
+// Regret,  free all resources
+Error:
+
+    cmsFreeToneCurveTriple(Curves);
+    _cmsFree(self ->ContextID, Curves);
+    return NULL;
+
+     cmsUNUSED_PARAMETER(SizeOfTag);
+}
+
+
+// We don't support all flavors, only 16bits tables and formula
+static
+cmsBool Type_vcgt_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
+{
+    cmsToneCurve** Curves =  (cmsToneCurve**) Ptr;
+    cmsUInt32Number i, j;
+
+    if (cmsGetToneCurveParametricType(Curves[0]) == 5 &&
+        cmsGetToneCurveParametricType(Curves[1]) == 5 &&
+        cmsGetToneCurveParametricType(Curves[2]) == 5) {
+
+        if (!_cmsWriteUInt32Number(io, cmsVideoCardGammaFormulaType)) return FALSE;
+
+        // Save parameters
+        for (i=0; i < 3; i++) {
+
+            _cmsVCGTGAMMA v;
+
+            v.Gamma = Curves[i] ->Segments[0].Params[0];
+            v.Min   = Curves[i] ->Segments[0].Params[5];
+            v.Max   = pow(Curves[i] ->Segments[0].Params[1], v.Gamma) + v.Min;
+
+            if (!_cmsWrite15Fixed16Number(io, v.Gamma)) return FALSE;
+            if (!_cmsWrite15Fixed16Number(io, v.Min)) return FALSE;
+            if (!_cmsWrite15Fixed16Number(io, v.Max)) return FALSE;
+        }
+    }
+
+    else {
+
+        // Always store as a table of 256 words
+        if (!_cmsWriteUInt32Number(io, cmsVideoCardGammaTableType)) return FALSE;
+        if (!_cmsWriteUInt16Number(io, 3)) return FALSE;
+        if (!_cmsWriteUInt16Number(io, 256)) return FALSE;
+        if (!_cmsWriteUInt16Number(io, 2)) return FALSE;
+
+        for (i=0; i < 3; i++) {
+            for (j=0; j < 256; j++) {
+
+                cmsFloat32Number v = cmsEvalToneCurveFloat(Curves[i], (cmsFloat32Number) (j / 255.0));
+                cmsUInt16Number  n = _cmsQuickSaturateWord(v * 65535.0);
+
+                if (!_cmsWriteUInt16Number(io, n)) return FALSE;
+            }
+        }
+    }
+
+    return TRUE;
+
+    cmsUNUSED_PARAMETER(self);
+    cmsUNUSED_PARAMETER(nItems);
+}
+
+static
+void* Type_vcgt_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
+{
+    cmsToneCurve** OldCurves =  (cmsToneCurve**) Ptr;
+    cmsToneCurve** NewCurves;
+
+    NewCurves = ( cmsToneCurve**) _cmsCalloc(self ->ContextID, 3, sizeof(cmsToneCurve*));
+    if (NewCurves == NULL) return NULL;
+
+    NewCurves[0] = cmsDupToneCurve(OldCurves[0]);
+    NewCurves[1] = cmsDupToneCurve(OldCurves[1]);
+    NewCurves[2] = cmsDupToneCurve(OldCurves[2]);
+
+    return (void*) NewCurves;
+
+    cmsUNUSED_PARAMETER(n);
+}
+
+
+static
+void Type_vcgt_Free(struct _cms_typehandler_struct* self, void* Ptr)
+{
+    cmsFreeToneCurveTriple((cmsToneCurve**) Ptr);
+    _cmsFree(self ->ContextID, Ptr);
+}
+
+// ********************************************************************************
+// Type support main routines
+// ********************************************************************************
+
+
+// This is the list of built-in types
+static _cmsTagTypeLinkedList SupportedTagTypes[] = {
+
+{TYPE_HANDLER(cmsSigChromaticityType,          Chromaticity),        &SupportedTagTypes[1] },
+{TYPE_HANDLER(cmsSigColorantOrderType,         ColorantOrderType),   &SupportedTagTypes[2] },
+{TYPE_HANDLER(cmsSigS15Fixed16ArrayType,       S15Fixed16),          &SupportedTagTypes[3] },
+{TYPE_HANDLER(cmsSigU16Fixed16ArrayType,       U16Fixed16),          &SupportedTagTypes[4] },
+{TYPE_HANDLER(cmsSigTextType,                  Text),                &SupportedTagTypes[5] },
+{TYPE_HANDLER(cmsSigTextDescriptionType,       Text_Description),    &SupportedTagTypes[6] },
+{TYPE_HANDLER(cmsSigCurveType,                 Curve),               &SupportedTagTypes[7] },
+{TYPE_HANDLER(cmsSigParametricCurveType,       ParametricCurve),     &SupportedTagTypes[8] },
+{TYPE_HANDLER(cmsSigDateTimeType,              DateTime),            &SupportedTagTypes[9] },
+{TYPE_HANDLER(cmsSigLut8Type,                  LUT8),                &SupportedTagTypes[10] },
+{TYPE_HANDLER(cmsSigLut16Type,                 LUT16),               &SupportedTagTypes[11] },
+{TYPE_HANDLER(cmsSigColorantTableType,         ColorantTable),       &SupportedTagTypes[12] },
+{TYPE_HANDLER(cmsSigNamedColor2Type,           NamedColor),          &SupportedTagTypes[13] },
+{TYPE_HANDLER(cmsSigMultiLocalizedUnicodeType, MLU),                 &SupportedTagTypes[14] },
+{TYPE_HANDLER(cmsSigProfileSequenceDescType,   ProfileSequenceDesc), &SupportedTagTypes[15] },
+{TYPE_HANDLER(cmsSigSignatureType,             Signature),           &SupportedTagTypes[16] },
+{TYPE_HANDLER(cmsSigMeasurementType,           Measurement),         &SupportedTagTypes[17] },
+{TYPE_HANDLER(cmsSigDataType,                  Data),                &SupportedTagTypes[18] },
+{TYPE_HANDLER(cmsSigLutAtoBType,               LUTA2B),              &SupportedTagTypes[19] },
+{TYPE_HANDLER(cmsSigLutBtoAType,               LUTB2A),              &SupportedTagTypes[20] },
+{TYPE_HANDLER(cmsSigUcrBgType,                 UcrBg),               &SupportedTagTypes[21] },
+{TYPE_HANDLER(cmsSigCrdInfoType,               CrdInfo),             &SupportedTagTypes[22] },
+{TYPE_HANDLER(cmsSigMultiProcessElementType,   MPE),                 &SupportedTagTypes[23] },
+{TYPE_HANDLER(cmsSigScreeningType,             Screening),           &SupportedTagTypes[24] },
+{TYPE_HANDLER(cmsSigViewingConditionsType,     ViewingConditions),   &SupportedTagTypes[25] },
+{TYPE_HANDLER(cmsSigXYZType,                   XYZ),                 &SupportedTagTypes[26] },
+{TYPE_HANDLER(cmsCorbisBrokenXYZtype,          XYZ),                 &SupportedTagTypes[27] },
+{TYPE_HANDLER(cmsMonacoBrokenCurveType,        Curve),               &SupportedTagTypes[28] },
+{TYPE_HANDLER(cmsSigProfileSequenceIdType,     ProfileSequenceId),   &SupportedTagTypes[29] },
+{TYPE_HANDLER(cmsSigVcgtType,                  vcgt),                NULL }
+};
+
+#define DEFAULT_TAG_TYPE_COUNT  (sizeof(SupportedTagTypes) / sizeof(_cmsTagTypeLinkedList))
+
+// Both kind of plug-ins share same structure
+cmsBool  _cmsRegisterTagTypePlugin(cmsPluginBase* Data)
+{
+    return RegisterTypesPlugin(Data, SupportedTagTypes, DEFAULT_TAG_TYPE_COUNT);
+}
+
+cmsBool  _cmsRegisterMultiProcessElementPlugin(cmsPluginBase* Data)
+{
+    return RegisterTypesPlugin(Data, SupportedMPEtypes, DEFAULT_MPE_TYPE_COUNT);
+}
+
+
+// Wrapper for tag types
+cmsTagTypeHandler* _cmsGetTagTypeHandler(cmsTagTypeSignature sig)
+{
+    return GetHandler(sig, SupportedTagTypes);
+}
+
+// ********************************************************************************
+// Tag support main routines
+// ********************************************************************************
+
+typedef struct _cmsTagLinkedList_st {
+
+            cmsTagSignature Signature;
+            cmsTagDescriptor Descriptor;
+            struct _cmsTagLinkedList_st* Next;
+
+} _cmsTagLinkedList;
+
+// This is the list of built-in tags
+static _cmsTagLinkedList SupportedTags[] = {
+
+    { cmsSigAToB0Tag,               { 1, 3,  { cmsSigLut16Type,  cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[1]},
+    { cmsSigAToB1Tag,               { 1, 3,  { cmsSigLut16Type,  cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[2]},
+    { cmsSigAToB2Tag,               { 1, 3,  { cmsSigLut16Type,  cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[3]},
+    { cmsSigBToA0Tag,               { 1, 3,  { cmsSigLut16Type,  cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[4]},
+    { cmsSigBToA1Tag,               { 1, 3,  { cmsSigLut16Type,  cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[5]},
+    { cmsSigBToA2Tag,               { 1, 3,  { cmsSigLut16Type,  cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[6]},
+
+    // Allow corbis  and its broken XYZ type
+    { cmsSigRedColorantTag,         { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[7]},
+    { cmsSigGreenColorantTag,       { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[8]},
+    { cmsSigBlueColorantTag,        { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[9]},
+
+    { cmsSigRedTRCTag,              { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[10]},
+    { cmsSigGreenTRCTag,            { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[11]},
+    { cmsSigBlueTRCTag,             { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[12]},
+
+    { cmsSigCalibrationDateTimeTag, { 1, 1, { cmsSigDateTimeType }, NULL}, &SupportedTags[13]},
+    { cmsSigCharTargetTag,          { 1, 1, { cmsSigTextType },     NULL}, &SupportedTags[14]},
+
+    { cmsSigChromaticAdaptationTag, { 9, 1, { cmsSigS15Fixed16ArrayType }, NULL}, &SupportedTags[15]},
+    { cmsSigChromaticityTag,        { 1, 1, { cmsSigChromaticityType    }, NULL}, &SupportedTags[16]},
+    { cmsSigColorantOrderTag,       { 1, 1, { cmsSigColorantOrderType   }, NULL}, &SupportedTags[17]},
+    { cmsSigColorantTableTag,       { 1, 1, { cmsSigColorantTableType   }, NULL}, &SupportedTags[18]},
+    { cmsSigColorantTableOutTag,    { 1, 1, { cmsSigColorantTableType   }, NULL}, &SupportedTags[19]},
+
+    { cmsSigCopyrightTag,           { 1, 3, { cmsSigTextType,  cmsSigMultiLocalizedUnicodeType, cmsSigTextDescriptionType}, DecideTextType}, &SupportedTags[20]},
+    { cmsSigDateTimeTag,            { 1, 1, { cmsSigDateTimeType }, NULL}, &SupportedTags[21]},
+
+    { cmsSigDeviceMfgDescTag,       { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[22]},
+    { cmsSigDeviceModelDescTag,     { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[23]},
+
+    { cmsSigGamutTag,               { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[24]},
+
+    { cmsSigGrayTRCTag,             { 1, 2, { cmsSigCurveType, cmsSigParametricCurveType }, DecideCurveType}, &SupportedTags[25]},
+    { cmsSigLuminanceTag,           { 1, 1, { cmsSigXYZType }, NULL}, &SupportedTags[26]},
+
+    { cmsSigMediaBlackPointTag,     { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, NULL}, &SupportedTags[27]},
+    { cmsSigMediaWhitePointTag,     { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, NULL}, &SupportedTags[28]},
+
+    { cmsSigNamedColor2Tag,         { 1, 1, { cmsSigNamedColor2Type }, NULL}, &SupportedTags[29]},
+
+    { cmsSigPreview0Tag,            { 1, 3,  { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[30]},
+    { cmsSigPreview1Tag,            { 1, 3,  { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[31]},
+    { cmsSigPreview2Tag,            { 1, 3,  { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[32]},
+
+    { cmsSigProfileDescriptionTag,  { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[33]},
+    { cmsSigProfileSequenceDescTag, { 1, 1, { cmsSigProfileSequenceDescType }, NULL}, &SupportedTags[34]},
+    { cmsSigTechnologyTag,          { 1, 1, { cmsSigSignatureType }, NULL},  &SupportedTags[35]},
+
+    { cmsSigColorimetricIntentImageStateTag,   { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[36]},
+    { cmsSigPerceptualRenderingIntentGamutTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[37]},
+    { cmsSigSaturationRenderingIntentGamutTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[38]},
+
+    { cmsSigMeasurementTag,         { 1, 1, { cmsSigMeasurementType }, NULL}, &SupportedTags[39]},
+
+    { cmsSigPs2CRD0Tag,             { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[40]},
+    { cmsSigPs2CRD1Tag,             { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[41]},
+    { cmsSigPs2CRD2Tag,             { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[42]},
+    { cmsSigPs2CRD3Tag,             { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[43]},
+    { cmsSigPs2CSATag,              { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[44]},
+    { cmsSigPs2RenderingIntentTag,  { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[45]},
+
+    { cmsSigViewingCondDescTag,     { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[46]},
+
+    { cmsSigUcrBgTag,               { 1, 1, { cmsSigUcrBgType}, NULL},    &SupportedTags[47]},
+    { cmsSigCrdInfoTag,             { 1, 1, { cmsSigCrdInfoType}, NULL},  &SupportedTags[48]},
+
+    { cmsSigDToB0Tag,               { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[49]},
+    { cmsSigDToB1Tag,               { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[50]},
+    { cmsSigDToB2Tag,               { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[51]},
+    { cmsSigDToB3Tag,               { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[52]},
+    { cmsSigBToD0Tag,               { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[53]},
+    { cmsSigBToD1Tag,               { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[54]},
+    { cmsSigBToD2Tag,               { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[55]},
+    { cmsSigBToD3Tag,               { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[56]},
+
+    { cmsSigScreeningDescTag,       { 1, 1, { cmsSigTextDescriptionType },    NULL}, &SupportedTags[57]},
+    { cmsSigViewingConditionsTag,   { 1, 1, { cmsSigViewingConditionsType },  NULL}, &SupportedTags[58]},
+
+    { cmsSigScreeningTag,           { 1, 1, { cmsSigScreeningType},          NULL }, &SupportedTags[59]},
+    { cmsSigVcgtTag,                { 1, 1, { cmsSigVcgtType},               NULL }, &SupportedTags[60]},
+    { cmsSigProfileSequenceIdTag,   { 1, 1, { cmsSigProfileSequenceIdType},  NULL},  NULL}
+
+};
+
+/*
+    Not supported                 Why
+    =======================       =========================================
+    cmsSigOutputResponseTag   ==> WARNING, POSSIBLE PATENT ON THIS SUBJECT!
+    cmsSigNamedColorTag       ==> Deprecated
+    cmsSigDataTag             ==> Ancient, unused
+    cmsSigDeviceSettingsTag   ==> Deprecated, useless
+*/
+
+#define DEFAULT_TAG_COUNT  (sizeof(SupportedTags) / sizeof(_cmsTagLinkedList))
+
+cmsBool  _cmsRegisterTagPlugin(cmsPluginBase* Data)
+{
+    cmsPluginTag* Plugin = (cmsPluginTag*) Data;
+    _cmsTagLinkedList *pt, *Anterior;
+
+
+    if (Data == NULL) {
+
+        SupportedTags[DEFAULT_TAG_COUNT-1].Next = NULL;
+        return TRUE;
+    }
+
+    pt = Anterior = SupportedTags;
+    while (pt != NULL) {
+
+        if (Plugin->Signature == pt -> Signature) {
+            pt ->Descriptor = Plugin ->Descriptor;  // Replace old behaviour
+            return TRUE;
+        }
+
+        Anterior = pt;
+        pt = pt ->Next;
+    }
+
+    pt = (_cmsTagLinkedList*) _cmsPluginMalloc(sizeof(_cmsTagLinkedList));
+    if (pt == NULL) return FALSE;
+
+    pt ->Signature  = Plugin ->Signature;
+    pt ->Descriptor = Plugin ->Descriptor;
+    pt ->Next       = NULL;
+
+    if (Anterior != NULL) Anterior -> Next = pt;
+
+    return TRUE;
+}
+
+// Return a descriptor for a given tag or NULL
+cmsTagDescriptor* _cmsGetTagDescriptor(cmsTagSignature sig)
+{
+    _cmsTagLinkedList* pt;
+
+    for (pt = SupportedTags;
+            pt != NULL;
+            pt = pt ->Next) {
+
+                if (sig == pt -> Signature) return &pt ->Descriptor;
+    }
+
+    return NULL;
+}
+
--- a/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,425 +49,313 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
+//
+//---------------------------------------------------------------------------------
+//
 
-#include "lcms.h"
-
+#include "lcms2_internal.h"
 
 // Virtual (built-in) profiles
 // -----------------------------------------------------------------------------------
 
+static
+cmsBool SetTextTags(cmsHPROFILE hProfile, const wchar_t* Description)
+{
+    cmsMLU *DescriptionMLU, *CopyrightMLU;
+    cmsBool  rc = FALSE;
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+
+    DescriptionMLU  = cmsMLUalloc(ContextID, 1);
+    CopyrightMLU    = cmsMLUalloc(ContextID, 1);
+
+    if (DescriptionMLU == NULL || CopyrightMLU == NULL) goto Error;
+
+    if (!cmsMLUsetWide(DescriptionMLU,  "en", "US", Description)) goto Error;
+    if (!cmsMLUsetWide(CopyrightMLU,    "en", "US", L"No copyright, use freely")) goto Error;
+
+    if (!cmsWriteTag(hProfile, cmsSigProfileDescriptionTag,  DescriptionMLU)) goto Error;
+    if (!cmsWriteTag(hProfile, cmsSigCopyrightTag,           CopyrightMLU)) goto Error;
+
+    rc = TRUE;
+
+Error:
+
+    if (DescriptionMLU)
+        cmsMLUfree(DescriptionMLU);
+    if (CopyrightMLU)
+        cmsMLUfree(CopyrightMLU);
+    return rc;
+}
+
+
+static
+cmsBool  SetSeqDescTag(cmsHPROFILE hProfile, const char* Model)
+{
+    cmsBool  rc = FALSE;
+    cmsContext ContextID = cmsGetProfileContextID(hProfile);
+    cmsSEQ* Seq = cmsAllocProfileSequenceDescription(ContextID, 1);
+
+    if (Seq == NULL) return FALSE;
+
+    Seq->seq[0].deviceMfg = (cmsSignature) 0;
+    Seq->seq[0].deviceModel = (cmsSignature) 0;
+
+#ifdef CMS_DONT_USE_INT64
+    Seq->seq[0].attributes[0] = 0;
+    Seq->seq[0].attributes[1] = 0;
+#else
+    Seq->seq[0].attributes = 0;
+#endif
+
+    Seq->seq[0].technology = (cmsTechnologySignature) 0;
+
+    cmsMLUsetASCII( Seq->seq[0].Manufacturer, cmsNoLanguage, cmsNoCountry, "Little CMS");
+    cmsMLUsetASCII( Seq->seq[0].Model,        cmsNoLanguage, cmsNoCountry, Model);
+
+    if (!_cmsWriteProfileSequence(hProfile, Seq)) goto Error;
+
+    rc = TRUE;
+
+Error:
+    if (Seq)
+        cmsFreeProfileSequenceDescription(Seq);
+
+    return rc;
+}
+
+
 
 // This function creates a profile based on White point, primaries and
 // transfer functions.
-
-
-cmsHPROFILE LCMSEXPORT cmsCreateRGBProfile(LPcmsCIExyY WhitePoint,
-                                LPcmsCIExyYTRIPLE Primaries,
-                                LPGAMMATABLE TransferFunction[3])
+cmsHPROFILE CMSEXPORT cmsCreateRGBProfileTHR(cmsContext ContextID,
+                                          const cmsCIExyY* WhitePoint,
+                                          const cmsCIExyYTRIPLE* Primaries,
+                                          cmsToneCurve* const TransferFunction[3])
 {
-       cmsHPROFILE hICC;
-       cmsCIEXYZ tmp;
-       MAT3 MColorants;
-       cmsCIEXYZTRIPLE Colorants;
-       cmsCIExyY MaxWhite;
-
+    cmsHPROFILE hICC;
+    cmsMAT3 MColorants;
+    cmsCIEXYZTRIPLE Colorants;
+    cmsCIExyY MaxWhite;
+    cmsMAT3 CHAD;
+    cmsCIEXYZ WhitePointXYZ;
 
-       hICC = _cmsCreateProfilePlaceholder();
-       if (!hICC)                          // can't allocate
-            return NULL;
+    hICC = cmsCreateProfilePlaceholder(ContextID);
+    if (!hICC)                          // can't allocate
+        return NULL;
 
+    cmsSetProfileVersion(hICC, 4.2);
 
-       cmsSetDeviceClass(hICC,      icSigDisplayClass);
-       cmsSetColorSpace(hICC,       icSigRgbData);
-       cmsSetPCS(hICC,              icSigXYZData);
-       cmsSetRenderingIntent(hICC,  INTENT_PERCEPTUAL);
+    cmsSetDeviceClass(hICC,      cmsSigDisplayClass);
+    cmsSetColorSpace(hICC,       cmsSigRgbData);
+    cmsSetPCS(hICC,              cmsSigXYZData);
+
+    cmsSetHeaderRenderingIntent(hICC,  INTENT_PERCEPTUAL);
 
 
-       // Implement profile using following tags:
-       //
-       //  1 icSigProfileDescriptionTag
-       //  2 icSigMediaWhitePointTag
-       //  3 icSigRedColorantTag
-       //  4 icSigGreenColorantTag
-       //  5 icSigBlueColorantTag
-       //  6 icSigRedTRCTag
-       //  7 icSigGreenTRCTag
-       //  8 icSigBlueTRCTag
-
-       // This conforms a standard RGB DisplayProfile as says ICC, and then I add
-
-       // 9 icSigChromaticityTag
-
-       // As addendum II
+    // Implement profile using following tags:
+    //
+    //  1 cmsSigProfileDescriptionTag
+    //  2 cmsSigMediaWhitePointTag
+    //  3 cmsSigRedColorantTag
+    //  4 cmsSigGreenColorantTag
+    //  5 cmsSigBlueColorantTag
+    //  6 cmsSigRedTRCTag
+    //  7 cmsSigGreenTRCTag
+    //  8 cmsSigBlueTRCTag
+    //  9 Chromatic adaptation Tag
+    // This conforms a standard RGB DisplayProfile as says ICC, and then I add (As per addendum II)
+    // 10 cmsSigChromaticityTag
 
 
-       // Fill-in the tags
+    if (!SetTextTags(hICC, L"RGB built-in")) goto Error;
 
-       cmsAddTag(hICC, icSigDeviceMfgDescTag,       (LPVOID) "(lcms internal)");
-       cmsAddTag(hICC, icSigProfileDescriptionTag,  (LPVOID) "lcms RGB virtual profile");
-       cmsAddTag(hICC, icSigDeviceModelDescTag,     (LPVOID) "rgb built-in");
+    if (WhitePoint) {
 
+        if (!cmsWriteTag(hICC, cmsSigMediaWhitePointTag, cmsD50_XYZ())) goto Error;
 
-       if (WhitePoint) {
+        cmsxyY2XYZ(&WhitePointXYZ, WhitePoint);
+        _cmsAdaptationMatrix(&CHAD, NULL, &WhitePointXYZ, cmsD50_XYZ());
 
-       cmsxyY2XYZ(&tmp, WhitePoint);
-       cmsAddTag(hICC, icSigMediaWhitePointTag, (LPVOID) &tmp);
-       }
+        // This is a V4 tag, but many CMM does read and understand it no matter which version
+        if (!cmsWriteTag(hICC, cmsSigChromaticAdaptationTag, (void*) &CHAD)) goto Error;
+    }
 
-       if (WhitePoint && Primaries) {
+    if (WhitePoint && Primaries) {
 
         MaxWhite.x =  WhitePoint -> x;
         MaxWhite.y =  WhitePoint -> y;
         MaxWhite.Y =  1.0;
 
-       if (!cmsBuildRGB2XYZtransferMatrix(&MColorants, &MaxWhite, Primaries))
-       {
-              cmsCloseProfile(hICC);
-              return NULL;
-       }
+        if (!_cmsBuildRGB2XYZtransferMatrix(&MColorants, &MaxWhite, Primaries)) goto Error;
 
-       cmsAdaptMatrixToD50(&MColorants, &MaxWhite);
-
-       Colorants.Red.X = MColorants.v[0].n[0];
-       Colorants.Red.Y = MColorants.v[1].n[0];
-       Colorants.Red.Z = MColorants.v[2].n[0];
+        Colorants.Red.X   = MColorants.v[0].n[0];
+        Colorants.Red.Y   = MColorants.v[1].n[0];
+        Colorants.Red.Z   = MColorants.v[2].n[0];
 
-       Colorants.Green.X = MColorants.v[0].n[1];
-       Colorants.Green.Y = MColorants.v[1].n[1];
-       Colorants.Green.Z = MColorants.v[2].n[1];
+        Colorants.Green.X = MColorants.v[0].n[1];
+        Colorants.Green.Y = MColorants.v[1].n[1];
+        Colorants.Green.Z = MColorants.v[2].n[1];
 
-       Colorants.Blue.X = MColorants.v[0].n[2];
-       Colorants.Blue.Y = MColorants.v[1].n[2];
-       Colorants.Blue.Z = MColorants.v[2].n[2];
+        Colorants.Blue.X  = MColorants.v[0].n[2];
+        Colorants.Blue.Y  = MColorants.v[1].n[2];
+        Colorants.Blue.Z  = MColorants.v[2].n[2];
 
-       cmsAddTag(hICC, icSigRedColorantTag,   (LPVOID) &Colorants.Red);
-       cmsAddTag(hICC, icSigBlueColorantTag,  (LPVOID) &Colorants.Blue);
-       cmsAddTag(hICC, icSigGreenColorantTag, (LPVOID) &Colorants.Green);
-       }
+        if (!cmsWriteTag(hICC, cmsSigRedColorantTag,   (void*) &Colorants.Red)) goto Error;
+        if (!cmsWriteTag(hICC, cmsSigBlueColorantTag,  (void*) &Colorants.Blue)) goto Error;
+        if (!cmsWriteTag(hICC, cmsSigGreenColorantTag, (void*) &Colorants.Green)) goto Error;
+    }
 
 
-       if (TransferFunction) {
+    if (TransferFunction) {
 
-       // In case of gamma, we must dup' the table pointer
+        if (!cmsWriteTag(hICC, cmsSigRedTRCTag,   (void*) TransferFunction[0])) goto Error;
+        if (!cmsWriteTag(hICC, cmsSigGreenTRCTag, (void*) TransferFunction[1])) goto Error;
+        if (!cmsWriteTag(hICC, cmsSigBlueTRCTag,  (void*) TransferFunction[2])) goto Error;
+    }
+
+    if (Primaries) {
+        if (!cmsWriteTag(hICC, cmsSigChromaticityTag, (void*) Primaries)) goto Error;
+    }
+
 
-        cmsAddTag(hICC, icSigRedTRCTag,   (LPVOID) TransferFunction[0]);
-        cmsAddTag(hICC, icSigGreenTRCTag, (LPVOID) TransferFunction[1]);
-        cmsAddTag(hICC, icSigBlueTRCTag,  (LPVOID) TransferFunction[2]);
-       }
+    return hICC;
 
-       if (Primaries) {
-            cmsAddTag(hICC, icSigChromaticityTag, (LPVOID) Primaries);
-       }
+Error:
+    if (hICC)
+        cmsCloseProfile(hICC);
+    return NULL;
+}
 
-       return hICC;
+cmsHPROFILE CMSEXPORT cmsCreateRGBProfile(const cmsCIExyY* WhitePoint,
+                                          const cmsCIExyYTRIPLE* Primaries,
+                                          cmsToneCurve* const TransferFunction[3])
+{
+    return cmsCreateRGBProfileTHR(NULL, WhitePoint, Primaries, TransferFunction);
 }
 
 
 
 // This function creates a profile based on White point and transfer function.
-
-cmsHPROFILE   LCMSEXPORT cmsCreateGrayProfile(LPcmsCIExyY WhitePoint,
-                                              LPGAMMATABLE TransferFunction)
+cmsHPROFILE CMSEXPORT cmsCreateGrayProfileTHR(cmsContext ContextID,
+                                           const cmsCIExyY* WhitePoint,
+                                           const cmsToneCurve* TransferFunction)
 {
-       cmsHPROFILE hICC;
-       cmsCIEXYZ tmp;
-
-
-       hICC = _cmsCreateProfilePlaceholder();
-       if (!hICC)                          // can't allocate
-            return NULL;
-
-
-       cmsSetDeviceClass(hICC,      icSigDisplayClass);
-       cmsSetColorSpace(hICC,       icSigGrayData);
-       cmsSetPCS(hICC,              icSigXYZData);
-       cmsSetRenderingIntent(hICC,  INTENT_PERCEPTUAL);
-
-
-
-       // Implement profile using following tags:
-       //
-       //  1 icSigProfileDescriptionTag
-       //  2 icSigMediaWhitePointTag
-       //  6 icSigGrayTRCTag
+    cmsHPROFILE hICC;
+    cmsCIEXYZ tmp;
 
-       // This conforms a standard Gray DisplayProfile
-
-       // Fill-in the tags
-
-
-       cmsAddTag(hICC, icSigDeviceMfgDescTag,       (LPVOID) "(lcms internal)");
-       cmsAddTag(hICC, icSigProfileDescriptionTag,  (LPVOID) "lcms gray virtual profile");
-       cmsAddTag(hICC, icSigDeviceModelDescTag,     (LPVOID) "gray built-in");
-
-
-       if (WhitePoint) {
+    hICC = cmsCreateProfilePlaceholder(ContextID);
+    if (!hICC)                          // can't allocate
+        return NULL;
 
-       cmsxyY2XYZ(&tmp, WhitePoint);
-       cmsAddTag(hICC, icSigMediaWhitePointTag, (LPVOID) &tmp);
-       }
-
-
-       if (TransferFunction) {
+    cmsSetProfileVersion(hICC, 4.2);
 
-       // In case of gamma, we must dup' the table pointer
-
-       cmsAddTag(hICC, icSigGrayTRCTag, (LPVOID) TransferFunction);
-       }
-
-       return hICC;
-
-}
+    cmsSetDeviceClass(hICC,      cmsSigDisplayClass);
+    cmsSetColorSpace(hICC,       cmsSigGrayData);
+    cmsSetPCS(hICC,              cmsSigXYZData);
+    cmsSetHeaderRenderingIntent(hICC,  INTENT_PERCEPTUAL);
 
 
-static
-int IsPCS(icColorSpaceSignature ColorSpace)
-{
-    return (ColorSpace == icSigXYZData ||
-            ColorSpace == icSigLabData);
-}
+    // Implement profile using following tags:
+    //
+    //  1 cmsSigProfileDescriptionTag
+    //  2 cmsSigMediaWhitePointTag
+    //  3 cmsSigGrayTRCTag
 
-static
-void FixColorSpaces(cmsHPROFILE hProfile,
-                              icColorSpaceSignature ColorSpace,
-                              icColorSpaceSignature PCS,
-                              DWORD dwFlags)
-{
-
-    if (dwFlags & cmsFLAGS_GUESSDEVICECLASS) {
-
-            if (IsPCS(ColorSpace) && IsPCS(PCS)) {
+    // This conforms a standard Gray DisplayProfile
 
-                    cmsSetDeviceClass(hProfile,      icSigAbstractClass);
-                    cmsSetColorSpace(hProfile,       ColorSpace);
-                    cmsSetPCS(hProfile,              PCS);
-                    return;
-            }
+    // Fill-in the tags
 
-            if (IsPCS(ColorSpace) && !IsPCS(PCS)) {
+    if (!SetTextTags(hICC, L"gray built-in")) goto Error;
+
 
-                    cmsSetDeviceClass(hProfile, icSigOutputClass);
-                    cmsSetPCS(hProfile,         ColorSpace);
-                    cmsSetColorSpace(hProfile,  PCS);
-                    return;
-            }
+    if (WhitePoint) {
 
-            if (IsPCS(PCS) && !IsPCS(ColorSpace)) {
-
-                   cmsSetDeviceClass(hProfile,  icSigInputClass);
-                   cmsSetColorSpace(hProfile,   ColorSpace);
-                   cmsSetPCS(hProfile,          PCS);
-                   return;
-            }
+        cmsxyY2XYZ(&tmp, WhitePoint);
+        if (!cmsWriteTag(hICC, cmsSigMediaWhitePointTag, (void*) &tmp)) goto Error;
     }
 
-    cmsSetDeviceClass(hProfile,      icSigLinkClass);
-    cmsSetColorSpace(hProfile,       ColorSpace);
-    cmsSetPCS(hProfile,              PCS);
-
-}
-
-
-static
-cmsHPROFILE CreateNamedColorDevicelink(cmsHTRANSFORM xform)
-{
-    _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
-    cmsHPROFILE hICC;
-    cmsCIEXYZ WhitePoint;
-    int i, nColors;
-    size_t Size;
-    LPcmsNAMEDCOLORLIST nc2;
-
-
-    hICC = _cmsCreateProfilePlaceholder();
-    if (hICC == NULL) return NULL;
+    if (TransferFunction) {
 
-    cmsSetRenderingIntent(hICC, v -> Intent);
-    cmsSetDeviceClass(hICC, icSigNamedColorClass);
-    cmsSetColorSpace(hICC, v ->ExitColorSpace);
-    cmsSetPCS(hICC, cmsGetPCS(v ->InputProfile));
-    cmsTakeMediaWhitePoint(&WhitePoint, v ->InputProfile);
-
-    cmsAddTag(hICC, icSigMediaWhitePointTag,  &WhitePoint);
-    cmsAddTag(hICC, icSigDeviceMfgDescTag,       (LPVOID) "LittleCMS");
-    cmsAddTag(hICC, icSigProfileDescriptionTag,  (LPVOID) "Named color Device link");
-    cmsAddTag(hICC, icSigDeviceModelDescTag,     (LPVOID) "Named color Device link");
-
-
-    nColors = cmsNamedColorCount(xform);
-    nc2     = cmsAllocNamedColorList(nColors);
-
-    Size = sizeof(cmsNAMEDCOLORLIST) + (sizeof(cmsNAMEDCOLOR) * (nColors-1));
-
-    CopyMemory(nc2, v->NamedColorList, Size);
-    nc2 ->ColorantCount = _cmsChannelsOf(v ->ExitColorSpace);
-
-    for (i=0; i < nColors; i++) {
-        cmsDoTransform(xform, &i, nc2 ->List[i].DeviceColorant, 1);
+        if (!cmsWriteTag(hICC, cmsSigGrayTRCTag, (void*) TransferFunction)) goto Error;
     }
 
-    cmsAddTag(hICC, icSigNamedColor2Tag, (void*) nc2);
-    cmsFreeNamedColorList(nc2);
+    return hICC;
 
-    return hICC;
+Error:
+    if (hICC)
+        cmsCloseProfile(hICC);
+    return NULL;
 }
 
 
-// Does convert a transform into a device link profile
 
-cmsHPROFILE LCMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, DWORD dwFlags)
+cmsHPROFILE CMSEXPORT cmsCreateGrayProfile(const cmsCIExyY* WhitePoint,
+                                                    const cmsToneCurve* TransferFunction)
+{
+    return cmsCreateGrayProfileTHR(NULL, WhitePoint, TransferFunction);
+}
+
+// This is a devicelink operating in the target colorspace with as many transfer functions as components
+
+cmsHPROFILE CMSEXPORT cmsCreateLinearizationDeviceLinkTHR(cmsContext ContextID,
+                                                          cmsColorSpaceSignature ColorSpace,
+                                                          cmsToneCurve* const TransferFunctions[])
 {
     cmsHPROFILE hICC;
-    _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) hTransform;
-    LPLUT Lut;
-    LCMSBOOL MustFreeLUT;
-    LPcmsNAMEDCOLORLIST InputColorant = NULL;
-    LPcmsNAMEDCOLORLIST OutputColorant = NULL;
-
-
-    // Check if is a named color transform
-
-    if (cmsGetDeviceClass(v ->InputProfile) == icSigNamedColorClass) {
-
-        return CreateNamedColorDevicelink(hTransform);
-
-    }
+    cmsPipeline* Pipeline;
+    cmsStage* Lin;
+    int nChannels;
 
-    if (v ->DeviceLink) {
-
-        Lut = v -> DeviceLink;
-        MustFreeLUT = FALSE;
-    }
-    else {
+    hICC = cmsCreateProfilePlaceholder(ContextID);
+    if (!hICC)
+        return NULL;
 
-        Lut = _cmsPrecalculateDeviceLink(hTransform, dwFlags);
-        if (!Lut) return NULL;
-        MustFreeLUT = TRUE;
-    }
-
-    hICC = _cmsCreateProfilePlaceholder();
-    if (!hICC) {                          // can't allocate
+    cmsSetProfileVersion(hICC, 4.2);
 
-        if (MustFreeLUT) cmsFreeLUT(Lut);
-        return NULL;
-    }
-
-
-    FixColorSpaces(hICC, v -> EntryColorSpace, v -> ExitColorSpace, dwFlags);
+    cmsSetDeviceClass(hICC,      cmsSigLinkClass);
+    cmsSetColorSpace(hICC,       ColorSpace);
+    cmsSetPCS(hICC,              ColorSpace);
 
-    cmsSetRenderingIntent(hICC,  v -> Intent);
-
-    // Implement devicelink profile using following tags:
-    //
-    //  1 icSigProfileDescriptionTag
-    //  2 icSigMediaWhitePointTag
-    //  3 icSigAToB0Tag
+    cmsSetHeaderRenderingIntent(hICC,  INTENT_PERCEPTUAL);
 
-
-    cmsAddTag(hICC, icSigDeviceMfgDescTag,       (LPVOID) "LittleCMS");
-    cmsAddTag(hICC, icSigProfileDescriptionTag,  (LPVOID) "Device link");
-    cmsAddTag(hICC, icSigDeviceModelDescTag,     (LPVOID) "Device link");
-
-
-    cmsAddTag(hICC, icSigMediaWhitePointTag,  (LPVOID) cmsD50_XYZ());
+    // Set up channels
+    nChannels = cmsChannelsOf(ColorSpace);
 
-    if (cmsGetDeviceClass(hICC) == icSigOutputClass) {
-
-        cmsAddTag(hICC, icSigBToA0Tag, (LPVOID) Lut);
-    }
-    else
-        cmsAddTag(hICC, icSigAToB0Tag, (LPVOID) Lut);
-
+    // Creates a Pipeline with prelinearization step only
+    Pipeline = cmsPipelineAlloc(ContextID, nChannels, nChannels);
+    if (Pipeline == NULL) goto Error;
 
 
-    // Try to read input and output colorant table
-    if (cmsIsTag(v ->InputProfile, icSigColorantTableTag)) {
-
-        // Input table can only come in this way.
-        InputColorant = cmsReadColorantTable(v ->InputProfile, icSigColorantTableTag);
-    }
+    // Copy tables to Pipeline
+    Lin = cmsStageAllocToneCurves(ContextID, nChannels, TransferFunctions);
+    if (Lin == NULL) goto Error;
 
-    // Output is a little bit more complex.
-    if (cmsGetDeviceClass(v ->OutputProfile) == icSigLinkClass) {
-
-        // This tag may exist only on devicelink profiles.
-        if (cmsIsTag(v ->OutputProfile, icSigColorantTableOutTag)) {
-
-            OutputColorant = cmsReadColorantTable(v ->OutputProfile, icSigColorantTableOutTag);
-        }
-
-    } else {
+    cmsPipelineInsertStage(Pipeline, cmsAT_BEGIN, Lin);
 
-        if (cmsIsTag(v ->OutputProfile, icSigColorantTableTag)) {
-
-            OutputColorant = cmsReadColorantTable(v ->OutputProfile, icSigColorantTableTag);
-        }
-    }
-
-    if (InputColorant)
-           cmsAddTag(hICC, icSigColorantTableTag, InputColorant);
+    // Create tags
+    if (!SetTextTags(hICC, L"Linearization built-in")) goto Error;
+    if (!cmsWriteTag(hICC, cmsSigAToB0Tag, (void*) Pipeline)) goto Error;
+    if (!SetSeqDescTag(hICC, "Linearization built-in")) goto Error;
 
-    if (OutputColorant)
-           cmsAddTag(hICC, icSigColorantTableOutTag, OutputColorant);
-
-
+    // Pipeline is already on virtual profile
+    cmsPipelineFree(Pipeline);
 
-    if (MustFreeLUT) cmsFreeLUT(Lut);
-    if (InputColorant) cmsFreeNamedColorList(InputColorant);
-    if (OutputColorant) cmsFreeNamedColorList(OutputColorant);
-
+    // Ok, done
     return hICC;
 
-}
+Error:
+    if (hICC)
+        cmsCloseProfile(hICC);
 
 
-// This is a devicelink operating in the target colorspace with as many transfer
-// functions as components
-
-cmsHPROFILE LCMSEXPORT cmsCreateLinearizationDeviceLink(icColorSpaceSignature ColorSpace,
-                                                        LPGAMMATABLE TransferFunctions[])
-{
-       cmsHPROFILE hICC;
-       LPLUT Lut;
-
-
-       hICC = _cmsCreateProfilePlaceholder();
-       if (!hICC)                          // can't allocate
-            return NULL;
-
-
-       cmsSetDeviceClass(hICC,      icSigLinkClass);
-       cmsSetColorSpace(hICC,       ColorSpace);
-       cmsSetPCS(hICC,              ColorSpace);
-       cmsSetRenderingIntent(hICC,  INTENT_PERCEPTUAL);
-
-
-       // Creates a LUT with prelinearization step only
-       Lut = cmsAllocLUT();
-       if (Lut == NULL) return NULL;
-
-       // Set up channels
-       Lut ->InputChan = Lut ->OutputChan = _cmsChannelsOf(ColorSpace);
-
-       // Copy tables to LUT
-       cmsAllocLinearTable(Lut, TransferFunctions, 1);
-
-       // Create tags
-       cmsAddTag(hICC, icSigDeviceMfgDescTag,       (LPVOID) "(lcms internal)");
-       cmsAddTag(hICC, icSigProfileDescriptionTag,  (LPVOID) "lcms linearization device link");
-       cmsAddTag(hICC, icSigDeviceModelDescTag,     (LPVOID) "linearization built-in");
-
-       cmsAddTag(hICC, icSigMediaWhitePointTag, (LPVOID) cmsD50_XYZ());
-       cmsAddTag(hICC, icSigAToB0Tag, (LPVOID) Lut);
-
-       // LUT is already on virtual profile
-       cmsFreeLUT(Lut);
-
-       // Ok, done
-       return hICC;
+    return NULL;
 }
 
+cmsHPROFILE CMSEXPORT cmsCreateLinearizationDeviceLink(cmsColorSpaceSignature ColorSpace,
+                                                                 cmsToneCurve* const TransferFunctions[])
+{
+    return cmsCreateLinearizationDeviceLinkTHR(NULL, ColorSpace, TransferFunctions);
+}
 
 // Ink-limiting algorithm
 //
@@ -486,257 +375,282 @@
 //     K: Does not change
 
 static
-int InkLimitingSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
+int InkLimitingSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
 {
-        double InkLimit = *(double *) Cargo;
-        double SumCMY, SumCMYK, Ratio;
+    cmsFloat64Number InkLimit = *(cmsFloat64Number *) Cargo;
+    cmsFloat64Number SumCMY, SumCMYK, Ratio;
 
-        InkLimit = (InkLimit * 655.35);
+    InkLimit = (InkLimit * 655.35);
 
-        SumCMY   = In[0]  + In[1] + In[2];
-        SumCMYK  = SumCMY + In[3];
+    SumCMY   = In[0]  + In[1] + In[2];
+    SumCMYK  = SumCMY + In[3];
 
-        if (SumCMYK > InkLimit) {
+    if (SumCMYK > InkLimit) {
 
-                Ratio = 1 - ((SumCMYK - InkLimit) / SumCMY);
-                if (Ratio < 0)
-                        Ratio = 0;
-        }
-        else Ratio = 1;
+        Ratio = 1 - ((SumCMYK - InkLimit) / SumCMY);
+        if (Ratio < 0)
+            Ratio = 0;
+    }
+    else Ratio = 1;
 
-        Out[0] = (WORD) floor(In[0] * Ratio + 0.5);     // C
-        Out[1] = (WORD) floor(In[1] * Ratio + 0.5);     // M
-        Out[2] = (WORD) floor(In[2] * Ratio + 0.5);     // Y
+    Out[0] = _cmsQuickSaturateWord(In[0] * Ratio);     // C
+    Out[1] = _cmsQuickSaturateWord(In[1] * Ratio);     // M
+    Out[2] = _cmsQuickSaturateWord(In[2] * Ratio);     // Y
 
-        Out[3] = In[3];                                 // K (untouched)
+    Out[3] = In[3];                                 // K (untouched)
 
-        return TRUE;
+    return TRUE;
 }
 
 // This is a devicelink operating in CMYK for ink-limiting
 
-cmsHPROFILE LCMSEXPORT cmsCreateInkLimitingDeviceLink(icColorSpaceSignature ColorSpace,
-                                                        double Limit)
+cmsHPROFILE CMSEXPORT cmsCreateInkLimitingDeviceLinkTHR(cmsContext ContextID,
+                                                     cmsColorSpaceSignature ColorSpace,
+                                                     cmsFloat64Number Limit)
 {
-       cmsHPROFILE hICC;
-       LPLUT Lut;
+    cmsHPROFILE hICC;
+    cmsPipeline* LUT;
+    cmsStage* CLUT;
+    int nChannels;
 
-       if (ColorSpace != icSigCmykData) {
-            cmsSignalError(LCMS_ERRC_ABORTED, "InkLimiting: Only CMYK currently supported");
-            return NULL;
-       }
+    if (ColorSpace != cmsSigCmykData) {
+        cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "InkLimiting: Only CMYK currently supported");
+        return NULL;
+    }
 
-       if (Limit < 0.0 || Limit > 400) {
-
-           cmsSignalError(LCMS_ERRC_WARNING, "InkLimiting: Limit should be between 0..400");
-           if (Limit < 0) Limit = 0;
-           if (Limit > 400) Limit = 400;
+    if (Limit < 0.0 || Limit > 400) {
 
-       }
+        cmsSignalError(ContextID, cmsERROR_RANGE, "InkLimiting: Limit should be between 0..400");
+        if (Limit < 0) Limit = 0;
+        if (Limit > 400) Limit = 400;
 
-      hICC = _cmsCreateProfilePlaceholder();
-       if (!hICC)                          // can't allocate
-            return NULL;
-
+    }
 
-       cmsSetDeviceClass(hICC,      icSigLinkClass);
-       cmsSetColorSpace(hICC,       ColorSpace);
-       cmsSetPCS(hICC,              ColorSpace);
-       cmsSetRenderingIntent(hICC,  INTENT_PERCEPTUAL);
+    hICC = cmsCreateProfilePlaceholder(ContextID);
+    if (!hICC)                          // can't allocate
+        return NULL;
 
+    cmsSetProfileVersion(hICC, 4.2);
 
-       // Creates a LUT with 3D grid only
-       Lut = cmsAllocLUT();
-       if (Lut == NULL) {
-           cmsCloseProfile(hICC);
-           return NULL;
-           }
+    cmsSetDeviceClass(hICC,      cmsSigLinkClass);
+    cmsSetColorSpace(hICC,       ColorSpace);
+    cmsSetPCS(hICC,              ColorSpace);
+
+    cmsSetHeaderRenderingIntent(hICC,  INTENT_PERCEPTUAL);
 
 
-       cmsAlloc3DGrid(Lut, 17, _cmsChannelsOf(ColorSpace),
-                               _cmsChannelsOf(ColorSpace));
-
-       if (!cmsSample3DGrid(Lut, InkLimitingSampler, (LPVOID) &Limit, 0)) {
-
-                // Shouldn't reach here
-                cmsFreeLUT(Lut);
-                cmsCloseProfile(hICC);
-                return NULL;
-       }
-
-       // Create tags
-
-       cmsAddTag(hICC, icSigDeviceMfgDescTag,      (LPVOID) "(lcms internal)");
-       cmsAddTag(hICC, icSigProfileDescriptionTag, (LPVOID) "lcms ink limiting device link");
-       cmsAddTag(hICC, icSigDeviceModelDescTag,    (LPVOID) "ink limiting built-in");
-
-       cmsAddTag(hICC, icSigMediaWhitePointTag, (LPVOID) cmsD50_XYZ());
-
-       cmsAddTag(hICC, icSigAToB0Tag, (LPVOID) Lut);
-
-       // LUT is already on virtual profile
-       cmsFreeLUT(Lut);
-
-       // Ok, done
-       return hICC;
-}
-
+    // Creates a Pipeline with 3D grid only
+    LUT = cmsPipelineAlloc(ContextID, 4, 4);
+    if (LUT == NULL) goto Error;
 
 
-static
-LPLUT Create3x3EmptyLUT(void)
-{
-        LPLUT AToB0 = cmsAllocLUT();
-        if (AToB0 == NULL) return NULL;
+    nChannels = cmsChannelsOf(ColorSpace);
+
+    CLUT = cmsStageAllocCLut16bit(ContextID, 17, nChannels, nChannels, NULL);
+    if (CLUT == NULL) goto Error;
+
+    if (!cmsStageSampleCLut16bit(CLUT, InkLimitingSampler, (void*) &Limit, 0)) goto Error;
+
+    cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, nChannels));
+    cmsPipelineInsertStage(LUT, cmsAT_END, CLUT);
+    cmsPipelineInsertStage(LUT, cmsAT_END, _cmsStageAllocIdentityCurves(ContextID, nChannels));
+
+    // Create tags
+    if (!SetTextTags(hICC, L"ink-limiting built-in")) goto Error;
 
-        AToB0 -> InputChan = AToB0 -> OutputChan = 3;
-        return AToB0;
+    if (!cmsWriteTag(hICC, cmsSigAToB0Tag, (void*) LUT))  goto Error;
+    if (!SetSeqDescTag(hICC, "ink-limiting built-in")) goto Error;
+
+    // cmsPipeline is already on virtual profile
+    cmsPipelineFree(LUT);
+
+    // Ok, done
+    return hICC;
+
+Error:
+    if (LUT != NULL)
+        cmsPipelineFree(LUT);
+
+    if (hICC != NULL)
+        cmsCloseProfile(hICC);
+
+    return NULL;
 }
 
-
-
-// Creates a fake Lab identity.
-cmsHPROFILE LCMSEXPORT cmsCreateLabProfile(LPcmsCIExyY WhitePoint)
+cmsHPROFILE CMSEXPORT cmsCreateInkLimitingDeviceLink(cmsColorSpaceSignature ColorSpace, cmsFloat64Number Limit)
 {
-        cmsHPROFILE hProfile;
-        LPLUT Lut;
-
-        hProfile = cmsCreateRGBProfile(WhitePoint == NULL ? cmsD50_xyY() : WhitePoint, NULL, NULL);
-        if (hProfile == NULL) return NULL;
-
-        cmsSetDeviceClass(hProfile, icSigAbstractClass);
-        cmsSetColorSpace(hProfile,  icSigLabData);
-        cmsSetPCS(hProfile,         icSigLabData);
-
-        cmsAddTag(hProfile, icSigDeviceMfgDescTag,     (LPVOID) "(lcms internal)");
-        cmsAddTag(hProfile, icSigProfileDescriptionTag, (LPVOID) "lcms Lab identity");
-        cmsAddTag(hProfile, icSigDeviceModelDescTag,    (LPVOID) "Lab built-in");
-
-
-       // An empty LUTs is all we need
-       Lut = Create3x3EmptyLUT();
-       if (Lut == NULL) {
-           cmsCloseProfile(hProfile);
-           return NULL;
-           }
-
-       cmsAddTag(hProfile, icSigAToB0Tag,    (LPVOID) Lut);
-       cmsAddTag(hProfile, icSigBToA0Tag,    (LPVOID) Lut);
-
-       cmsFreeLUT(Lut);
-
-       return hProfile;
+    return cmsCreateInkLimitingDeviceLinkTHR(NULL, ColorSpace, Limit);
 }
 
 
 // Creates a fake Lab identity.
-cmsHPROFILE LCMSEXPORT cmsCreateLab4Profile(LPcmsCIExyY WhitePoint)
+cmsHPROFILE CMSEXPORT cmsCreateLab2ProfileTHR(cmsContext ContextID, const cmsCIExyY* WhitePoint)
 {
-        cmsHPROFILE hProfile;
-        LPLUT Lut;
+    cmsHPROFILE hProfile;
+    cmsPipeline* LUT = NULL;
+
+    hProfile = cmsCreateRGBProfileTHR(ContextID, WhitePoint == NULL ? cmsD50_xyY() : WhitePoint, NULL, NULL);
+    if (hProfile == NULL) return NULL;
 
-        hProfile = cmsCreateRGBProfile(WhitePoint == NULL ? cmsD50_xyY() : WhitePoint, NULL, NULL);
-        if (hProfile == NULL) return NULL;
+    cmsSetProfileVersion(hProfile, 2.1);
+
+    cmsSetDeviceClass(hProfile, cmsSigAbstractClass);
+    cmsSetColorSpace(hProfile,  cmsSigLabData);
+    cmsSetPCS(hProfile,         cmsSigLabData);
+
+    if (!SetTextTags(hProfile, L"Lab identity built-in")) return NULL;
 
-        cmsSetProfileICCversion(hProfile, 0x4000000);
+    // An identity LUT is all we need
+    LUT = cmsPipelineAlloc(ContextID, 3, 3);
+    if (LUT == NULL) goto Error;
+
+    cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCLut(ContextID, 3));
+
+    if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT)) goto Error;
+    cmsPipelineFree(LUT);
+
+    return hProfile;
 
-        cmsSetDeviceClass(hProfile, icSigAbstractClass);
-        cmsSetColorSpace(hProfile,  icSigLabData);
-        cmsSetPCS(hProfile,         icSigLabData);
+Error:
+
+    if (LUT != NULL)
+        cmsPipelineFree(LUT);
 
-        cmsAddTag(hProfile, icSigDeviceMfgDescTag,     (LPVOID) "(lcms internal)");
-        cmsAddTag(hProfile, icSigProfileDescriptionTag, (LPVOID) "lcms Lab identity v4");
-        cmsAddTag(hProfile, icSigDeviceModelDescTag,    (LPVOID) "Lab v4 built-in");
+    if (hProfile != NULL)
+        cmsCloseProfile(hProfile);
+
+    return NULL;
+}
 
 
-       // An empty LUTs is all we need
-       Lut = Create3x3EmptyLUT();
-       if (Lut == NULL) {
-           cmsCloseProfile(hProfile);
-           return NULL;
-           }
-
-       Lut -> wFlags |= LUT_V4_INPUT_EMULATE_V2;
-       cmsAddTag(hProfile, icSigAToB0Tag,    (LPVOID) Lut);
-
-       Lut -> wFlags |= LUT_V4_OUTPUT_EMULATE_V2;
-       cmsAddTag(hProfile, icSigBToA0Tag,    (LPVOID) Lut);
-
-       cmsFreeLUT(Lut);
-
-       return hProfile;
+cmsHPROFILE CMSEXPORT cmsCreateLab2Profile(const cmsCIExyY* WhitePoint)
+{
+    return cmsCreateLab2ProfileTHR(NULL, WhitePoint);
 }
 
 
+// Creates a fake Lab V4 identity.
+cmsHPROFILE CMSEXPORT cmsCreateLab4ProfileTHR(cmsContext ContextID, const cmsCIExyY* WhitePoint)
+{
+    cmsHPROFILE hProfile;
+    cmsPipeline* LUT = NULL;
+
+    hProfile = cmsCreateRGBProfileTHR(ContextID, WhitePoint == NULL ? cmsD50_xyY() : WhitePoint, NULL, NULL);
+    if (hProfile == NULL) return NULL;
+
+    cmsSetProfileVersion(hProfile, 4.2);
+
+    cmsSetDeviceClass(hProfile, cmsSigAbstractClass);
+    cmsSetColorSpace(hProfile,  cmsSigLabData);
+    cmsSetPCS(hProfile,         cmsSigLabData);
+
+    if (!SetTextTags(hProfile, L"Lab identity built-in")) goto Error;
+
+    // An empty LUTs is all we need
+    LUT = cmsPipelineAlloc(ContextID, 3, 3);
+    if (LUT == NULL) goto Error;
+
+    cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, 3));
+
+    if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT)) goto Error;
+    cmsPipelineFree(LUT);
+
+    return hProfile;
+
+Error:
+
+    if (LUT != NULL)
+        cmsPipelineFree(LUT);
+
+    if (hProfile != NULL)
+        cmsCloseProfile(hProfile);
+
+    return NULL;
+}
+
+cmsHPROFILE CMSEXPORT cmsCreateLab4Profile(const cmsCIExyY* WhitePoint)
+{
+    return cmsCreateLab4ProfileTHR(NULL, WhitePoint);
+}
+
 
 // Creates a fake XYZ identity
-cmsHPROFILE LCMSEXPORT cmsCreateXYZProfile(void)
+cmsHPROFILE CMSEXPORT cmsCreateXYZProfileTHR(cmsContext ContextID)
 {
-        cmsHPROFILE hProfile;
-        LPLUT Lut;
+    cmsHPROFILE hProfile;
+    cmsPipeline* LUT = NULL;
+
+    hProfile = cmsCreateRGBProfileTHR(ContextID, cmsD50_xyY(), NULL, NULL);
+    if (hProfile == NULL) return NULL;
 
-        hProfile = cmsCreateRGBProfile(cmsD50_xyY(), NULL, NULL);
-        if (hProfile == NULL) return NULL;
+    cmsSetProfileVersion(hProfile, 4.2);
 
-        cmsSetDeviceClass(hProfile, icSigAbstractClass);
-        cmsSetColorSpace(hProfile, icSigXYZData);
-        cmsSetPCS(hProfile,  icSigXYZData);
+    cmsSetDeviceClass(hProfile, cmsSigAbstractClass);
+    cmsSetColorSpace(hProfile,  cmsSigXYZData);
+    cmsSetPCS(hProfile,         cmsSigXYZData);
+
+    if (!SetTextTags(hProfile, L"XYZ identity built-in")) goto Error;
 
-        cmsAddTag(hProfile, icSigDeviceMfgDescTag,      (LPVOID) "(lcms internal)");
-        cmsAddTag(hProfile, icSigProfileDescriptionTag, (LPVOID) "lcms XYZ identity");
-        cmsAddTag(hProfile, icSigDeviceModelDescTag,    (LPVOID)  "XYZ built-in");
+    // An identity LUT is all we need
+    LUT = cmsPipelineAlloc(ContextID, 3, 3);
+    if (LUT == NULL) goto Error;
+
+    cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, 3));
+
+    if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT)) goto Error;
+    cmsPipelineFree(LUT);
 
-       // An empty LUTs is all we need
-       Lut = Create3x3EmptyLUT();
-       if (Lut == NULL) {
-           cmsCloseProfile(hProfile);
-           return NULL;
-           }
+    return hProfile;
+
+Error:
 
-       cmsAddTag(hProfile, icSigAToB0Tag,    (LPVOID) Lut);
-       cmsAddTag(hProfile, icSigBToA0Tag,    (LPVOID) Lut);
-       cmsAddTag(hProfile, icSigPreview0Tag, (LPVOID) Lut);
+    if (LUT != NULL)
+        cmsPipelineFree(LUT);
 
-       cmsFreeLUT(Lut);
-       return hProfile;
+    if (hProfile != NULL)
+        cmsCloseProfile(hProfile);
+
+    return NULL;
 }
 
 
-
-/*
-
-If  R’sRGB,G’sRGB, B’sRGB < 0.04045
-
-    R =  R’sRGB / 12.92
-    G =  G’sRGB / 12.92
-    B =  B’sRGB / 12.92
-
+cmsHPROFILE CMSEXPORT cmsCreateXYZProfile(void)
+{
+    return cmsCreateXYZProfileTHR(NULL);
+}
 
 
-else if  R’sRGB,G’sRGB, B’sRGB >= 0.04045
-
-    R = ((R’sRGB + 0.055) / 1.055)^2.4
-    G = ((G’sRGB + 0.055) / 1.055)^2.4
-    B = ((B’sRGB + 0.055) / 1.055)^2.4
-
-  */
+//sRGB Curves are defined by:
+//
+//If  R’sRGB,G’sRGB, B’sRGB < 0.04045
+//
+//    R =  R’sRGB / 12.92
+//    G =  G’sRGB / 12.92
+//    B =  B’sRGB / 12.92
+//
+//
+//else if  R’sRGB,G’sRGB, B’sRGB >= 0.04045
+//
+//    R = ((R’sRGB + 0.055) / 1.055)^2.4
+//    G = ((G’sRGB + 0.055) / 1.055)^2.4
+//    B = ((B’sRGB + 0.055) / 1.055)^2.4
 
 static
-LPGAMMATABLE Build_sRGBGamma(void)
+cmsToneCurve* Build_sRGBGamma(cmsContext ContextID)
 {
-    double Parameters[5];
+    cmsFloat64Number Parameters[5];
 
     Parameters[0] = 2.4;
     Parameters[1] = 1. / 1.055;
     Parameters[2] = 0.055 / 1.055;
     Parameters[3] = 1. / 12.92;
-    Parameters[4] = 0.04045;    // d
+    Parameters[4] = 0.04045;
 
-    return cmsBuildParametricGamma(1024, 4, Parameters);
+    return cmsBuildParametricToneCurve(ContextID, 4, Parameters);
 }
 
 // Create the ICC virtual profile for sRGB space
-cmsHPROFILE LCMSEXPORT cmsCreate_sRGBProfile(void)
+cmsHPROFILE CMSEXPORT cmsCreate_sRGBProfileTHR(cmsContext ContextID)
 {
        cmsCIExyY       D65;
        cmsCIExyYTRIPLE Rec709Primaries = {
@@ -744,38 +658,44 @@
                                    {0.3000, 0.6000, 1.0},
                                    {0.1500, 0.0600, 1.0}
                                    };
-       LPGAMMATABLE Gamma22[3];
+       cmsToneCurve* Gamma22[3];
        cmsHPROFILE  hsRGB;
 
-       cmsWhitePointFromTemp(6504, &D65);
-       Gamma22[0] = Gamma22[1] = Gamma22[2] = Build_sRGBGamma();
+       cmsWhitePointFromTemp(&D65, 6504);
+       Gamma22[0] = Gamma22[1] = Gamma22[2] = Build_sRGBGamma(ContextID);
+       if (Gamma22[0] == NULL) return NULL;
 
-       hsRGB = cmsCreateRGBProfile(&D65, &Rec709Primaries, Gamma22);
-       cmsFreeGamma(Gamma22[0]);
+       hsRGB = cmsCreateRGBProfileTHR(ContextID, &D65, &Rec709Primaries, Gamma22);
+       cmsFreeToneCurve(Gamma22[0]);
        if (hsRGB == NULL) return NULL;
 
-
-       cmsAddTag(hsRGB, icSigDeviceMfgDescTag,      (LPVOID) "(lcms internal)");
-       cmsAddTag(hsRGB, icSigDeviceModelDescTag,    (LPVOID) "sRGB built-in");
-       cmsAddTag(hsRGB, icSigProfileDescriptionTag, (LPVOID) "sRGB built-in");
+       if (!SetTextTags(hsRGB, L"sRGB built-in")) {
+           cmsCloseProfile(hsRGB);
+           return NULL;
+       }
 
        return hsRGB;
 }
 
+cmsHPROFILE CMSEXPORT cmsCreate_sRGBProfile(void)
+{
+    return cmsCreate_sRGBProfileTHR(NULL);
+}
+
 
 
 typedef struct {
-                double Brightness;
-                double Contrast;
-                double Hue;
-                double Saturation;
+                cmsFloat64Number Brightness;
+                cmsFloat64Number Contrast;
+                cmsFloat64Number Hue;
+                cmsFloat64Number Saturation;
                 cmsCIEXYZ WPsrc, WPdest;
 
 } BCHSWADJUSTS, *LPBCHSWADJUSTS;
 
 
 static
-int bchswSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
+int bchswSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
 {
     cmsCIELab LabIn, LabOut;
     cmsCIELCh LChIn, LChOut;
@@ -813,116 +733,438 @@
 // Creates an abstract profile operating in Lab space for Brightness,
 // contrast, Saturation and white point displacement
 
-cmsHPROFILE LCMSEXPORT cmsCreateBCHSWabstractProfile(int nLUTPoints,
-                                                     double Bright,
-                                                     double Contrast,
-                                                     double Hue,
-                                                     double Saturation,
+cmsHPROFILE CMSEXPORT cmsCreateBCHSWabstractProfileTHR(cmsContext ContextID,
+                                                     int nLUTPoints,
+                                                     cmsFloat64Number Bright,
+                                                     cmsFloat64Number Contrast,
+                                                     cmsFloat64Number Hue,
+                                                     cmsFloat64Number Saturation,
                                                      int TempSrc,
                                                      int TempDest)
 {
      cmsHPROFILE hICC;
-     LPLUT Lut;
+     cmsPipeline* Pipeline;
      BCHSWADJUSTS bchsw;
      cmsCIExyY WhitePnt;
+     cmsStage* CLUT;
+     cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
+     int i;
+
 
      bchsw.Brightness = Bright;
      bchsw.Contrast   = Contrast;
      bchsw.Hue        = Hue;
      bchsw.Saturation = Saturation;
 
-     cmsWhitePointFromTemp(TempSrc,  &WhitePnt);
+     cmsWhitePointFromTemp(&WhitePnt, TempSrc );
      cmsxyY2XYZ(&bchsw.WPsrc, &WhitePnt);
 
-     cmsWhitePointFromTemp(TempDest, &WhitePnt);
+     cmsWhitePointFromTemp(&WhitePnt, TempDest);
      cmsxyY2XYZ(&bchsw.WPdest, &WhitePnt);
 
-      hICC = _cmsCreateProfilePlaceholder();
+      hICC = cmsCreateProfilePlaceholder(ContextID);
        if (!hICC)                          // can't allocate
             return NULL;
 
 
-       cmsSetDeviceClass(hICC,      icSigAbstractClass);
-       cmsSetColorSpace(hICC,       icSigLabData);
-       cmsSetPCS(hICC,              icSigLabData);
+       cmsSetDeviceClass(hICC,      cmsSigAbstractClass);
+       cmsSetColorSpace(hICC,       cmsSigLabData);
+       cmsSetPCS(hICC,              cmsSigLabData);
 
-       cmsSetRenderingIntent(hICC,  INTENT_PERCEPTUAL);
+       cmsSetHeaderRenderingIntent(hICC,  INTENT_PERCEPTUAL);
 
 
-       // Creates a LUT with 3D grid only
-       Lut = cmsAllocLUT();
-       if (Lut == NULL) {
+       // Creates a Pipeline with 3D grid only
+       Pipeline = cmsPipelineAlloc(ContextID, 3, 3);
+       if (Pipeline == NULL) {
            cmsCloseProfile(hICC);
            return NULL;
            }
 
-       cmsAlloc3DGrid(Lut, nLUTPoints, 3, 3);
+       for (i=0; i < MAX_INPUT_DIMENSIONS; i++) Dimensions[i] = nLUTPoints;
+       CLUT = cmsStageAllocCLut16bitGranular(ContextID, Dimensions, 3, 3, NULL);
+       if (CLUT == NULL) return NULL;
 
-       if (!cmsSample3DGrid(Lut, bchswSampler, (LPVOID) &bchsw, 0)) {
+
+       if (!cmsStageSampleCLut16bit(CLUT, bchswSampler, (void*) &bchsw, 0)) {
 
                 // Shouldn't reach here
-                cmsFreeLUT(Lut);
+                cmsPipelineFree(Pipeline);
                 cmsCloseProfile(hICC);
                 return NULL;
        }
 
+       cmsPipelineInsertStage(Pipeline, cmsAT_END, CLUT);
+
        // Create tags
 
-       cmsAddTag(hICC, icSigDeviceMfgDescTag,      (LPVOID) "(lcms internal)");
-       cmsAddTag(hICC, icSigProfileDescriptionTag, (LPVOID) "lcms BCHSW abstract profile");
-       cmsAddTag(hICC, icSigDeviceModelDescTag,    (LPVOID) "BCHSW built-in");
+       if (!SetTextTags(hICC, L"BCHS built-in")) return NULL;
+
+       cmsWriteTag(hICC, cmsSigMediaWhitePointTag, (void*) cmsD50_XYZ());
 
-       cmsAddTag(hICC, icSigMediaWhitePointTag, (LPVOID) cmsD50_XYZ());
+       cmsWriteTag(hICC, cmsSigAToB0Tag, (void*) Pipeline);
 
-       cmsAddTag(hICC, icSigAToB0Tag, (LPVOID) Lut);
-
-       // LUT is already on virtual profile
-       cmsFreeLUT(Lut);
+       // Pipeline is already on virtual profile
+       cmsPipelineFree(Pipeline);
 
        // Ok, done
        return hICC;
+}
 
+
+CMSAPI cmsHPROFILE   CMSEXPORT cmsCreateBCHSWabstractProfile(int nLUTPoints,
+                                                             cmsFloat64Number Bright,
+                                                             cmsFloat64Number Contrast,
+                                                             cmsFloat64Number Hue,
+                                                             cmsFloat64Number Saturation,
+                                                             int TempSrc,
+                                                             int TempDest)
+{
+    return cmsCreateBCHSWabstractProfileTHR(NULL, nLUTPoints, Bright, Contrast, Hue, Saturation, TempSrc, TempDest);
 }
 
 
 // Creates a fake NULL profile. This profile return 1 channel as always 0.
 // Is useful only for gamut checking tricks
-
-cmsHPROFILE LCMSEXPORT cmsCreateNULLProfile(void)
+cmsHPROFILE CMSEXPORT cmsCreateNULLProfileTHR(cmsContext ContextID)
 {
-        cmsHPROFILE hProfile;
-        LPLUT Lut;
-        LPGAMMATABLE EmptyTab;
+    cmsHPROFILE hProfile;
+    cmsPipeline* LUT = NULL;
+    cmsStage* PostLin;
+    cmsToneCurve* EmptyTab;
+    cmsUInt16Number Zero[2] = { 0, 0 };
+
+    hProfile = cmsCreateProfilePlaceholder(ContextID);
+    if (!hProfile)                          // can't allocate
+        return NULL;
+
+    cmsSetProfileVersion(hProfile, 4.2);
+
+    if (!SetTextTags(hProfile, L"NULL profile built-in")) goto Error;
+
+
+
+    cmsSetDeviceClass(hProfile, cmsSigOutputClass);
+    cmsSetColorSpace(hProfile,  cmsSigGrayData);
+    cmsSetPCS(hProfile,         cmsSigLabData);
+
+    // An empty LUTs is all we need
+    LUT = cmsPipelineAlloc(ContextID, 1, 1);
+    if (LUT == NULL) goto Error;
+
+    EmptyTab = cmsBuildTabulatedToneCurve16(ContextID, 2, Zero);
+    PostLin = cmsStageAllocToneCurves(ContextID, 1, &EmptyTab);
+    cmsFreeToneCurve(EmptyTab);
+
+    cmsPipelineInsertStage(LUT, cmsAT_END, PostLin);
+
+    if (!cmsWriteTag(hProfile, cmsSigBToA0Tag, (void*) LUT)) goto Error;
+    if (!cmsWriteTag(hProfile, cmsSigMediaWhitePointTag, cmsD50_XYZ())) goto Error;
+
+    cmsPipelineFree(LUT);
+    return hProfile;
+
+Error:
+
+    if (LUT != NULL)
+        cmsPipelineFree(LUT);
+
+    if (hProfile != NULL)
+        cmsCloseProfile(hProfile);
+
+    return NULL;
+}
+
+cmsHPROFILE CMSEXPORT cmsCreateNULLProfile(void)
+{
+    return cmsCreateNULLProfileTHR(NULL);
+}
+
+
+static
+int IsPCS(cmsColorSpaceSignature ColorSpace)
+{
+    return (ColorSpace == cmsSigXYZData ||
+            ColorSpace == cmsSigLabData);
+}
+
+
+static
+void FixColorSpaces(cmsHPROFILE hProfile,
+                              cmsColorSpaceSignature ColorSpace,
+                              cmsColorSpaceSignature PCS,
+                              cmsUInt32Number dwFlags)
+{
+    if (dwFlags & cmsFLAGS_GUESSDEVICECLASS) {
+
+            if (IsPCS(ColorSpace) && IsPCS(PCS)) {
 
-        hProfile = _cmsCreateProfilePlaceholder();
-        if (!hProfile)                          // can't allocate
-                return NULL;
+                    cmsSetDeviceClass(hProfile,      cmsSigAbstractClass);
+                    cmsSetColorSpace(hProfile,       ColorSpace);
+                    cmsSetPCS(hProfile,              PCS);
+                    return;
+            }
+
+            if (IsPCS(ColorSpace) && !IsPCS(PCS)) {
+
+                    cmsSetDeviceClass(hProfile, cmsSigOutputClass);
+                    cmsSetPCS(hProfile,         ColorSpace);
+                    cmsSetColorSpace(hProfile,  PCS);
+                    return;
+            }
+
+            if (IsPCS(PCS) && !IsPCS(ColorSpace)) {
+
+                   cmsSetDeviceClass(hProfile,  cmsSigInputClass);
+                   cmsSetColorSpace(hProfile,   ColorSpace);
+                   cmsSetPCS(hProfile,          PCS);
+                   return;
+            }
+    }
+
+    cmsSetDeviceClass(hProfile,      cmsSigLinkClass);
+    cmsSetColorSpace(hProfile,       ColorSpace);
+    cmsSetPCS(hProfile,              PCS);
+}
+
+
 
-        cmsSetDeviceClass(hProfile, icSigOutputClass);
-        cmsSetColorSpace(hProfile,  icSigGrayData);
-        cmsSetPCS(hProfile,         icSigLabData);
+// This function creates a named color profile dumping all the contents of transform to a single profile
+// In this way, LittleCMS may be used to "group" several named color databases into a single profile.
+// It has, however, several minor limitations. PCS is always Lab, which is not very critic since this
+// is the normal PCS for named color profiles.
+static
+cmsHPROFILE CreateNamedColorDevicelink(cmsHTRANSFORM xform)
+{
+    _cmsTRANSFORM* v = (_cmsTRANSFORM*) xform;
+    cmsHPROFILE hICC = NULL;
+    int i, nColors;
+    cmsNAMEDCOLORLIST *nc2 = NULL, *Original = NULL;
+
+    // Create an empty placeholder
+    hICC = cmsCreateProfilePlaceholder(v->ContextID);
+    if (hICC == NULL) return NULL;
+
+    // Critical information
+    cmsSetDeviceClass(hICC, cmsSigNamedColorClass);
+    cmsSetColorSpace(hICC, v ->ExitColorSpace);
+    cmsSetPCS(hICC, cmsSigLabData);
+
+    // Tag profile with information
+    if (!SetTextTags(hICC, L"Named color devicelink")) goto Error;
+
+    Original = cmsGetNamedColorList(xform);
+    if (Original == NULL) goto Error;
+
+    nColors = cmsNamedColorCount(Original);
+    nc2     = cmsDupNamedColorList(Original);
+    if (nc2 == NULL) goto Error;
+
+    // Colorant count now depends on the output space
+    nc2 ->ColorantCount = cmsPipelineOutputChannels(v ->Lut);
+
+    // Apply the transfor to colorants.
+    for (i=0; i < nColors; i++) {
+        cmsDoTransform(xform, &i, nc2 ->List[i].DeviceColorant, 1);
+    }
+
+    if (!cmsWriteTag(hICC, cmsSigNamedColor2Tag, (void*) nc2)) goto Error;
+    cmsFreeNamedColorList(nc2);
+
+    return hICC;
+
+Error:
+    if (hICC != NULL) cmsCloseProfile(hICC);
+    return NULL;
+}
 
 
-       // An empty LUTs is all we need
-       Lut = cmsAllocLUT();
-       if (Lut == NULL) {
-           cmsCloseProfile(hProfile);
-           return NULL;
-           }
+// This structure holds information about which MPU can be stored on a profile based on the version
+
+typedef struct {
+    cmsBool              IsV4;             // Is a V4 tag?
+    cmsTagTypeSignature  LutType;          // The LUT type
+    int                  nTypes;           // Number of types (up to 5)
+    cmsStageSignature    MpeTypes[5];      // 5 is the maximum number
+
+} cmsAllowedLUT;
+
+static const cmsAllowedLUT AllowedLUTTypes[] = {
+
+    { FALSE, cmsSigLut16Type,    4,  { cmsSigMatrixElemType,  cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType}},
+    { FALSE, cmsSigLut16Type,    3,  { cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType}},
+    { TRUE , cmsSigLutAtoBType,  1,  { cmsSigCurveSetElemType } },
+    { TRUE , cmsSigLutAtoBType,  3,  { cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType } },
+    { TRUE , cmsSigLutAtoBType,  3,  { cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType   } },
+    { TRUE , cmsSigLutAtoBType,  5,  { cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType }},
+    { TRUE , cmsSigLutBtoAType,  1,  { cmsSigCurveSetElemType }},
+    { TRUE , cmsSigLutBtoAType,  3,  { cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType }},
+    { TRUE , cmsSigLutBtoAType,  3,  { cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType }},
+    { TRUE , cmsSigLutBtoAType,  5,  { cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType }}
+};
+
+#define SIZE_OF_ALLOWED_LUT (sizeof(AllowedLUTTypes)/sizeof(cmsAllowedLUT))
+
+// Check a single entry
+static
+cmsBool CheckOne(const cmsAllowedLUT* Tab, const cmsPipeline* Lut)
+{
+    cmsStage* mpe;
+    int n;
+
+    for (n=0, mpe = Lut ->Elements; mpe != NULL; mpe = mpe ->Next, n++) {
+
+        if (n > Tab ->nTypes) return FALSE;
+        if (cmsStageType(mpe) != Tab ->MpeTypes[n]) return FALSE;
+    }
+
+    return (n == Tab ->nTypes);
+}
+
 
-       Lut -> InputChan = 3;
-       Lut -> OutputChan = 1;
+static
+const cmsAllowedLUT* FindCombination(const cmsPipeline* Lut, cmsBool IsV4)
+{
+    int n;
+
+    for (n=0; n < SIZE_OF_ALLOWED_LUT; n++) {
+
+        const cmsAllowedLUT* Tab = AllowedLUTTypes + n;
+
+        if (IsV4 ^ Tab -> IsV4) continue;
+        if (CheckOne(Tab, Lut)) return Tab;
+    }
+
+    return NULL;
+}
+
+
+// Does convert a transform into a device link profile
+cmsHPROFILE CMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, cmsFloat64Number Version, cmsUInt32Number dwFlags)
+{
+    cmsHPROFILE hProfile = NULL;
+    cmsUInt32Number FrmIn, FrmOut, ChansIn, ChansOut;
+    cmsUInt32Number ColorSpaceBitsIn, ColorSpaceBitsOut;
+    _cmsTRANSFORM* xform = (_cmsTRANSFORM*) hTransform;
+    cmsPipeline* LUT = NULL;
+    cmsStage* mpe;
+    cmsContext ContextID = cmsGetTransformContextID(hTransform);
+    const cmsAllowedLUT* AllowedLUT;
+
+    _cmsAssert(hTransform != NULL);
+
+    // Get the first mpe to check for named color
+    mpe = cmsPipelineGetPtrToFirstStage(xform ->Lut);
+
+    // Check if is a named color transform
+    if (mpe != NULL) {
+
+        if (cmsStageType(mpe) == cmsSigNamedColorElemType) {
+            return CreateNamedColorDevicelink(hTransform);
+        }
+    }
+
+    // First thing to do is to get a copy of the transformation
+    LUT = cmsPipelineDup(xform ->Lut);
+    if (LUT == NULL) return NULL;
+
+    // Time to fix the Lab2/Lab4 issue.
+    if ((xform ->EntryColorSpace == cmsSigLabData) && (Version < 4.0)) {
+
+        cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocLabV2ToV4curves(ContextID));
+    }
 
-       EmptyTab = cmsAllocGamma(2);
-       EmptyTab ->GammaTable[0] = 0;
-       EmptyTab ->GammaTable[1] = 0;
+    // On the output side too
+    if ((xform ->ExitColorSpace) == cmsSigLabData && (Version < 4.0)) {
+
+        cmsPipelineInsertStage(LUT, cmsAT_END, _cmsStageAllocLabV4ToV2(ContextID));
+    }
+
+    // Optimize the LUT and precalculate a devicelink
+
+    ChansIn  = cmsChannelsOf(xform -> EntryColorSpace);
+    ChansOut = cmsChannelsOf(xform -> ExitColorSpace);
+
+    ColorSpaceBitsIn  = _cmsLCMScolorSpace(xform -> EntryColorSpace);
+    ColorSpaceBitsOut = _cmsLCMScolorSpace(xform -> ExitColorSpace);
+
+    FrmIn  = COLORSPACE_SH(ColorSpaceBitsIn) | CHANNELS_SH(ChansIn)|BYTES_SH(2);
+    FrmOut = COLORSPACE_SH(ColorSpaceBitsOut) | CHANNELS_SH(ChansOut)|BYTES_SH(2);
+
 
-       cmsAllocLinearTable(Lut, &EmptyTab, 2);
+    // Check if the profile/version can store the result
+    if (dwFlags & cmsFLAGS_FORCE_CLUT)
+        AllowedLUT = NULL;
+    else
+    AllowedLUT = FindCombination(LUT, Version >= 4.0);
+
+    if (AllowedLUT == NULL) {
+
+        // Try to optimize
+        _cmsOptimizePipeline(&LUT, xform ->RenderingIntent, &FrmIn, &FrmOut, &dwFlags);
+        AllowedLUT = FindCombination(LUT, Version >= 4.0);
+
+    }
+
+    // If no way, then force CLUT that for sure can be written
+    if (AllowedLUT == NULL) {
+
+        dwFlags |= cmsFLAGS_FORCE_CLUT;
+        _cmsOptimizePipeline(&LUT, xform ->RenderingIntent, &FrmIn, &FrmOut, &dwFlags);
+
+        // Put identity curves if needed
+        if (cmsPipelineStageCount(LUT) == 1) {
+
+            cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, ChansIn));
+            cmsPipelineInsertStage(LUT, cmsAT_END,   _cmsStageAllocIdentityCurves(ContextID, ChansOut));
+        }
 
-       cmsAddTag(hProfile, icSigBToA0Tag, (LPVOID) Lut);
+        AllowedLUT = FindCombination(LUT, Version >= 4.0);
+    }
+
+    // Somethings is wrong...
+    if (AllowedLUT == NULL) {
+        goto Error;
+    }
+
+    hProfile = cmsCreateProfilePlaceholder(ContextID);
+    if (!hProfile) goto Error;                    // can't allocate
+
+    cmsSetProfileVersion(hProfile, Version);
+
+    FixColorSpaces(hProfile, xform -> EntryColorSpace, xform -> ExitColorSpace, dwFlags);
+
+    if (dwFlags & cmsFLAGS_8BITS_DEVICELINK)
+                     cmsPipelineSetSaveAs8bitsFlag(LUT, TRUE);
+
+    // Tag profile with information
+    if (!SetTextTags(hProfile, L"devicelink")) return NULL;
+
+    if (cmsGetDeviceClass(hProfile) == cmsSigOutputClass) {
 
-       cmsFreeLUT(Lut);
-       cmsFreeGamma(EmptyTab);
+        if (!cmsWriteTag(hProfile, cmsSigBToA0Tag, LUT)) goto Error;
+    }
+    else
+        if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT)) goto Error;
+
+
+    if (xform -> InputColorant != NULL) {
+           if (!cmsWriteTag(hProfile, cmsSigColorantTableTag, xform->InputColorant)) goto Error;
+    }
 
-       return hProfile;
+    if (xform -> OutputColorant != NULL) {
+           if (!cmsWriteTag(hProfile, cmsSigColorantTableOutTag, xform->OutputColorant)) goto Error;
+    }
+
+    if (xform ->Sequence != NULL) {
+        if (!_cmsWriteProfileSequence(hProfile, xform ->Sequence)) goto Error;
+    }
+
+    cmsPipelineFree(LUT);
+    return hProfile;
+
+Error:
+    if (LUT != NULL) cmsPipelineFree(LUT);
+    cmsCloseProfile(hProfile);
+    return NULL;
 }
--- a/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,43 +49,38 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-#include "lcms.h"
-
-
-// Conversions
+//
+//---------------------------------------------------------------------------------
+//
 
-void LCMSEXPORT cmsXYZ2xyY(LPcmsCIExyY Dest, const cmsCIEXYZ* Source)
-{
-       double ISum;
-
-       ISum = 1./(Source -> X + Source -> Y + Source -> Z);
-
-       Dest -> x = (Source -> X) * ISum;
-       Dest -> y = (Source -> Y) * ISum;
-       Dest -> Y = Source -> Y;
-}
+#include "lcms2_internal.h"
 
 
-void LCMSEXPORT cmsxyY2XYZ(LPcmsCIEXYZ Dest, const cmsCIExyY* Source)
+// D50 - Widely used
+const cmsCIEXYZ* CMSEXPORT cmsD50_XYZ(void)
 {
+    static cmsCIEXYZ D50XYZ = {cmsD50X, cmsD50Y, cmsD50Z};
 
-        Dest -> X = (Source -> x / Source -> y) * Source -> Y;
-        Dest -> Y = Source -> Y;
-        Dest -> Z = ((1 - Source -> x - Source -> y) / Source -> y) * Source -> Y;
+    return &D50XYZ;
 }
 
+const cmsCIExyY* CMSEXPORT cmsD50_xyY(void)
+{
+    static cmsCIExyY D50xyY;
+
+    cmsXYZ2xyY(&D50xyY, cmsD50_XYZ());
+
+    return &D50xyY;
+}
 
 // Obtains WhitePoint from Temperature
-
-LCMSBOOL LCMSEXPORT cmsWhitePointFromTemp(int TempK, LPcmsCIExyY WhitePoint)
+cmsBool  CMSEXPORT cmsWhitePointFromTemp(cmsCIExyY* WhitePoint, cmsFloat64Number TempK)
 {
-       double x, y;
-       double T, T2, T3;
-       // double M1, M2;
+       cmsFloat64Number x, y;
+       cmsFloat64Number T, T2, T3;
+       // cmsFloat64Number M1, M2;
 
-
-       // No optimization provided.
+       _cmsAssert(WhitePoint != NULL);
 
        T = TempK;
        T2 = T*T;            // Square
@@ -104,7 +100,7 @@
               x = -2.0064*(1E9/T3) + 1.9018*(1E6/T2) + 0.24748*(1E3/T) + 0.237040;
        }
        else {
-              cmsSignalError(LCMS_ERRC_ABORTED, "cmsWhitePointFromTemp: invalid temp");
+              cmsSignalError(0, cmsERROR_RANGE, "cmsWhitePointFromTemp: invalid temp");
               return FALSE;
               }
 
@@ -117,10 +113,6 @@
        // M1 = (-1.3515 - 1.7703*x + 5.9114 *y)/(0.0241 + 0.2562*x - 0.7341*y);
        // M2 = (0.0300 - 31.4424*x + 30.0717*y)/(0.0241 + 0.2562*x - 0.7341*y);
 
-
-
-       // Fill WhitePoint struct
-
        WhitePoint -> x = x;
        WhitePoint -> y = y;
        WhitePoint -> Y = 1.0;
@@ -128,205 +120,16 @@
        return TRUE;
 }
 
-// Build a White point, primary chromas transfer matrix from RGB to CIE XYZ
-// This is just an approximation, I am not handling all the non-linear
-// aspects of the RGB to XYZ process, and assumming that the gamma correction
-// has transitive property in the tranformation chain.
-//
-// the alghoritm:
-//
-//            - First I build the absolute conversion matrix using
-//              primaries in XYZ. This matrix is next inverted
-//            - Then I eval the source white point across this matrix
-//              obtaining the coeficients of the transformation
-//            - Then, I apply these coeficients to the original matrix
-
-
-LCMSBOOL LCMSEXPORT cmsBuildRGB2XYZtransferMatrix(LPMAT3 r, LPcmsCIExyY WhitePt,
-                                            LPcmsCIExyYTRIPLE Primrs)
-{
-        VEC3 WhitePoint, Coef;
-        MAT3 Result, Primaries;
-        double xn, yn;
-        double xr, yr;
-        double xg, yg;
-        double xb, yb;
-
-
-        xn = WhitePt -> x;
-        yn = WhitePt -> y;
-        xr = Primrs -> Red.x;
-        yr = Primrs -> Red.y;
-        xg = Primrs -> Green.x;
-        yg = Primrs -> Green.y;
-        xb = Primrs -> Blue.x;
-        yb = Primrs -> Blue.y;
-
-
-        // Build Primaries matrix
-        VEC3init(&Primaries.v[0], xr,        xg,         xb);
-        VEC3init(&Primaries.v[1], yr,        yg,         yb);
-        VEC3init(&Primaries.v[2], (1-xr-yr), (1-xg-yg),  (1-xb-yb));
-
-
-        // Result = Primaries ^ (-1) inverse matrix
-        if (!MAT3inverse(&Primaries, &Result))
-                        return FALSE;
-
-
-        VEC3init(&WhitePoint, xn/yn, 1.0, (1.0-xn-yn)/yn);
-
-        // Across inverse primaries ...
-        MAT3eval(&Coef, &Result, &WhitePoint);
-
-        // Give us the Coefs, then I build transformation matrix
-        VEC3init(&r -> v[0], Coef.n[VX]*xr,          Coef.n[VY]*xg,          Coef.n[VZ]*xb);
-        VEC3init(&r -> v[1], Coef.n[VX]*yr,          Coef.n[VY]*yg,          Coef.n[VZ]*yb);
-        VEC3init(&r -> v[2], Coef.n[VX]*(1.0-xr-yr), Coef.n[VY]*(1.0-xg-yg), Coef.n[VZ]*(1.0-xb-yb));
-
-
-        return TRUE;
-}
-
-
-
-// Compute chromatic adaptation matrix using Chad as cone matrix
-
-static
-void ComputeChromaticAdaptation(LPMAT3 Conversion,
-                                LPcmsCIEXYZ SourceWhitePoint,
-                                LPcmsCIEXYZ DestWhitePoint,
-                                LPMAT3 Chad)
-
-{
-
-        MAT3 Chad_Inv;
-        VEC3 ConeSourceXYZ, ConeSourceRGB;
-        VEC3 ConeDestXYZ, ConeDestRGB;
-        MAT3 Cone, Tmp;
-
-
-        Tmp = *Chad;
-        MAT3inverse(&Tmp, &Chad_Inv);
-
-        VEC3init(&ConeSourceXYZ, SourceWhitePoint -> X,
-                                 SourceWhitePoint -> Y,
-                                 SourceWhitePoint -> Z);
-
-        VEC3init(&ConeDestXYZ,   DestWhitePoint -> X,
-                                 DestWhitePoint -> Y,
-                                 DestWhitePoint -> Z);
-
-        MAT3eval(&ConeSourceRGB, Chad, &ConeSourceXYZ);
-        MAT3eval(&ConeDestRGB,   Chad, &ConeDestXYZ);
-
-        // Build matrix
-
-        VEC3init(&Cone.v[0], ConeDestRGB.n[0]/ConeSourceRGB.n[0],    0.0,  0.0);
-        VEC3init(&Cone.v[1], 0.0,   ConeDestRGB.n[1]/ConeSourceRGB.n[1],   0.0);
-        VEC3init(&Cone.v[2], 0.0,   0.0,   ConeDestRGB.n[2]/ConeSourceRGB.n[2]);
-
-
-        // Normalize
-        MAT3per(&Tmp, &Cone, Chad);
-        MAT3per(Conversion, &Chad_Inv, &Tmp);
-
-}
-
-
-// Returns the final chrmatic adaptation from illuminant FromIll to Illuminant ToIll
-// The cone matrix can be specified in ConeMatrix. If NULL, Bradford is assumed
-
-LCMSBOOL cmsAdaptationMatrix(LPMAT3 r, LPMAT3 ConeMatrix, LPcmsCIEXYZ FromIll, LPcmsCIEXYZ ToIll)
-{
-     MAT3 LamRigg   = {{ // Bradford matrix
-                      {{  0.8951,  0.2664, -0.1614 }},
-                      {{ -0.7502,  1.7135,  0.0367 }},
-                      {{  0.0389, -0.0685,  1.0296 }}
-                      }};
-
-
-      if (ConeMatrix == NULL)
-            ConeMatrix = &LamRigg;
-
-      ComputeChromaticAdaptation(r, FromIll, ToIll, ConeMatrix);
-      return TRUE;
-
-}
-
-// Same as anterior, but assuming D50 destination. White point is given in xyY
-
-LCMSBOOL cmsAdaptMatrixToD50(LPMAT3 r, LPcmsCIExyY SourceWhitePt)
-{
-        cmsCIEXYZ Dn;
-        MAT3 Bradford;
-        MAT3 Tmp;
-
-        cmsxyY2XYZ(&Dn, SourceWhitePt);
-
-        cmsAdaptationMatrix(&Bradford, NULL, &Dn, cmsD50_XYZ());
-
-        Tmp = *r;
-        MAT3per(r, &Bradford, &Tmp);
-
-        return TRUE;
-}
-
-
-// Same as anterior, but assuming D50 source. White point is given in xyY
-
-LCMSBOOL cmsAdaptMatrixFromD50(LPMAT3 r, LPcmsCIExyY DestWhitePt)
-{
-        cmsCIEXYZ Dn;
-        MAT3 Bradford;
-        MAT3 Tmp;
-
-        cmsxyY2XYZ(&Dn, DestWhitePt);
-
-        cmsAdaptationMatrix(&Bradford, NULL, cmsD50_XYZ(), &Dn);
-
-        Tmp = *r;
-        MAT3per(r, &Bradford, &Tmp);
-
-        return TRUE;
-}
-
-
-// Adapts a color to a given illuminant. Original color is expected to have
-// a SourceWhitePt white point.
-
-LCMSBOOL LCMSEXPORT cmsAdaptToIlluminant(LPcmsCIEXYZ Result,
-                                     LPcmsCIEXYZ SourceWhitePt,
-                                     LPcmsCIEXYZ Illuminant,
-                                     LPcmsCIEXYZ Value)
-{
-        MAT3 Bradford;
-        VEC3 In, Out;
-
-        // BradfordLamRiggChromaticAdaptation(&Bradford, SourceWhitePt, Illuminant);
-
-        cmsAdaptationMatrix(&Bradford, NULL, SourceWhitePt, Illuminant);
-
-        VEC3init(&In, Value -> X, Value -> Y, Value -> Z);
-        MAT3eval(&Out, &Bradford, &In);
-
-        Result -> X = Out.n[0];
-        Result -> Y = Out.n[1];
-        Result -> Z = Out.n[2];
-
-        return TRUE;
-}
-
 
 
 typedef struct {
 
-    double mirek;  // temp (in microreciprocal kelvin)
-    double ut;     // u coord of intersection w/ blackbody locus
-    double vt;     // v coord of intersection w/ blackbody locus
-    double tt;     // slope of ISOTEMPERATURE. line
+    cmsFloat64Number mirek;  // temp (in microreciprocal kelvin)
+    cmsFloat64Number ut;     // u coord of intersection w/ blackbody locus
+    cmsFloat64Number vt;     // v coord of intersection w/ blackbody locus
+    cmsFloat64Number tt;     // slope of ISOTEMPERATURE. line
 
-    } ISOTEMPERATURE,FAR* LPISOTEMPERATURE;
+    } ISOTEMPERATURE;
 
 static ISOTEMPERATURE isotempdata[] = {
 //  {Mirek, Ut,       Vt,      Tt      }
@@ -360,27 +163,28 @@
     {525,   0.31320,  0.35968,  -15.628 },
     {550,   0.32129,  0.36011,  -23.325 },
     {575,   0.32931,  0.36038,  -40.770 },
-    {600,   0.33724,  0.36051, -116.45  }
+    {600,   0.33724,  0.36051,  -116.45  }
 };
 
 #define NISO sizeof(isotempdata)/sizeof(ISOTEMPERATURE)
 
 
 // Robertson's method
-
-static
-double Robertson(LPcmsCIExyY v)
+cmsBool  CMSEXPORT cmsTempFromWhitePoint(cmsFloat64Number* TempK, const cmsCIExyY* WhitePoint)
 {
     int j;
-    double us,vs;
-    double uj,vj,tj,di,dj,mi,mj;
-    double Tc = -1, xs, ys;
+    cmsFloat64Number us,vs;
+    cmsFloat64Number uj,vj,tj,di,dj,mi,mj;
+    cmsFloat64Number xs, ys;
+
+    _cmsAssert(WhitePoint != NULL);
+    _cmsAssert(TempK != NULL);
 
     di = mi = 0;
-    xs = v -> x;
-    ys = v -> y;
+    xs = WhitePoint -> x;
+    ys = WhitePoint -> y;
 
-    // convert (x,y) to CIE 1960 (u,v)
+    // convert (x,y) to CIE 1960 (u,WhitePoint)
 
     us = (2*xs) / (-xs + 6*ys + 1.5);
     vs = (3*ys) / (-xs + 6*ys + 1.5);
@@ -393,332 +197,182 @@
         tj = isotempdata[j].tt;
         mj = isotempdata[j].mirek;
 
-        dj = ((vs - vj) - tj * (us - uj)) / sqrt(1 + tj*tj);
+        dj = ((vs - vj) - tj * (us - uj)) / sqrt(1.0 + tj * tj);
+
+        if ((j != 0) && (di/dj < 0.0)) {
 
-        if ((j!=0) && (di/dj < 0.0)) {
-            Tc = 1000000.0 / (mi + (di / (di - dj)) * (mj - mi));
-            break;
+            // Found a match
+            *TempK = 1000000.0 / (mi + (di / (di - dj)) * (mj - mi));
+            return TRUE;
         }
 
         di = dj;
         mi = mj;
     }
 
-
-    if (j == NISO) return -1;
-    return Tc;
-}
-
-
-
-static
-LCMSBOOL InRange(LPcmsCIExyY a, LPcmsCIExyY b, double tolerance)
-{
-       double dist_x, dist_y;
-
-       dist_x = fabs(a->x - b->x);
-       dist_y = fabs(a->y - b->y);
-
-       return (tolerance >= dist_x * dist_x + dist_y * dist_y);
-
+    // Not found
+    return FALSE;
 }
 
 
-typedef struct {
-                char Name[30];
-                cmsCIExyY Val;
-
-              } WHITEPOINTS,FAR *LPWHITEPOINTS;
+// Compute chromatic adaptation matrix using Chad as cone matrix
 
 static
-int FromD40toD150(LPWHITEPOINTS pts)
+cmsBool ComputeChromaticAdaptation(cmsMAT3* Conversion,
+                                const cmsCIEXYZ* SourceWhitePoint,
+                                const cmsCIEXYZ* DestWhitePoint,
+                                const cmsMAT3* Chad)
+
 {
-       int i, n;
+
+    cmsMAT3 Chad_Inv;
+    cmsVEC3 ConeSourceXYZ, ConeSourceRGB;
+    cmsVEC3 ConeDestXYZ, ConeDestRGB;
+    cmsMAT3 Cone, Tmp;
+
+
+    Tmp = *Chad;
+    if (!_cmsMAT3inverse(&Tmp, &Chad_Inv)) return FALSE;
 
-       n = 0;
-       for (i=40; i < 150; i ++)
-       {
-              sprintf(pts[n].Name, "D%d", i);
-              cmsWhitePointFromTemp((int) (i*100.0), &pts[n].Val);
-              n++;
-       }
+    _cmsVEC3init(&ConeSourceXYZ, SourceWhitePoint -> X,
+                             SourceWhitePoint -> Y,
+                             SourceWhitePoint -> Z);
+
+    _cmsVEC3init(&ConeDestXYZ,   DestWhitePoint -> X,
+                             DestWhitePoint -> Y,
+                             DestWhitePoint -> Z);
 
-   return n;
-}
+    _cmsMAT3eval(&ConeSourceRGB, Chad, &ConeSourceXYZ);
+    _cmsMAT3eval(&ConeDestRGB,   Chad, &ConeDestXYZ);
+
+    // Build matrix
+    _cmsVEC3init(&Cone.v[0], ConeDestRGB.n[0]/ConeSourceRGB.n[0],    0.0,  0.0);
+    _cmsVEC3init(&Cone.v[1], 0.0,   ConeDestRGB.n[1]/ConeSourceRGB.n[1],   0.0);
+    _cmsVEC3init(&Cone.v[2], 0.0,   0.0,   ConeDestRGB.n[2]/ConeSourceRGB.n[2]);
 
 
-// To be removed in future versions
-void _cmsIdentifyWhitePoint(char *Buffer, LPcmsCIEXYZ WhitePt)
+    // Normalize
+    _cmsMAT3per(&Tmp, &Cone, Chad);
+    _cmsMAT3per(Conversion, &Chad_Inv, &Tmp);
+
+    return TRUE;
+}
+
+// Returns the final chrmatic adaptation from illuminant FromIll to Illuminant ToIll
+// The cone matrix can be specified in ConeMatrix. If NULL, Bradford is assumed
+cmsBool  _cmsAdaptationMatrix(cmsMAT3* r, const cmsMAT3* ConeMatrix, const cmsCIEXYZ* FromIll, const cmsCIEXYZ* ToIll)
 {
-       int i, n;
-       cmsCIExyY Val;
-       double T;
-       WHITEPOINTS SomeIlluminants[140] = {
+    cmsMAT3 LamRigg   = {{ // Bradford matrix
+            {{  0.8951,  0.2664, -0.1614 }},
+            {{ -0.7502,  1.7135,  0.0367 }},
+            {{  0.0389, -0.0685,  1.0296 }}
+        }};
+
+    if (ConeMatrix == NULL)
+        ConeMatrix = &LamRigg;
 
-                                   {"CIE illuminant A", {0.4476, 0.4074, 1.0}},
-                                   {"CIE illuminant C", {0.3101, 0.3162, 1.0}},
-                                   {"D65 (daylight)",   {0.3127, 0.3291, 1.0}},
-                                   };
+    return ComputeChromaticAdaptation(r, FromIll, ToIll, ConeMatrix);
+}
 
-              n = FromD40toD150(&SomeIlluminants[3]) + 3;
+// Same as anterior, but assuming D50 destination. White point is given in xyY
+static
+cmsBool _cmsAdaptMatrixToD50(cmsMAT3* r, const cmsCIExyY* SourceWhitePt)
+{
+    cmsCIEXYZ Dn;
+    cmsMAT3 Bradford;
+    cmsMAT3 Tmp;
 
-              cmsXYZ2xyY(&Val, WhitePt);
+    cmsxyY2XYZ(&Dn, SourceWhitePt);
+
+    if (!_cmsAdaptationMatrix(&Bradford, NULL, &Dn, cmsD50_XYZ())) return FALSE;
+
+    Tmp = *r;
+    _cmsMAT3per(r, &Bradford, &Tmp);
+
+    return TRUE;
+}
 
-              Val.Y = 1.;
-              for (i=0; i < n; i++)
-              {
+// Build a White point, primary chromas transfer matrix from RGB to CIE XYZ
+// This is just an approximation, I am not handling all the non-linear
+// aspects of the RGB to XYZ process, and assumming that the gamma correction
+// has transitive property in the tranformation chain.
+//
+// the alghoritm:
+//
+//            - First I build the absolute conversion matrix using
+//              primaries in XYZ. This matrix is next inverted
+//            - Then I eval the source white point across this matrix
+//              obtaining the coeficients of the transformation
+//            - Then, I apply these coeficients to the original matrix
+//
+cmsBool _cmsBuildRGB2XYZtransferMatrix(cmsMAT3* r, const cmsCIExyY* WhitePt, const cmsCIExyYTRIPLE* Primrs)
+{
+    cmsVEC3 WhitePoint, Coef;
+    cmsMAT3 Result, Primaries;
+    cmsFloat64Number xn, yn;
+    cmsFloat64Number xr, yr;
+    cmsFloat64Number xg, yg;
+    cmsFloat64Number xb, yb;
 
-                            if (InRange(&Val, &SomeIlluminants[i].Val, 0.000005))
-                            {
-                                strcpy(Buffer, "WhitePoint : ");
-                                strcat(Buffer, SomeIlluminants[i].Name);
-                                return;
-                            }
-              }
+    xn = WhitePt -> x;
+    yn = WhitePt -> y;
+    xr = Primrs -> Red.x;
+    yr = Primrs -> Red.y;
+    xg = Primrs -> Green.x;
+    yg = Primrs -> Green.y;
+    xb = Primrs -> Blue.x;
+    yb = Primrs -> Blue.y;
+
+    // Build Primaries matrix
+    _cmsVEC3init(&Primaries.v[0], xr,        xg,         xb);
+    _cmsVEC3init(&Primaries.v[1], yr,        yg,         yb);
+    _cmsVEC3init(&Primaries.v[2], (1-xr-yr), (1-xg-yg),  (1-xb-yb));
+
 
-              T = Robertson(&Val);
+    // Result = Primaries ^ (-1) inverse matrix
+    if (!_cmsMAT3inverse(&Primaries, &Result))
+        return FALSE;
+
+
+    _cmsVEC3init(&WhitePoint, xn/yn, 1.0, (1.0-xn-yn)/yn);
 
-              if (T > 0)
-                sprintf(Buffer, "White point near %dK", (int) T);
-              else
-              {
-              sprintf(Buffer, "Unknown white point (X:%1.2g, Y:%1.2g, Z:%1.2g)",
-                                          WhitePt -> X, WhitePt -> Y, WhitePt -> Z);
+    // Across inverse primaries ...
+    _cmsMAT3eval(&Coef, &Result, &WhitePoint);
 
-              }
+    // Give us the Coefs, then I build transformation matrix
+    _cmsVEC3init(&r -> v[0], Coef.n[VX]*xr,          Coef.n[VY]*xg,          Coef.n[VZ]*xb);
+    _cmsVEC3init(&r -> v[1], Coef.n[VX]*yr,          Coef.n[VY]*yg,          Coef.n[VZ]*yb);
+    _cmsVEC3init(&r -> v[2], Coef.n[VX]*(1.0-xr-yr), Coef.n[VY]*(1.0-xg-yg), Coef.n[VZ]*(1.0-xb-yb));
+
+
+    return _cmsAdaptMatrixToD50(r, WhitePt);
 
 }
 
 
-// Use darker colorant to obtain black point
-
-static
-int BlackPointAsDarkerColorant(cmsHPROFILE hInput,
-                               int Intent,
-                               LPcmsCIEXYZ BlackPoint,
-                               DWORD dwFlags)
+// Adapts a color to a given illuminant. Original color is expected to have
+// a SourceWhitePt white point.
+cmsBool CMSEXPORT cmsAdaptToIlluminant(cmsCIEXYZ* Result,
+                                       const cmsCIEXYZ* SourceWhitePt,
+                                       const cmsCIEXYZ* Illuminant,
+                                       const cmsCIEXYZ* Value)
 {
-    WORD *Black, *White;
-    cmsHTRANSFORM xform;
-    icColorSpaceSignature Space;
-    int nChannels;
-    DWORD dwFormat;
-    cmsHPROFILE hLab;
-    cmsCIELab  Lab;
-    cmsCIEXYZ  BlackXYZ, MediaWhite;
-
-    // If the profile does not support input direction, assume Black point 0
-    if (!cmsIsIntentSupported(hInput, Intent, LCMS_USED_AS_INPUT)) {
-
-        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
-        return 0;
-    }
-
-
-    // Try to get black by using black colorant
-    Space = cmsGetColorSpace(hInput);
-
-    if (!_cmsEndPointsBySpace(Space, &White, &Black, &nChannels)) {
-
-        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
-        return 0;
-    }
-
-    dwFormat = CHANNELS_SH(nChannels)|BYTES_SH(2);
-
-    hLab = cmsCreateLabProfile(NULL);
-
-    xform = cmsCreateTransform(hInput, dwFormat,
-                                hLab, TYPE_Lab_DBL, Intent, cmsFLAGS_NOTPRECALC);
-
-
-    cmsDoTransform(xform, Black, &Lab, 1);
-
-    // Force it to be neutral, clip to max. L* of 50
-
-    Lab.a = Lab.b = 0;
-    if (Lab.L > 50) Lab.L = 50;
-
-    cmsCloseProfile(hLab);
-    cmsDeleteTransform(xform);
-
-    cmsLab2XYZ(NULL, &BlackXYZ, &Lab);
-
-    if (Intent == INTENT_ABSOLUTE_COLORIMETRIC) {
-
-        *BlackPoint = BlackXYZ;
-    }
-    else {
-
-        if (!(dwFlags & LCMS_BPFLAGS_D50_ADAPTED)) {
-
-            cmsTakeMediaWhitePoint(&MediaWhite, hInput);
-            cmsAdaptToIlluminant(BlackPoint, cmsD50_XYZ(), &MediaWhite, &BlackXYZ);
-        }
-        else
-            *BlackPoint = BlackXYZ;
-    }
-
-    return 1;
-}
-
-
-// Get a black point of output CMYK profile, discounting any ink-limiting embedded
-// in the profile. For doing that, use perceptual intent in input direction:
-// Lab (0, 0, 0) -> [Perceptual] Profile -> CMYK -> [Rel. colorimetric] Profile -> Lab
-
-static
-int BlackPointUsingPerceptualBlack(LPcmsCIEXYZ BlackPoint,
-                                   cmsHPROFILE hProfile,
-                                   DWORD dwFlags)
-{
-    cmsHTRANSFORM hPercLab2CMYK, hRelColCMYK2Lab;
-    cmsHPROFILE hLab;
-    cmsCIELab LabIn, LabOut;
-    WORD CMYK[MAXCHANNELS];
-    cmsCIEXYZ  BlackXYZ, MediaWhite;
-
-
-     if (!cmsIsIntentSupported(hProfile, INTENT_PERCEPTUAL, LCMS_USED_AS_INPUT)) {
-
-        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
-        return 0;
-    }
-
-    hLab = cmsCreateLabProfile(NULL);
-
-    hPercLab2CMYK  = cmsCreateTransform(hLab, TYPE_Lab_DBL,
-                                        hProfile, TYPE_CMYK_16,
-                                        INTENT_PERCEPTUAL, cmsFLAGS_NOTPRECALC);
-
-    hRelColCMYK2Lab = cmsCreateTransform(hProfile, TYPE_CMYK_16,
-                                         hLab, TYPE_Lab_DBL,
-                                         INTENT_RELATIVE_COLORIMETRIC, cmsFLAGS_NOTPRECALC);
-
-    LabIn.L = LabIn.a = LabIn.b = 0;
-
-    cmsDoTransform(hPercLab2CMYK, &LabIn, CMYK, 1);
-    cmsDoTransform(hRelColCMYK2Lab, CMYK, &LabOut, 1);
-
-    if (LabOut.L > 50) LabOut.L = 50;
-    LabOut.a = LabOut.b = 0;
+    cmsMAT3 Bradford;
+    cmsVEC3 In, Out;
 
-    cmsDeleteTransform(hPercLab2CMYK);
-    cmsDeleteTransform(hRelColCMYK2Lab);
-    cmsCloseProfile(hLab);
-
-    cmsLab2XYZ(NULL, &BlackXYZ, &LabOut);
-
-    if (!(dwFlags & LCMS_BPFLAGS_D50_ADAPTED)){
-            cmsTakeMediaWhitePoint(&MediaWhite, hProfile);
-            cmsAdaptToIlluminant(BlackPoint, cmsD50_XYZ(), &MediaWhite, &BlackXYZ);
-    }
-    else
-            *BlackPoint = BlackXYZ;
-
-    return 1;
-
-}
-
-
-// Get Perceptual black of v4 profiles.
-static
-int GetV4PerceptualBlack(LPcmsCIEXYZ BlackPoint, cmsHPROFILE hProfile, DWORD dwFlags)
-{
-        if (dwFlags & LCMS_BPFLAGS_D50_ADAPTED) {
+    _cmsAssert(Result != NULL);
+    _cmsAssert(SourceWhitePt != NULL);
+    _cmsAssert(Illuminant != NULL);
+    _cmsAssert(Value != NULL);
 
-            BlackPoint->X = PERCEPTUAL_BLACK_X;
-            BlackPoint->Y = PERCEPTUAL_BLACK_Y;
-            BlackPoint->Z = PERCEPTUAL_BLACK_Z;
-        }
-        else {
-
-            cmsCIEXYZ D50BlackPoint, MediaWhite;
-
-            cmsTakeMediaWhitePoint(&MediaWhite, hProfile);
-            D50BlackPoint.X = PERCEPTUAL_BLACK_X;
-            D50BlackPoint.Y = PERCEPTUAL_BLACK_Y;
-            D50BlackPoint.Z = PERCEPTUAL_BLACK_Z;
-
-            // Obtain the absolute XYZ. Adapt perceptual black back from D50 to whatever media white
-            cmsAdaptToIlluminant(BlackPoint, cmsD50_XYZ(), &MediaWhite, &D50BlackPoint);
-        }
-
-
-        return 1;
-}
-
-
-// This function shouldn't exist at all -- there is such quantity of broken
-// profiles on black point tag, that we must somehow fix chromaticity to
-// avoid huge tint when doing Black point compensation. This function does
-// just that. There is a special flag for using black point tag, but turned
-// off by default because it is bogus on most profiles. The detection algorithm
-// involves to turn BP to neutral and to use only L component.
-
-int cmsDetectBlackPoint(LPcmsCIEXYZ BlackPoint, cmsHPROFILE hProfile, int Intent, DWORD dwFlags)
-{
-
-    // v4 + perceptual & saturation intents does have its own black point, and it is
-    // well specified enough to use it.
+    if (!_cmsAdaptationMatrix(&Bradford, NULL, SourceWhitePt, Illuminant)) return FALSE;
 
-    if ((cmsGetProfileICCversion(hProfile) >= 0x4000000) &&
-        (Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) {
-
-       // Matrix shaper share MRC & perceptual intents
-       if (_cmsIsMatrixShaper(hProfile))
-           return BlackPointAsDarkerColorant(hProfile, INTENT_RELATIVE_COLORIMETRIC, BlackPoint, cmsFLAGS_NOTPRECALC);
-
-       // CLUT based - Get perceptual black point (fixed value)
-       return GetV4PerceptualBlack(BlackPoint, hProfile, dwFlags);
-    }
-
-
-#ifdef HONOR_BLACK_POINT_TAG
-
-    // v2, v4 rel/abs colorimetric
-    if (cmsIsTag(hProfile, icSigMediaBlackPointTag) &&
-                    Intent == INTENT_RELATIVE_COLORIMETRIC) {
-
-        cmsCIEXYZ BlackXYZ, UntrustedBlackPoint, TrustedBlackPoint, MediaWhite;
-        cmsCIELab Lab;
-
-             // If black point is specified, then use it,
-
-             cmsTakeMediaBlackPoint(&BlackXYZ, hProfile);
-             cmsTakeMediaWhitePoint(&MediaWhite, hProfile);
-
-             // Black point is absolute XYZ, so adapt to D50 to get PCS value
-             cmsAdaptToIlluminant(&UntrustedBlackPoint, &MediaWhite, cmsD50_XYZ(), &BlackXYZ);
+    _cmsVEC3init(&In, Value -> X, Value -> Y, Value -> Z);
+    _cmsMAT3eval(&Out, &Bradford, &In);
 
-             // Force a=b=0 to get rid of any chroma
-
-             cmsXYZ2Lab(NULL, &Lab, &UntrustedBlackPoint);
-             Lab.a = Lab.b = 0;
-             if (Lab.L > 50) Lab.L = 50; // Clip to L* <= 50
-
-             cmsLab2XYZ(NULL, &TrustedBlackPoint, &Lab);
-
-             // Return BP as D50 relative or absolute XYZ (depends on flags)
-             if (!(dwFlags & LCMS_BPFLAGS_D50_ADAPTED))
-                    cmsAdaptToIlluminant(BlackPoint, cmsD50_XYZ(), &MediaWhite, &TrustedBlackPoint);
-             else
-                    *BlackPoint = TrustedBlackPoint;
+    Result -> X = Out.n[0];
+    Result -> Y = Out.n[1];
+    Result -> Z = Out.n[2];
 
-             return 1;
-    }
-
-#endif
-
-    // That is about v2 profiles.
-
-    // If output profile, discount ink-limiting and that's all
-    if (Intent == INTENT_RELATIVE_COLORIMETRIC &&
-            (cmsGetDeviceClass(hProfile) == icSigOutputClass) &&
-            (cmsGetColorSpace(hProfile) == icSigCmykData))
-                return BlackPointUsingPerceptualBlack(BlackPoint, hProfile, dwFlags);
-
-    // Nope, compute BP using current intent.
-    return BlackPointAsDarkerColorant(hProfile, Intent, BlackPoint, dwFlags);
-
+    return TRUE;
 }
--- a/src/share/native/sun/java2d/cmm/lcms/cmsxform.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/share/native/sun/java2d/cmm/lcms/cmsxform.c	Fri Sep 24 16:41:32 2010 -0700
@@ -27,9 +27,10 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+//---------------------------------------------------------------------------------
 //
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -48,1863 +49,436 @@
 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
+//
+//---------------------------------------------------------------------------------
+//
 
-#include "lcms.h"
-
+#include "lcms2_internal.h"
 
 // Transformations stuff
 // -----------------------------------------------------------------------
 
-
-// Interface
-
-cmsHTRANSFORM LCMSEXPORT cmsCreateTransform(cmsHPROFILE Input,
-                                       DWORD InputFormat,
-                                       cmsHPROFILE Output,
-                                       DWORD OutputFormat,
-                                       int Intent,
-                                       DWORD dwFlags);
-
-cmsHTRANSFORM LCMSEXPORT cmsCreateProofingTransform(cmsHPROFILE Input,
-                                               DWORD InputFormat,
-                                               cmsHPROFILE Output,
-                                               DWORD OutputFormat,
-                                               cmsHPROFILE Proofing,
-                                               int Intent,
-                                               int ProofingIntent,
-                                               DWORD dwFlags);
+// Alarm codes for 16-bit transformations, because the fixed range of containers there are
+// no values left to mark out of gamut. volatile is C99 per 6.2.5
+static volatile cmsUInt16Number Alarm[cmsMAXCHANNELS];
+static volatile cmsFloat64Number GlobalAdaptationState = 0;
 
-
-void         LCMSEXPORT cmsDeleteTransform(cmsHTRANSFORM hTransform);
-
-void         LCMSEXPORT cmsDoTransform(cmsHTRANSFORM Transform,
-                                  LPVOID InputBuffer,
-                                  LPVOID OutputBuffer, unsigned int Size);
+// The adaptation state may be defaulted by this function. If you don't like it, use the extended transform routine
+cmsFloat64Number CMSEXPORT cmsSetAdaptationState(cmsFloat64Number d)
+{
+    cmsFloat64Number OldVal = GlobalAdaptationState;
 
-void         LCMSEXPORT cmsGetAlarmCodes(int *r, int *g, int *b);
-void         LCMSEXPORT cmsSetAlarmCodes(int r, int g, int b);
-LCMSBOOL     LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
-                                                int Intent, int UsedDirection);
-
-// -------------------------------------------------------------------------
-
-
-// Alarm RGB codes
-
-static WORD AlarmR = 0x8fff, AlarmG = 0x8fff, AlarmB = 0x8fff;
+    if (d >= 0)
+        GlobalAdaptationState = d;
 
-// Tag tables, soted by intents
-
-static icTagSignature Device2PCS[] = {icSigAToB0Tag,       // Perceptual
-                                      icSigAToB1Tag,       // Relative colorimetric
-                                      icSigAToB2Tag,       // Saturation
-                                      icSigAToB1Tag };     // Absolute colorimetric
-                                                           // (Relative/WhitePoint)
-
-static icTagSignature PCS2Device[] = {icSigBToA0Tag,       // Perceptual
-                                      icSigBToA1Tag,       // Relative colorimetric
-                                      icSigBToA2Tag,       // Saturation
-                                      icSigBToA1Tag };     // Absolute colorimetric
-                                                           // (Relative/WhitePoint)
-
+    return OldVal;
+}
 
-static icTagSignature Preview[]    = {icSigPreview0Tag,
-                                      icSigPreview1Tag,
-                                      icSigPreview2Tag,
-                                      icSigPreview1Tag };
-
-
-
-static volatile double GlobalAdaptationState = 0;
-
-// --------------------------------Stages--------------------------------------
+// Alarm codes are always global
+void CMSEXPORT cmsSetAlarmCodes(cmsUInt16Number NewAlarm[cmsMAXCHANNELS])
+{
+    int i;
 
-// Following routines does implement several kind of steps inside
-// transform. On building the transform, code chooses adequate.
-
-
-// From Shaper-Matrix to PCS
+    _cmsAssert(NewAlarm != NULL);
 
-static
-void ShaperMatrixToPCS(struct _cmstransform_struct *p,
-                     WORD In[3], WORD Out[3])
-{
-       cmsEvalMatShaper(p -> InMatShaper, In, Out);
+    for (i=0; i < cmsMAXCHANNELS; i++)
+        Alarm[i] = NewAlarm[i];
 }
 
-// From LUT to PCS
-
-static
-void LUTtoPCS(struct _cmstransform_struct *p,
-                     WORD In[], WORD Out[3])
-{
-       cmsEvalLUT(p -> Device2PCS, In, Out);
-}
-
-// From indexed named color to PCS
-
-static
-void NC2toPCS(struct _cmstransform_struct *p,
-                     WORD In[], WORD Out[3])
+// You can get the codes cas well
+void CMSEXPORT cmsGetAlarmCodes(cmsUInt16Number OldAlarm[cmsMAXCHANNELS])
 {
-    int index = In[0];
-
-    if (index >= p ->NamedColorList-> nColors)
-        cmsSignalError(LCMS_ERRC_WARNING, "Color %d out of range", index);
-    else
-        CopyMemory(Out, p ->NamedColorList->List[index].PCS, 3 * sizeof(WORD));
-}
+    int i;
 
-// From PCS to Shaper-Matrix
+    _cmsAssert(OldAlarm != NULL);
 
-static
-void PCStoShaperMatrix(struct _cmstransform_struct *p,
-                     WORD In[3], WORD Out[3])
-{
-       cmsEvalMatShaper(p -> OutMatShaper, In, Out);
+    for (i=0; i < cmsMAXCHANNELS; i++)
+        OldAlarm[i] = Alarm[i];
 }
 
-// From PCS to LUT
+// Get rid of transform resources
+void CMSEXPORT cmsDeleteTransform(cmsHTRANSFORM hTransform)
+{
+    _cmsTRANSFORM* p = (_cmsTRANSFORM*) hTransform;
+
+    _cmsAssert(p != NULL);
+
+    if (p -> GamutCheck)
+        cmsPipelineFree(p -> GamutCheck);
 
-static
-void PCStoLUT(struct _cmstransform_struct *p,
-                     WORD In[3], WORD Out[])
-{
-       cmsEvalLUT(p -> PCS2Device, In, Out);
+    if (p -> Lut)
+        cmsPipelineFree(p -> Lut);
+
+    if (p ->InputColorant)
+        cmsFreeNamedColorList(p ->InputColorant);
+
+    if (p -> OutputColorant)
+        cmsFreeNamedColorList(p ->OutputColorant);
+
+    if (p ->Sequence)
+        cmsFreeProfileSequenceDescription(p ->Sequence);
+
+    LCMS_FREE_LOCK(&p->rwlock);
+    _cmsFree(p ->ContextID, (void *) p);
 }
 
-
-
-
-// ----------------------- TRANSFORMATIONS --------------------------
-
-
-// Inlining some assignations
-
-#define COPY_3CHANS(to, from) { to[0]=from[0]; to[1]=from[1]; to[2]=from[2]; }
-
-
-// Null transformation, only hold channels
+// Apply transform
+void CMSEXPORT cmsDoTransform(cmsHTRANSFORM  Transform,
+                              const void* InputBuffer,
+                              void* OutputBuffer,
+                              cmsUInt32Number Size)
 
-static
-void NullXFORM(_LPcmsTRANSFORM p,
-                     LPVOID in,
-                     LPVOID out, unsigned int Size)
 {
-       register LPBYTE accum;
-       register LPBYTE output;
-       WORD wIn[MAXCHANNELS];
-       register unsigned int i, n;
-
+    _cmsTRANSFORM* p = (_cmsTRANSFORM*) Transform;
 
-       accum  = (LPBYTE) in;
-       output = (LPBYTE) out;
-       n = Size;                    // Buffer len
-
-       for (i=0; i < n; i++)
-       {
-       accum = p -> FromInput(p, wIn, accum);
-       output = p -> ToOutput(p, wIn, output);
-       }
-
+    p -> xform(p, InputBuffer, OutputBuffer, Size);
 }
 
 
-// This is the "normal" proofing transform
+// Transform routines ----------------------------------------------------------------------------------------------------------
 
+// Float xform converts floats. Since there are no performance issues, one routine does all job, including gamut check.
+// Note that because extended range, we can use a -1.0 value for out of gamut in this case.
 static
-void NormalXFORM(_LPcmsTRANSFORM p,
-                     LPVOID in,
-                     LPVOID out, unsigned int Size)
+void FloatXFORM(_cmsTRANSFORM* p,
+                const void* in,
+                void* out, cmsUInt32Number Size)
 {
-       register LPBYTE accum;
-       register LPBYTE output;
-       WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
-       WORD wStageABC[3], wPCS[3], wStageLMN[MAXCHANNELS];
-       WORD wGamut[1];
-       register unsigned int i, n;
+    cmsUInt8Number* accum;
+    cmsUInt8Number* output;
+    cmsFloat32Number fIn[cmsMAXCHANNELS], fOut[cmsMAXCHANNELS];
+    cmsFloat32Number OutOfGamut;
+    cmsUInt32Number i, j;
 
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+
+    for (i=0; i < Size; i++) {
+
+        accum = p -> FromInputFloat(p, fIn, accum, Size);
 
+        // Any gamut chack to do?
+        if (p ->GamutCheck != NULL) {
 
-       accum  = (LPBYTE) in;
-       output = (LPBYTE) out;
-       n = Size;                    // Buffer len
+            // Evaluate gamut marker.
+            cmsPipelineEvalFloat( fIn, &OutOfGamut, p ->GamutCheck);
 
-       for (i=0; i < n; i++)
-       {
+            // Is current color out of gamut?
+            if (OutOfGamut > 0.0) {
+
+                // Certainly, out of gamut
+                for (j=0; j < cmsMAXCHANNELS; j++)
+                    fOut[j] = -1.0;
 
-       accum = p -> FromInput(p, wIn, accum);
-
-       p -> FromDevice(p, wIn, wStageABC);
+            }
+            else {
+                // No, proceed normally
+                cmsPipelineEvalFloat(fIn, fOut, p -> Lut);
+            }
+        }
+        else {
 
-       if (p -> Stage1) {
+            // No gamut check at all
+            cmsPipelineEvalFloat(fIn, fOut, p -> Lut);
+        }
 
-              p -> Stage1(wStageABC, wPCS, &p->m1, &p->of1);
+        // Back to asked representation
+        output = p -> ToOutputFloat(p, fOut, output, Size);
+    }
+}
+
+// 16 bit precision -----------------------------------------------------------------------------------------------------------
 
-              if (wPCS[0] == 0xFFFF &&
-                  wPCS[1] == 0xFFFF &&
-                  wPCS[2] == 0xFFFF) {
-
-                     // White cutoff
+// Null transformation, only applies formatters. No caché
+static
+void NullXFORM(_cmsTRANSFORM* p,
+               const void* in,
+               void* out, cmsUInt32Number Size)
+{
+    cmsUInt8Number* accum;
+    cmsUInt8Number* output;
+    cmsUInt16Number wIn[cmsMAXCHANNELS];
+    cmsUInt32Number i, n;
 
-                     output = p -> ToOutput((_LPcmsTRANSFORM) p,
-                                   _cmsWhiteBySpace(cmsGetColorSpace(p -> OutputProfile)),
-                                   output);
-                     continue;
-                     }
-              }
-       else
-              COPY_3CHANS(wPCS, wStageABC);
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;                    // Buffer len
+
+    for (i=0; i < n; i++) {
+
+        accum  = p -> FromInput(p, wIn, accum, Size);
+        output = p -> ToOutput(p, wIn, output, Size);
+    }
+}
 
 
-       if (p->Gamut) {
-
-       // Gamut check, enabled across CLUT
-
-       cmsEvalLUT(p -> Gamut, wPCS, wGamut);
-
-       if (wGamut[0] >= 1) {
-
-              wOut[0] = AlarmR;          // Gamut alarm
-              wOut[1] = AlarmG;
-              wOut[2] = AlarmB;
-              wOut[3] = 0;
-
-              output = p -> ToOutput((_LPcmsTRANSFORM)p, wOut, output);
-              continue;
-              }
-       }
-
-       if (p -> Preview)
-       {
-              WORD wPreview[3];    // PCS
-
-              cmsEvalLUT(p -> Preview, wPCS, wPreview);
-              COPY_3CHANS(wPCS, wPreview);
-       }
-
-       if (p -> Stage2) {
-
-              p -> Stage2(wPCS, wStageLMN, &p->m2, &p->of2);
-
-              if (wPCS[0] == 0xFFFF &&
-                  wPCS[1] == 0xFFFF &&
-                  wPCS[2] == 0xFFFF) {
-
-                     // White cutoff
-
-                     output = p -> ToOutput((_LPcmsTRANSFORM)p,
-                                   _cmsWhiteBySpace(cmsGetColorSpace(p -> OutputProfile)),
-                                   output);
-
-                     continue;
-                     }
-
-              }
-       else
-              COPY_3CHANS(wStageLMN, wPCS);
-
-       // Here wOut may come as MAXCHANNELS channels
-
-       p -> ToDevice(p, wStageLMN, wOut);
-
-       output = p -> ToOutput((_LPcmsTRANSFORM)p, wOut, output);
-       }
-}
-
-// Using precalculated LUT
+// No gamut check, no cache, 16 bits
+static
+void PrecalculatedXFORM(_cmsTRANSFORM* p,
+                        const void* in,
+                        void* out, cmsUInt32Number Size)
+{
+    register cmsUInt8Number* accum;
+    register cmsUInt8Number* output;
+    cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
+    cmsUInt32Number i, n;
 
-static
-void PrecalculatedXFORM(_LPcmsTRANSFORM p,
-                     LPVOID in,
-                     LPVOID out, unsigned int Size)
-{
-       register LPBYTE accum;
-       register LPBYTE output;
-       WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
-       unsigned int i, n;
-
-
-       accum  = (LPBYTE) in;
-       output = (LPBYTE) out;
-       n = Size;                    // Buffer len
-
-
-       for (i=0; i < n; i++) {
-
-         accum = p -> FromInput(p, wIn, accum);
-
-         // Try to speedup things on plain devicelinks
-
-         if (p ->DeviceLink ->wFlags == LUT_HAS3DGRID) {
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;
 
-           p ->DeviceLink ->CLut16params.Interp3D(wIn, wOut,
-                                    p ->DeviceLink -> T,
-                                    &p ->DeviceLink -> CLut16params);
-         }
-         else
-            cmsEvalLUT(p -> DeviceLink, wIn, wOut);
-
-
-          output = p -> ToOutput(p, wOut, output);
-       }
-}
-
-// Auxiliar: Handle precalculated gamut check
+    for (i=0; i < n; i++) {
 
-static
-void TransformOnePixelWithGamutCheck(_LPcmsTRANSFORM p, WORD wIn[], WORD wOut[])
-{
-    WORD wOutOfGamut;
-
-       cmsEvalLUT(p ->GamutCheck,  wIn, &wOutOfGamut);
-
-       if (wOutOfGamut >= 1) {
-
-              ZeroMemory(wOut, sizeof(WORD) * MAXCHANNELS);
-
-              wOut[0] = AlarmR;
-              wOut[1] = AlarmG;
-              wOut[2] = AlarmB;
-
-       }
-       else
-            cmsEvalLUT(p -> DeviceLink, wIn, wOut);
-
+        accum = p -> FromInput(p, wIn, accum, Size);
+        p ->Lut ->Eval16Fn(wIn, wOut, p -> Lut->Data);
+        output = p -> ToOutput(p, wOut, output, Size);
+    }
 }
 
 
+// Auxiliar: Handle precalculated gamut check
 static
-void PrecalculatedXFORMGamutCheck(_LPcmsTRANSFORM p,
-                                  LPVOID in,
-                                  LPVOID out, unsigned int Size)
+void TransformOnePixelWithGamutCheck(_cmsTRANSFORM* p,
+                                     const cmsUInt16Number wIn[],
+                                     cmsUInt16Number wOut[])
 {
-       register LPBYTE accum;
-       register LPBYTE output;
-       WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
-       register unsigned int i, n;
+    cmsUInt16Number wOutOfGamut;
+
+    p ->GamutCheck ->Eval16Fn(wIn, &wOutOfGamut, p ->GamutCheck ->Data);
+    if (wOutOfGamut >= 1) {
+
+        cmsUInt16Number i;
 
+        for (i=0; i < p ->Lut->OutputChannels; i++)
+            wOut[i] = Alarm[i];
+    }
+    else
+        p ->Lut ->Eval16Fn(wIn, wOut, p -> Lut->Data);
+}
 
-       accum  = (LPBYTE) in;
-       output = (LPBYTE) out;
-       n = Size;                    // Buffer len
-
-       for (i=0; i < n; i++) {
+// Gamut check, No caché, 16 bits.
+static
+void PrecalculatedXFORMGamutCheck(_cmsTRANSFORM* p,
+                                  const void* in,
+                                  void* out, cmsUInt32Number Size)
+{
+    cmsUInt8Number* accum;
+    cmsUInt8Number* output;
+    cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
+    cmsUInt32Number i, n;
 
-       accum = p -> FromInput(p, wIn, accum);
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;                    // Buffer len
 
-       TransformOnePixelWithGamutCheck(p, wIn, wOut);
+    for (i=0; i < n; i++) {
 
-       output = p -> ToOutput(p, wOut, output);
-       }
+        accum = p -> FromInput(p, wIn, accum, Size);
+        TransformOnePixelWithGamutCheck(p, wIn, wOut);
+        output = p -> ToOutput(p, wOut, output, Size);
+    }
 }
 
 
-
-// Using precalculated LUT + Cache
-
+// No gamut check, Caché, 16 bits,
 static
-void CachedXFORM(_LPcmsTRANSFORM p,
-                     LPVOID in,
-                     LPVOID out, unsigned int Size)
+void CachedXFORM(_cmsTRANSFORM* p,
+                 const void* in,
+                 void* out, cmsUInt32Number Size)
 {
-       register LPBYTE accum;
-       register LPBYTE output;
-       WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
-       register unsigned int i, n;
-       WORD CacheIn[MAXCHANNELS], CacheOut[MAXCHANNELS];
+    cmsUInt8Number* accum;
+    cmsUInt8Number* output;
+    cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
+    cmsUInt32Number i, n;
+    cmsUInt16Number CacheIn[cmsMAXCHANNELS], CacheOut[cmsMAXCHANNELS];
+
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;                    // Buffer len
+
+    // Empty buffers for quick memcmp
+    memset(wIn,  0, sizeof(wIn));
+    memset(wOut, 0, sizeof(wOut));
 
 
-       accum  = (LPBYTE) in;
-       output = (LPBYTE) out;
+    LCMS_READ_LOCK(&p ->rwlock);
+    memmove(CacheIn,  p ->CacheIn, sizeof(CacheIn));
+    memmove(CacheOut, p ->CacheOut, sizeof(CacheOut));
+    LCMS_UNLOCK(&p ->rwlock);
+
+    for (i=0; i < n; i++) {
+
+        accum = p -> FromInput(p, wIn, accum, Size);
+
+        if (memcmp(wIn, CacheIn, sizeof(CacheIn)) == 0) {
+
+            memmove(wOut, CacheOut, sizeof(CacheOut));
+        }
+        else {
+
+            p ->Lut ->Eval16Fn(wIn, wOut, p -> Lut->Data);
+
+            memmove(CacheIn,  wIn,  sizeof(CacheIn));
+            memmove(CacheOut, wOut, sizeof(CacheOut));
+        }
+
+        output = p -> ToOutput(p, wOut, output, Size);
+    }
+
+
+    LCMS_WRITE_LOCK(&p ->rwlock);
+    memmove(p->CacheIn,  CacheIn, sizeof(CacheIn));
+    memmove(p->CacheOut, CacheOut, sizeof(CacheOut));
+    LCMS_UNLOCK(&p ->rwlock);
+}
+
+
+// All those nice features together
+static
+void CachedXFORMGamutCheck(_cmsTRANSFORM* p,
+                           const void* in,
+                           void* out, cmsUInt32Number Size)
+{
+       cmsUInt8Number* accum;
+       cmsUInt8Number* output;
+       cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
+       cmsUInt32Number i, n;
+       cmsUInt16Number CacheIn[cmsMAXCHANNELS], CacheOut[cmsMAXCHANNELS];
+
+       accum  = (cmsUInt8Number*)  in;
+       output = (cmsUInt8Number*)  out;
        n = Size;                    // Buffer len
 
        // Empty buffers for quick memcmp
-
-       ZeroMemory(wIn,  sizeof(WORD) * MAXCHANNELS);
-       ZeroMemory(wOut, sizeof(WORD) * MAXCHANNELS);
-
+       memset(wIn,  0, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
+       memset(wOut, 0, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
 
        LCMS_READ_LOCK(&p ->rwlock);
-           CopyMemory(CacheIn,  p ->CacheIn, sizeof(WORD) * MAXCHANNELS);
-           CopyMemory(CacheOut, p ->CacheOut, sizeof(WORD) * MAXCHANNELS);
-       LCMS_UNLOCK(&p ->rwlock);
-
-       for (i=0; i < n; i++) {
-
-       accum = p -> FromInput(p, wIn, accum);
-
-
-       if (memcmp(wIn, CacheIn, sizeof(WORD) * MAXCHANNELS) == 0) {
-
-            CopyMemory(wOut, CacheOut, sizeof(WORD) * MAXCHANNELS);
-       }
-       else {
-
-            // Try to speedup things on plain devicelinks
-
-             if (p ->DeviceLink ->wFlags == LUT_HAS3DGRID) {
-
-             p ->DeviceLink ->CLut16params.Interp3D(wIn, wOut,
-                                    p ->DeviceLink -> T,
-                                    &p ->DeviceLink -> CLut16params);
-             }
-             else
-                  cmsEvalLUT(p -> DeviceLink, wIn, wOut);
-
-
-            CopyMemory(CacheIn,  wIn,  sizeof(WORD) * MAXCHANNELS);
-            CopyMemory(CacheOut, wOut, sizeof(WORD) * MAXCHANNELS);
-       }
-
-       output = p -> ToOutput(p, wOut, output);
-       }
-
-
-       LCMS_WRITE_LOCK(&p ->rwlock);
-           CopyMemory(p->CacheIn,  CacheIn, sizeof(WORD) * MAXCHANNELS);
-           CopyMemory(p->CacheOut, CacheOut, sizeof(WORD) * MAXCHANNELS);
-       LCMS_UNLOCK(&p ->rwlock);
-
-}
-
-
-
-// Using precalculated LUT + Cache
-
-static
-void CachedXFORMGamutCheck(_LPcmsTRANSFORM p,
-                           LPVOID in,
-                           LPVOID out, unsigned int Size)
-{
-       register LPBYTE accum;
-       register LPBYTE output;
-       WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
-       register unsigned int i, n;
-       WORD CacheIn[MAXCHANNELS], CacheOut[MAXCHANNELS];
-
-
-       accum  = (LPBYTE) in;
-       output = (LPBYTE) out;
-       n = Size;                    // Buffer len
-
-       // Empty buffers for quick memcmp
-
-       ZeroMemory(wIn,  sizeof(WORD) * MAXCHANNELS);
-       ZeroMemory(wOut, sizeof(WORD) * MAXCHANNELS);
-
-       LCMS_READ_LOCK(&p ->rwlock);
-           CopyMemory(CacheIn,  p ->CacheIn, sizeof(WORD) * MAXCHANNELS);
-           CopyMemory(CacheOut, p ->CacheOut, sizeof(WORD) * MAXCHANNELS);
+           memmove(CacheIn,  p ->CacheIn, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
+           memmove(CacheOut, p ->CacheOut, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
        LCMS_UNLOCK(&p ->rwlock);
 
 
        for (i=0; i < n; i++) {
 
-       accum = p -> FromInput(p, wIn, accum);
-
-       if (memcmp(wIn, CacheIn, sizeof(WORD) * MAXCHANNELS) == 0) {
-
-            CopyMemory(wOut, CacheOut, sizeof(WORD) * MAXCHANNELS);
-       }
-       else {
+            accum = p -> FromInput(p, wIn, accum, Size);
 
-            TransformOnePixelWithGamutCheck(p, wIn, wOut);
+            if (memcmp(wIn, CacheIn, sizeof(cmsUInt16Number) * cmsMAXCHANNELS) == 0) {
+                    memmove(wOut, CacheOut, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
+            }
+            else {
+                    TransformOnePixelWithGamutCheck(p, wIn, wOut);
+                    memmove(CacheIn, wIn, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
+                    memmove(CacheOut, wOut, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
+            }
 
-            CopyMemory(CacheIn, wIn, sizeof(WORD) * MAXCHANNELS);
-            CopyMemory(CacheOut, wOut, sizeof(WORD) * MAXCHANNELS);
-       }
-
-       output = p -> ToOutput(p, wOut, output);
+            output = p -> ToOutput(p, wOut, output, Size);
        }
 
         LCMS_WRITE_LOCK(&p ->rwlock);
-           CopyMemory(p->CacheIn,  CacheIn, sizeof(WORD) * MAXCHANNELS);
-           CopyMemory(p->CacheOut, CacheOut, sizeof(WORD) * MAXCHANNELS);
+           memmove(p->CacheIn,  CacheIn, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
+           memmove(p->CacheOut, CacheOut, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
         LCMS_UNLOCK(&p ->rwlock);
 }
 
 
-// Using smelted Matrix/Shaper
-
-static
-void MatrixShaperXFORM(_LPcmsTRANSFORM p,
-                     LPVOID in,
-                     LPVOID out, unsigned int Size)
-{
-       register LPBYTE accum;
-       register LPBYTE output;
-       WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
-       register unsigned int i, n;
-
-
-       accum  = (LPBYTE) in;
-       output = (LPBYTE) out;
-       n = Size;                    // Buffer len
-
-       for (i=0; i < n; i++)
-       {
-       accum = p -> FromInput(p, wIn, accum);
-       cmsEvalMatShaper(p -> SmeltMatShaper, wIn, wOut);
-       output = p -> ToOutput(p, wOut, output);
-       }
-}
-
-
-// Using Named color input table
-
-static
-void NC2deviceXform(_LPcmsTRANSFORM p,
-                     LPVOID in,
-                     LPVOID out, unsigned int Size)
-{
-
-       register LPBYTE accum;
-       register LPBYTE output;
-       WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
-       register unsigned int i;
-
-
-       accum  = (LPBYTE) in;
-       output = (LPBYTE) out;
-
-       for (i=0; i < Size; i++) {
-
-       accum = p -> FromInput(p, wIn, accum);
-       CopyMemory(wOut, p ->NamedColorList->List[wIn[0]].DeviceColorant, sizeof(WORD) * MAXCHANNELS);
-       output = p -> ToOutput(p, wOut, output);
-       }
-
-}
-
-
-
-// --------------------------------------------------------------------------
-// Build a LUT based on shape-matrix method.
-
-
-// Some non-conformant gray profiles are using kTCR as L*,
-// this function converts the curve to XYZ PCS.
-
-static
-void FromLstarToXYZ(LPGAMMATABLE g, LPGAMMATABLE gxyz[3])
-{
-    int i;
-    int nPoints = 4096;
-    cmsCIELab Lab;
-    cmsCIEXYZ XYZ;
-    L16PARAMS L16;
-
-    // Setup interpolation across origin
-    cmsCalcL16Params(g ->nEntries, &L16);
-
-    // Allocate curves
-    gxyz[0] = cmsAllocGamma(nPoints);
-    gxyz[1] = cmsAllocGamma(nPoints);
-    gxyz[2] = cmsAllocGamma(nPoints);
-
-    // Transport from Lab to XYZ
-
-    for (i=0; i < nPoints; i++) {
-
-        WORD val = _cmsQuantizeVal(i, nPoints);
-        WORD w   = cmsLinearInterpLUT16(val, g->GammaTable, &L16);
-
-        Lab.L = ((double) 100.0 * w ) / 65535.0;
-        Lab.a = Lab.b = 0;
-
-        cmsLab2XYZ(NULL, &XYZ, &Lab);
-
-        // Should be same curve
-        gxyz[0] ->GammaTable[i] = (WORD) floor((65535.0 * XYZ.X) / D50X + 0.5);
-        gxyz[1] ->GammaTable[i] = (WORD) floor((65535.0 * XYZ.Y) / D50Y + 0.5);
-        gxyz[2] ->GammaTable[i] = (WORD) floor((65535.0 * XYZ.Z) / D50Z + 0.5);
-    }
-}
-
-// Monochrome version
-
-static
-LPMATSHAPER cmsBuildGrayInputMatrixShaper(cmsHPROFILE hProfile)
-{
-       cmsCIEXYZ Illuminant;
-       LPGAMMATABLE GrayTRC, Shapes[3];
-       LPMATSHAPER MatShaper;
-       MAT3 Scale;
-
-       GrayTRC = cmsReadICCGamma(hProfile, icSigGrayTRCTag);        // Y
-       if (GrayTRC == NULL) return NULL;
-
-       cmsTakeIluminant(&Illuminant, hProfile);
-
-       if (cmsGetPCS(hProfile) == icSigLabData) {
-
-                // Fixup for Lab monochrome
-                FromLstarToXYZ(GrayTRC, Shapes);
-       }
-       else  {
-                Shapes[0] = cmsDupGamma(GrayTRC);
-                Shapes[1] = cmsDupGamma(GrayTRC);
-                Shapes[2] = cmsDupGamma(GrayTRC);
-       }
-
-       if (!Shapes[0] || !Shapes[1] || !Shapes[2])
-              return NULL;
-
-       cmsFreeGamma(GrayTRC);
-
-       // R=G=B as precondition
-
-       VEC3init(&Scale.v[0], Illuminant.X/3,  Illuminant.X/3,  Illuminant.X/3);
-       VEC3init(&Scale.v[1], Illuminant.Y/3,  Illuminant.Y/3,  Illuminant.Y/3);
-       VEC3init(&Scale.v[2], Illuminant.Z/3,  Illuminant.Z/3,  Illuminant.Z/3);
-
-
-       MatShaper = cmsAllocMatShaper(&Scale, Shapes, MATSHAPER_INPUT);
-       cmsFreeGammaTriple(Shapes);
-       return MatShaper;
-
-}
-
-
-// Monochrome as output
-
-static
-LPMATSHAPER cmsBuildGrayOutputMatrixShaper(cmsHPROFILE hProfile)
-{
-       cmsCIEXYZ Illuminant;
-       LPGAMMATABLE GrayTRC, Shapes[3];
-       LPMATSHAPER MatShaper;
-       MAT3 Scale;
-
-       cmsTakeIluminant(&Illuminant, hProfile);
-
-       // That is a special case for non-compliant profiles.
-
-       if (cmsGetPCS(hProfile) == icSigLabData) {
-
-                LPGAMMATABLE Shapes1[3];
-
-                GrayTRC = cmsReadICCGamma(hProfile, icSigGrayTRCTag);
-                FromLstarToXYZ(GrayTRC, Shapes1);
-
-                // Reversing must be done after curve translation
-
-                Shapes[0] = cmsReverseGamma(Shapes1[0]->nEntries, Shapes1[0]);
-                Shapes[1] = cmsReverseGamma(Shapes1[1]->nEntries, Shapes1[1]);
-                Shapes[2] = cmsReverseGamma(Shapes1[2]->nEntries, Shapes1[2]);
-
-                cmsFreeGammaTriple(Shapes1);
-
-       }
-       else  {
-
-                // Normal case
-
-                GrayTRC = cmsReadICCGammaReversed(hProfile, icSigGrayTRCTag);   // Y
-
-                Shapes[0] = cmsDupGamma(GrayTRC);
-                Shapes[1] = cmsDupGamma(GrayTRC);
-                Shapes[2] = cmsDupGamma(GrayTRC);
-       }
-
-       if (!Shapes[0] || !Shapes[1] || !Shapes[2])
-              return NULL;
-
-       cmsFreeGamma(GrayTRC);
-
-       VEC3init(&Scale.v[0], 0,  1.0/Illuminant.Y,  0);
-       VEC3init(&Scale.v[1], 0,  1.0/Illuminant.Y,  0);
-       VEC3init(&Scale.v[2], 0,  1.0/Illuminant.Y,  0);
-
-
-       MatShaper = cmsAllocMatShaper(&Scale, Shapes, MATSHAPER_OUTPUT);
-       cmsFreeGammaTriple(Shapes);
-       return MatShaper;
-
-}
-
-
-
-// Input matrix, only in XYZ
-
-LPMATSHAPER cmsBuildInputMatrixShaper(cmsHPROFILE InputProfile)
-{
-       MAT3 DoubleMat;
-       LPGAMMATABLE Shapes[3];
-       LPMATSHAPER InMatSh;
-
-       // Check if this is a grayscale profile. If so, build
-       // appropiate conversion tables. The tables are the PCS
-       // iluminant, scaled across GrayTRC
-
-       if (cmsGetColorSpace(InputProfile) == icSigGrayData)
-       {
-              return cmsBuildGrayInputMatrixShaper(InputProfile);
-       }
-
-       if (!cmsReadICCMatrixRGB2XYZ(&DoubleMat, InputProfile))
-                     return NULL;
-
-       Shapes[0] = cmsReadICCGamma(InputProfile, icSigRedTRCTag);
-       Shapes[1] = cmsReadICCGamma(InputProfile, icSigGreenTRCTag);
-       Shapes[2] = cmsReadICCGamma(InputProfile, icSigBlueTRCTag);
-
-       if (!Shapes[0] || !Shapes[1] || !Shapes[2])
-                     return NULL;
-
-       InMatSh = cmsAllocMatShaper(&DoubleMat, Shapes, MATSHAPER_INPUT);
-
-       cmsFreeGammaTriple(Shapes);
-
-       return InMatSh;
-}
-
-
-// Output style matrix-shaper
-
-
-LPMATSHAPER cmsBuildOutputMatrixShaper(cmsHPROFILE OutputProfile)
-{
-       MAT3 DoubleMat, DoubleInv;
-       LPGAMMATABLE InverseShapes[3];
-       LPMATSHAPER OutMatSh;
-
-
-
-       if (cmsGetColorSpace(OutputProfile) == icSigGrayData)
-       {
-              return cmsBuildGrayOutputMatrixShaper(OutputProfile);
-       }
-
-
-       if (!cmsReadICCMatrixRGB2XYZ(&DoubleMat, OutputProfile))
-                     return NULL;
-
-       if (MAT3inverse(&DoubleMat, &DoubleInv) < 0)
-              return NULL;
-
-
-       InverseShapes[0] = cmsReadICCGammaReversed(OutputProfile, icSigRedTRCTag);
-       InverseShapes[1] = cmsReadICCGammaReversed(OutputProfile, icSigGreenTRCTag);
-       InverseShapes[2] = cmsReadICCGammaReversed(OutputProfile, icSigBlueTRCTag);
-
-       if (InverseShapes[0] == NULL ||
-           InverseShapes[1] == NULL ||
-           InverseShapes[2] == NULL) return NULL;
-
-       OutMatSh = cmsAllocMatShaper(&DoubleInv, InverseShapes, MATSHAPER_OUTPUT);
-
-       cmsFreeGammaTriple(InverseShapes);
-
-       return OutMatSh;
-}
-
-
-
-// This function builds a transform matrix chaining parameters
-
-static
-LCMSBOOL cmsBuildSmeltMatShaper(_LPcmsTRANSFORM p)
-{
-       MAT3 From, To, ToInv, Transfer;
-       LPGAMMATABLE In[3], InverseOut[3];
-
-
-       if (!cmsReadICCMatrixRGB2XYZ(&From, p -> InputProfile))
-                     return FALSE;
-
-
-       if (!cmsReadICCMatrixRGB2XYZ(&To, p -> OutputProfile))
-                     return FALSE;
-
-       // invert dest
-
-       if (MAT3inverse(&To, &ToInv) < 0)
-                        return FALSE;
-
-       // Multiply
-        MAT3per(&Transfer, &ToInv, &From);
-
-
-        // Read gamma curves
-
-        In[0] = cmsReadICCGamma(p -> InputProfile, icSigRedTRCTag);
-        In[1] = cmsReadICCGamma(p -> InputProfile, icSigGreenTRCTag);
-        In[2] = cmsReadICCGamma(p -> InputProfile, icSigBlueTRCTag);
-
-        if (!In[0] || !In[1] || !In[2])
-                     return FALSE;
-
-
-        InverseOut[0] = cmsReadICCGammaReversed(p -> OutputProfile, icSigRedTRCTag);
-        InverseOut[1] = cmsReadICCGammaReversed(p -> OutputProfile, icSigGreenTRCTag);
-        InverseOut[2] = cmsReadICCGammaReversed(p -> OutputProfile, icSigBlueTRCTag);
-
-        if (!InverseOut[0] || !InverseOut[1] || !InverseOut[2]) {
-                     cmsFreeGammaTriple(In);
-                     return FALSE;
-        }
-
-        p -> SmeltMatShaper = cmsAllocMatShaper2(&Transfer, In, InverseOut, MATSHAPER_ALLSMELTED);
-
-        cmsFreeGammaTriple(In);
-        cmsFreeGammaTriple(InverseOut);
-
-        return (p -> SmeltMatShaper != NULL);
-}
-
-
-
-
-// Conversion between PCS ------------------------------------------
-
-// Identifies intent archieved by LUT
-
-static
-int GetPhase(cmsHPROFILE hProfile)
-{
-       switch (cmsGetPCS(hProfile)) {
-
-       case icSigXYZData: return XYZRel;
-
-       case icSigLabData: return LabRel;
-
-       default:  cmsSignalError(LCMS_ERRC_ABORTED, "Invalid PCS");
-       }
-
-       return XYZRel;
-}
-
-
 
 
+// Allocate transform struct and set it to defaults
 static
-void TakeConversionRoutines(_LPcmsTRANSFORM p, int DoBPC)
-{
-       cmsCIEXYZ BlackPointIn, WhitePointIn, IlluminantIn;
-       cmsCIEXYZ BlackPointOut, WhitePointOut, IlluminantOut;
-       cmsCIEXYZ BlackPointProof, WhitePointProof, IlluminantProof;
-       MAT3 ChromaticAdaptationMatrixIn, ChromaticAdaptationMatrixOut;
-       MAT3 ChromaticAdaptationMatrixProof;
-
-
-       cmsTakeIluminant(&IlluminantIn,        p -> InputProfile);
-       cmsTakeMediaWhitePoint(&WhitePointIn,  p -> InputProfile);
-       cmsTakeMediaBlackPoint(&BlackPointIn,  p -> InputProfile);
-       cmsReadChromaticAdaptationMatrix(&ChromaticAdaptationMatrixIn, p -> InputProfile);
-
-       cmsTakeIluminant(&IlluminantOut,        p -> OutputProfile);
-       cmsTakeMediaWhitePoint(&WhitePointOut,  p -> OutputProfile);
-       cmsTakeMediaBlackPoint(&BlackPointOut,  p -> OutputProfile);
-       cmsReadChromaticAdaptationMatrix(&ChromaticAdaptationMatrixOut, p -> OutputProfile);
-
-
-       if (p -> Preview == NULL && p ->Gamut == NULL)     // Non-proofing
-       {
-            if (p ->Intent == INTENT_PERCEPTUAL ||
-                p ->Intent == INTENT_SATURATION) {
-
-
-                    // For v4 profiles, Perceptual PCS has a reference black point
-                    // which v2 profiles should scale to.
-
-                    if ((cmsGetProfileICCversion(p ->InputProfile) >= 0x4000000) ||
-                        (cmsGetProfileICCversion(p ->OutputProfile) >= 0x4000000)) {
-
-                           DoBPC = TRUE;
-                    }
-            }
-
-            // Black point compensation does not apply to absolute intent
-
-            if (p ->Intent == INTENT_ABSOLUTE_COLORIMETRIC)
-                            DoBPC = FALSE;
-
-            // Black point compensation does not apply to devicelink profiles
-
-            if (cmsGetDeviceClass(p ->InputProfile) == icSigLinkClass)
-                            DoBPC = FALSE;
-
-            if (cmsGetDeviceClass(p ->OutputProfile) == icSigLinkClass)
-                            DoBPC = FALSE;
-
-            if (DoBPC) {
-
-                // Detect Black points
-
-                cmsDetectBlackPoint(&BlackPointIn,    p->InputProfile,   p->Intent, 0);
-                cmsDetectBlackPoint(&BlackPointOut,   p->OutputProfile,  p->Intent, 0);
-
-                // If equal black points, then do nothing. This often applies to BP=0
-
-                if (BlackPointIn.X == BlackPointOut.X &&
-                    BlackPointIn.Y == BlackPointOut.Y &&
-                    BlackPointIn.Z == BlackPointOut.Z)
-                                DoBPC = FALSE;
-
-
-            }
-
-            cmsChooseCnvrt(p -> Intent == INTENT_ABSOLUTE_COLORIMETRIC,
-
-                 p -> Phase1,
-                             &BlackPointIn,
-                             &WhitePointIn,
-                             &IlluminantIn,
-                             &ChromaticAdaptationMatrixIn,
-
-                 p -> Phase3,
-                             &BlackPointOut,
-                             &WhitePointOut,
-                             &IlluminantOut,
-                             &ChromaticAdaptationMatrixOut,
-
-                 DoBPC,
-                 p ->AdaptationState,
-                 &p->Stage1,
-                 &p->m1, &p->of1);
-
-       }
-       else // Proofing
-       {
-
-
-       cmsTakeIluminant(&IlluminantProof,        p -> PreviewProfile);
-       cmsTakeMediaWhitePoint(&WhitePointProof,  p -> PreviewProfile);
-       cmsTakeMediaBlackPoint(&BlackPointProof,  p -> PreviewProfile);
-       cmsReadChromaticAdaptationMatrix(&ChromaticAdaptationMatrixProof, p -> PreviewProfile);
-
-       if (DoBPC) {
-
-            cmsDetectBlackPoint(&BlackPointProof, p->PreviewProfile, p->Intent, 0);
-            cmsDetectBlackPoint(&BlackPointIn,    p->InputProfile,   p->Intent, 0);
-            cmsDetectBlackPoint(&BlackPointOut,   p->OutputProfile,  p->Intent, 0);
-
-            // Reality check
-
-            if (BlackPointIn.X == BlackPointProof.X &&
-                BlackPointIn.Y == BlackPointProof.Y &&
-                BlackPointIn.Z == BlackPointProof.Z)
-                                DoBPC = FALSE;
-
-
-       }
-
-
-
-       cmsChooseCnvrt(p -> Intent == INTENT_ABSOLUTE_COLORIMETRIC,
-
-                 p -> Phase1,
-                             &BlackPointIn,
-                             &WhitePointIn,
-                             &IlluminantIn,
-                             &ChromaticAdaptationMatrixIn,
-
-                 p -> Phase2,
-                             &BlackPointProof,
-                             &WhitePointProof,
-                             &IlluminantProof,
-                             &ChromaticAdaptationMatrixProof,
-                 DoBPC,
-                 p ->AdaptationState,
-                 &p->Stage1,
-                 &p->m1, &p->of1);
-
-       cmsChooseCnvrt(p -> ProofIntent == INTENT_ABSOLUTE_COLORIMETRIC,
-
-                 p -> Phase2,
-                             &BlackPointProof,
-                             &WhitePointProof,
-                             &IlluminantProof,
-                             &ChromaticAdaptationMatrixProof,
-
-                 p -> Phase3,
-                             &BlackPointOut,
-                             &WhitePointOut,
-                             &IlluminantOut,
-                             &ChromaticAdaptationMatrixOut,
-                 0,
-                 0.0,
-                 &p->Stage2,
-                 &p->m2, &p->of2);
-       }
-
-}
-
-
-// Check colorspace
-
-static
-LCMSBOOL IsProperColorSpace(cmsHPROFILE hProfile, DWORD dwFormat, LCMSBOOL lUsePCS)
-{
-       int Space = T_COLORSPACE(dwFormat);
-
-       if (Space == PT_ANY) return TRUE;
-
-       if (lUsePCS)
-           return (Space == _cmsLCMScolorSpace(cmsGetPCS(hProfile)));
-       else
-           return (Space == _cmsLCMScolorSpace(cmsGetColorSpace(hProfile)));
-}
-
-
-// Auxiliary: allocate transform struct and set to defaults
-
-static
-_LPcmsTRANSFORM AllocEmptyTransform(void)
+_cmsTRANSFORM* AllocEmptyTransform(cmsContext ContextID, cmsUInt32Number InputFormat, cmsUInt32Number OutputFormat, cmsUInt32Number dwFlags)
 {
     // Allocate needed memory
-
-    _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) _cmsMalloc(sizeof(_cmsTRANSFORM));
-    if (!p) {
+    _cmsTRANSFORM* p = (_cmsTRANSFORM*) _cmsMallocZero(ContextID, sizeof(_cmsTRANSFORM));
+    if (!p) return NULL;
 
-          cmsSignalError(LCMS_ERRC_ABORTED, "cmsCreateTransform: _cmsMalloc() failed");
-          return NULL;
-    }
-
-    ZeroMemory(p, sizeof(_cmsTRANSFORM));
-
-    // Initialize default methods
+    // Check whatever this is a true floating point transform
+    if (_cmsFormatterIsFloat(InputFormat) && _cmsFormatterIsFloat(OutputFormat)) {
 
-    p -> xform          = NULL;
-    p -> Intent         = INTENT_PERCEPTUAL;
-    p -> ProofIntent    = INTENT_ABSOLUTE_COLORIMETRIC;
-    p -> DoGamutCheck   = FALSE;
-    p -> InputProfile   = NULL;
-    p -> OutputProfile  = NULL;
-    p -> PreviewProfile = NULL;
-    p -> Preview        = NULL;
-    p -> Gamut          = NULL;
-    p -> DeviceLink     = NULL;
-    p -> InMatShaper    = NULL;
-    p -> OutMatShaper   = NULL;
-    p -> SmeltMatShaper = NULL;
-    p -> NamedColorList = NULL;
-    p -> EntryColorSpace = (icColorSpaceSignature) 0;
-    p -> ExitColorSpace  = (icColorSpaceSignature) 0;
-    p -> AdaptationState = GlobalAdaptationState;
+        // Get formatter function always return a valid union, but the contents of this union may be NULL.
+        p ->FromInputFloat = _cmsGetFormatter(InputFormat,  cmsFormatterInput, CMS_PACK_FLAGS_FLOAT).FmtFloat;
+        p ->ToOutputFloat  = _cmsGetFormatter(OutputFormat, cmsFormatterOutput, CMS_PACK_FLAGS_FLOAT).FmtFloat;
 
-    LCMS_CREATE_LOCK(&p->rwlock);
-
-    return p;
-}
-
-
-// Identify whatever a transform is to be cached
+        if (p ->FromInputFloat == NULL || p ->ToOutputFloat == NULL) {
 
-static
-void SetPrecalculatedTransform(_LPcmsTRANSFORM p)
-{
-    if ((p->dwOriginalFlags & cmsFLAGS_GAMUTCHECK) && p ->GamutCheck != NULL) {
-
-        p -> xform = PrecalculatedXFORMGamutCheck;
-
-        if (!(p->dwOriginalFlags & cmsFLAGS_NOTCACHE)) {
-
-            ZeroMemory(p ->CacheIn, sizeof(WORD) * MAXCHANNELS);
-            TransformOnePixelWithGamutCheck(p, p->CacheIn, p ->CacheOut);
-            p ->xform = CachedXFORMGamutCheck;
+            cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported raster format");
+            _cmsFree(ContextID, p);
+            return NULL;
         }
 
+        // Float transforms don't use caché, always are non-NULL
+        p ->xform = FloatXFORM;
     }
     else {
 
-        p -> xform = PrecalculatedXFORM;
-
-        if (!(p->dwOriginalFlags & cmsFLAGS_NOTCACHE)) {
-
-            ZeroMemory(p ->CacheIn, sizeof(WORD) * MAXCHANNELS);
-            cmsEvalLUT(p ->DeviceLink, p->CacheIn, p ->CacheOut);
-            p ->xform = CachedXFORM;
-        }
-    }
-}
-
-
-// Transform is identified as device-link
-static
-cmsHPROFILE CreateDeviceLinkTransform(_LPcmsTRANSFORM p)
-{
-
-    if (!IsProperColorSpace(p->InputProfile, p->InputFormat, FALSE)) {
-        cmsSignalError(LCMS_ERRC_ABORTED, "Device link is operating on wrong colorspace on input");
-        return NULL;
-    }
-
-    if (!IsProperColorSpace(p->InputProfile, p->OutputFormat, TRUE)) {
-        cmsSignalError(LCMS_ERRC_ABORTED, "Device link is operating on wrong colorspace on output");
-        return NULL;
-    }
-
-    // Device link does only have AToB0Tag (ICC-Spec 1998/09)
-
-    p->DeviceLink = cmsReadICCLut(p->InputProfile, icSigAToB0Tag);
-
-    if (!p->DeviceLink) {
-
-         cmsSignalError(LCMS_ERRC_ABORTED, "Noncompliant device-link profile");
-         cmsDeleteTransform((cmsHTRANSFORM) p);
-         return NULL;
-         }
-
-    if (p ->PreviewProfile != NULL) {
-            cmsSignalError(LCMS_ERRC_WARNING, "Proofing not supported on device link transforms");
-    }
-
-    if (p ->OutputProfile != NULL) {
-            cmsSignalError(LCMS_ERRC_WARNING, "Output profile should be NULL, since this is a device-link transform");
-    }
+        p ->FromInput = _cmsGetFormatter(InputFormat,  cmsFormatterInput, CMS_PACK_FLAGS_16BITS).Fmt16;
+        p ->ToOutput  = _cmsGetFormatter(OutputFormat, cmsFormatterOutput, CMS_PACK_FLAGS_16BITS).Fmt16;
 
-    p -> Phase1 = -1;
-    p -> Phase2 = -1;
-    p -> Phase3 = -1;
-
-    SetPrecalculatedTransform(p);
-
-    p -> EntryColorSpace = cmsGetColorSpace(p -> InputProfile);
-    p -> ExitColorSpace  = cmsGetPCS(p -> InputProfile);
-
-    if (p ->EntryColorSpace == icSigRgbData ||
-        p ->EntryColorSpace == icSigCmyData) {
-
-                    p->DeviceLink -> CLut16params.Interp3D = cmsTetrahedralInterp16;
-    }
-
-    // Precalculated device-link profile is ready
-    return (cmsHTRANSFORM) p;
-}
-
-
-// Transform that includes proofing
-static
-void CreateProof(_LPcmsTRANSFORM p, icTagSignature *ToTagPtr)
+        if (p ->FromInput == NULL || p ->ToOutput == NULL) {
 
-{
-    icTagSignature ProofTag;
-
-    if (p -> dwOriginalFlags & cmsFLAGS_SOFTPROOFING) {
-
-      // Apr-15, 2002 - Too much profiles does have bogus content
-      // on preview tag, so I do compute it by my own.
-
-      p -> Preview = _cmsComputeSoftProofLUT(p ->PreviewProfile, p ->Intent);
-      p -> Phase2  = LabRel;
-
-      // That's a proofing transfor, so use second intent for output.
-
-      *ToTagPtr  = PCS2Device[p->ProofIntent];
-
-      if (p -> Preview == NULL) {
-
-        ProofTag = Preview[p -> Intent];
-
-        if (!cmsIsTag(p ->PreviewProfile,  ProofTag)) {
-
-            ProofTag = Preview[0];
-            if (!cmsIsTag(p ->PreviewProfile,  ProofTag))
-                            ProofTag = (icTagSignature)0;
+            cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported raster format");
+            _cmsFree(ContextID, p);
+            return NULL;
         }
 
-        if (ProofTag) {
+        if (dwFlags & cmsFLAGS_NULLTRANSFORM) {
 
-             p -> Preview = cmsReadICCLut(p ->PreviewProfile, ProofTag);
-             p -> Phase2 = GetPhase(p ->PreviewProfile);
-
+            p ->xform = NullXFORM;
         }
-        else
-             {
-             p -> Preview = NULL;
-             p ->PreviewProfile = NULL;
-             cmsSignalError(LCMS_ERRC_WARNING, "Sorry, the proof profile has not previewing capabilities");
-             }
-      }
+        else {
+            if (dwFlags & cmsFLAGS_NOCACHE) {
 
+                if (dwFlags & cmsFLAGS_GAMUTCHECK)
+                    p ->xform = PrecalculatedXFORMGamutCheck;  // Gamut check, no caché
+                else
+                    p ->xform = PrecalculatedXFORM;  // No caché, no gamut check
+            }
+            else {
+
+                if (dwFlags & cmsFLAGS_GAMUTCHECK)
+                    p ->xform = CachedXFORMGamutCheck;    // Gamut check, caché
+                else
+                    p ->xform = CachedXFORM;  // No gamut check, caché
+
+            }
+        }
     }
 
 
-    // Aug-31, 2001 - Too much profiles does have bogus content
-    // on gamut tag, so I do compute it by my own.
-
-    if ((p -> dwOriginalFlags & cmsFLAGS_GAMUTCHECK) && (p -> dwOriginalFlags & cmsFLAGS_NOTPRECALC)) {
-
-
-             p -> Gamut = _cmsComputeGamutLUT(p->PreviewProfile, p ->Intent);
-             p -> Phase2  = LabRel;
-
-             if (p -> Gamut == NULL) {
-
-                // Profile goes only in one direction... try to see
-                // if profile has the tag, and use it, no matter it
-                // could be bogus. This is the last chance!
-
-                if (cmsIsTag(p ->PreviewProfile, icSigGamutTag)) {
-
-                    p -> Gamut = cmsReadICCLut(p ->PreviewProfile, icSigGamutTag);
-
-                    }
-                    else   {
-
-                     // Nope, cannot be done.
-
-                     cmsSignalError(LCMS_ERRC_WARNING, "Sorry, the proof profile has not gamut checking capabilities");
-                     p -> Gamut = NULL;
-                    }
-             }
-
-      }
-
-}
-
-// Choose the adequate transform routine
-
-static
-_LPcmsTRANSFORM PickTransformRoutine(_LPcmsTRANSFORM p,
-                                    icTagSignature *FromTagPtr,
-                                    icTagSignature *ToTagPtr)
-{
-
-
-
-
-        // Is a named color profile?
-        if (cmsGetDeviceClass(p->InputProfile) == icSigNamedColorClass) {
-
-                  // Yes, and used as input
-                  p ->FromDevice = NC2toPCS;
-        }
-        else {
-                // Can we optimize matrix-shaper only transform?
-
-                   if ((*FromTagPtr == 0) &&
-                       (*ToTagPtr == 0) &&
-                       (!p->PreviewProfile) &&
-                       (p -> Intent != INTENT_ABSOLUTE_COLORIMETRIC) &&
-                       (p -> EntryColorSpace == icSigRgbData) &&
-                       (p -> ExitColorSpace == icSigRgbData)  &&
-                       !(p -> dwOriginalFlags & cmsFLAGS_BLACKPOINTCOMPENSATION)) {
-
-                          // Yes... try to smelt matrix-shapers
-                          p -> xform = MatrixShaperXFORM;
-                          p -> dwOriginalFlags |= cmsFLAGS_NOTPRECALC;
+    // Create a mutex for shared memory
+    LCMS_CREATE_LOCK(&p->rwlock);
 
-                          if (!cmsBuildSmeltMatShaper(p))
-                          {
-                                 cmsSignalError(LCMS_ERRC_ABORTED, "unable to smelt shaper-matrix, required tags missing");
-                                 return NULL;
-                          }
-
-                          p -> Phase1 = p -> Phase3 = XYZRel;
-                          return p;
-
-                }
-
-                // No, is a transform involving LUT
-
-                if (*FromTagPtr != 0) {
-
-                     p -> FromDevice = LUTtoPCS;
-                     p -> Device2PCS = cmsReadICCLut(p -> InputProfile, *FromTagPtr);
-                     if (!p -> Device2PCS) {
-
-                            cmsSignalError(LCMS_ERRC_ABORTED, "profile is unsuitable for input");
-                            return NULL;
-                            }
-
-              }
-              else
-              {
-                     p -> FromDevice = ShaperMatrixToPCS;
-                     p -> InMatShaper = cmsBuildInputMatrixShaper(p -> InputProfile);
-
-                     if (!p ->InMatShaper) {
-                            cmsSignalError(LCMS_ERRC_ABORTED, "profile is unsuitable for input");
-                            return NULL;
-                            }
-
-                     p -> Phase1 = XYZRel;
-
-              }
-              }
-
-              if (*ToTagPtr != 0) {
-
-                     p -> ToDevice = PCStoLUT;
-                     p -> PCS2Device = cmsReadICCLut(p -> OutputProfile, *ToTagPtr);
-                     if (!p -> PCS2Device) {
-                            cmsSignalError(LCMS_ERRC_ABORTED, "profile is unsuitable for output");
-                            return NULL;
-                            }
-
-                     }
-              else
-              {
-                     p -> ToDevice = PCStoShaperMatrix;
-                     p -> OutMatShaper = cmsBuildOutputMatrixShaper(p->OutputProfile);
-
-                     if (!p -> OutMatShaper) {
-                            cmsSignalError(LCMS_ERRC_ABORTED, "profile is unsuitable for output");
-                            return NULL;
-                            }
-                     p -> Phase3 = XYZRel;
-
-              }
-
-
-       return p;
+    p ->InputFormat     = InputFormat;
+    p ->OutputFormat    = OutputFormat;
+    p ->dwOriginalFlags = dwFlags;
+    p ->ContextID       = ContextID;
+    return p;
 }
 
-
-
-
-// Create a transform.
-
-cmsHTRANSFORM LCMSEXPORT cmsCreateProofingTransform(cmsHPROFILE InputProfile,
-                                               DWORD InputFormat,
-                                               cmsHPROFILE OutputProfile,
-                                               DWORD OutputFormat,
-                                               cmsHPROFILE ProofingProfile,
-                                               int nIntent,
-                                               int ProofingIntent,
-                                               DWORD dwFlags)
-
+static
+cmsBool GetXFormColorSpaces(int nProfiles, cmsHPROFILE hProfiles[], cmsColorSpaceSignature* Input, cmsColorSpaceSignature* Output)
 {
-       _LPcmsTRANSFORM p;
-       icTagSignature FromTag;
-       icTagSignature ToTag;
-
-       if (nIntent < 0 || nIntent > 3 ||
-           ProofingIntent < 0 || ProofingIntent > 3) {
-
-            cmsSignalError(LCMS_ERRC_ABORTED, "cmsCreateTransform: intent mismatch");
-            return NULL;
-       }
-
-       p = AllocEmptyTransform();
-       if (p == NULL) return NULL;
-
-       p -> xform           = NormalXFORM;
-       p -> Intent          = nIntent;
-       p -> ProofIntent     = ProofingIntent;
-       p -> DoGamutCheck    = FALSE;
-       p -> InputProfile    = InputProfile;
-       p -> OutputProfile   = OutputProfile;
-       p -> PreviewProfile  = ProofingProfile;
-       p -> InputFormat     = InputFormat;
-       p -> OutputFormat    = OutputFormat;
-       p -> dwOriginalFlags = dwFlags;
-
-       p -> lInputV4Lab     = p ->lOutputV4Lab = FALSE;
-
-
-       p -> FromInput = _cmsIdentifyInputFormat(p, InputFormat);
-       p -> ToOutput  = _cmsIdentifyOutputFormat(p, OutputFormat);
-
-       // Null transform can be done without profiles
-       if ((p->dwOriginalFlags & cmsFLAGS_NULLTRANSFORM) ||
-                        ((InputProfile == NULL) &&
-                         (OutputProfile == NULL))) {
-
-            p -> xform = NullXFORM;
-            return (cmsHTRANSFORM) p;
-       }
-
-       // From here we need at least one input profile
-       if (InputProfile == NULL) {
-
-          cmsSignalError(LCMS_ERRC_ABORTED, "Input profile cannot be NULL!");
-          cmsDeleteTransform((cmsHTRANSFORM) p);
-          return NULL;
-       }
-
-
-       //  Device link are means to store precalculated transform grids.
-       if (cmsGetDeviceClass(InputProfile) == icSigLinkClass) {
-
-            return CreateDeviceLinkTransform(p);
-       }
-
-       if (!IsProperColorSpace(InputProfile, InputFormat, FALSE)) {
-
-              cmsSignalError(LCMS_ERRC_ABORTED, "Input profile is operating on wrong colorspace");
-              cmsDeleteTransform((cmsHTRANSFORM) p);
-              return NULL;
-       }
-
-       p ->EntryColorSpace = cmsGetColorSpace(InputProfile);
-
-       // Oct-21-2002: Added named color transforms
-       if (cmsGetDeviceClass(InputProfile) == icSigNamedColorClass) {
-
-        if (p ->NamedColorList == NULL)
-                p ->NamedColorList = cmsAllocNamedColorList(0);
-
-        cmsReadICCnamedColorList(p, InputProfile, icSigNamedColor2Tag);
-
-        // Special case. If output profile == NULL, then the transform gives
-        // device values from named colors.
-
-        if (OutputProfile == NULL) {
-
-            p ->ExitColorSpace = p -> EntryColorSpace;
-            p ->xform = NC2deviceXform;
-            return (cmsHTRANSFORM) p;
-        }
-
-        // Named color doesn't precalc anything
-        p -> dwOriginalFlags |= cmsFLAGS_NOTPRECALC;
-       }
-
-
-       // From here we need also output profile.
-      if (OutputProfile == NULL) {
-          cmsSignalError(LCMS_ERRC_ABORTED, "Output profile cannot be NULL!");
-          cmsDeleteTransform((cmsHTRANSFORM) p);
-          return NULL;
-       }
-
-
-       if (!IsProperColorSpace(OutputProfile, OutputFormat, FALSE)) {
-              cmsSignalError(LCMS_ERRC_ABORTED, "Output profile is operating on wrong colorspace");
-              cmsDeleteTransform((cmsHTRANSFORM) p);
-              return NULL;
-       }
-
-       p -> ExitColorSpace = cmsGetColorSpace(OutputProfile);
-
-       // Named color only on input
-       if (cmsGetDeviceClass(OutputProfile) == icSigNamedColorClass) {
-
-           cmsSignalError(LCMS_ERRC_ABORTED, "Named color profiles are not supported as output");
-           cmsDeleteTransform((cmsHTRANSFORM) p);
-           return NULL;
-       }
-
-       p -> Phase1 = GetPhase(InputProfile);
-       p -> Phase2 = -1;
-       p -> Phase3 = GetPhase(OutputProfile);
-
-       // Try to locate a LUT
-
-       FromTag  = Device2PCS[nIntent];
-       ToTag    = PCS2Device[nIntent];
-
-       if (!cmsIsTag(InputProfile, FromTag)) {
-
-              FromTag = Device2PCS[0];
-
-              if (!cmsIsTag(InputProfile,  FromTag)) {
-                            FromTag = (icTagSignature)0;
-              }
-       }
-
-       // If proofing is needed, add required tags/parameters
-       if (ProofingProfile)
-           CreateProof(p, &ToTag);
-
-
-       if (!cmsIsTag(OutputProfile,  ToTag)) {
-
-           ToTag = PCS2Device[0];
-
-           // 12-Dec-2003, Abstract profiles can be placed as output and still using AToB0
-           if (cmsGetDeviceClass(OutputProfile) == icSigAbstractClass) {
-
-                    if (!cmsIsTag(OutputProfile,  ToTag)) {
-                                ToTag = (icTagSignature) icSigAToB0Tag;
-                    }
-           }
-
-           if (!cmsIsTag(OutputProfile,  ToTag))
-                            ToTag = (icTagSignature)0;
-       }
-
-
-       if (p-> dwOriginalFlags & cmsFLAGS_MATRIXINPUT)
-              FromTag = (icTagSignature)0;
-
-       if (p -> dwOriginalFlags & cmsFLAGS_MATRIXOUTPUT)
-              ToTag = (icTagSignature)0;
-
-
-
-       if (PickTransformRoutine(p, &FromTag, &ToTag) == NULL) {
-
-          cmsDeleteTransform((cmsHTRANSFORM) p);
-          return NULL;
-
-       }
-
-       TakeConversionRoutines(p, dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION);
-
-       if (!(p -> dwOriginalFlags & cmsFLAGS_NOTPRECALC)) {
-
-               LPLUT DeviceLink;
-               LPLUT GamutCheck = NULL;
-
-
-               if (p ->EntryColorSpace == icSigCmykData &&
-                   p ->ExitColorSpace == icSigCmykData &&
-                   (dwFlags & cmsFLAGS_PRESERVEBLACK)) {
-
-                    DeviceLink = _cmsPrecalculateBlackPreservingDeviceLink((cmsHTRANSFORM) p, dwFlags);
-
-                    // Cannot be done at all?
-                    if (DeviceLink == NULL)
-                            DeviceLink = _cmsPrecalculateDeviceLink((cmsHTRANSFORM) p, dwFlags);
-
-               }
-               else {
-
-                    DeviceLink = _cmsPrecalculateDeviceLink((cmsHTRANSFORM) p, dwFlags);
-               }
-
-               // Allow to specify cmsFLAGS_GAMUTCHECK, even if no proofing profile is given
-               if ((p ->PreviewProfile != NULL) && (p -> dwOriginalFlags & cmsFLAGS_GAMUTCHECK)) {
-
-                   GamutCheck = _cmsPrecalculateGamutCheck((cmsHTRANSFORM) p);
-               }
-
-               // If input colorspace is Rgb, Cmy, then use tetrahedral interpolation
-               // for speed reasons (it only works well on spaces on Luma is diagonal, and
-               // not if luma is in separate channel)
-               if (p ->EntryColorSpace == icSigRgbData ||
-                   p ->EntryColorSpace == icSigCmyData) {
-
-
-                    cmsCalcCLUT16ParamsEx(DeviceLink->CLut16params.nSamples,
-                                          DeviceLink->CLut16params.nInputs,
-                                          DeviceLink->CLut16params.nOutputs,
-                                          TRUE, &DeviceLink->CLut16params);
-
-               }
-
-               // If this is a 8-bit transform, optimize LUT further.
-
-                if ((T_BYTES(InputFormat) == 1) && (T_CHANNELS(InputFormat) == 3)) {
-
-                    DeviceLink = _cmsBlessLUT8(DeviceLink);
-                    if (DeviceLink == NULL) return NULL;
-
-                }
-
-
-                p ->GamutCheck = GamutCheck;
-
-                if (DeviceLink) {
-
-                    p ->DeviceLink = DeviceLink;
-
-                    if ((nIntent != INTENT_ABSOLUTE_COLORIMETRIC) &&
-                        !(p -> dwOriginalFlags & cmsFLAGS_NOWHITEONWHITEFIXUP))
-
-                            _cmsFixWhiteMisalignment(p);
-
-                }
-                else
-                {
-
-                     cmsSignalError(LCMS_ERRC_ABORTED,
-                                "Cannot precalculate %d->%d channels transform!",
-                                T_CHANNELS(InputFormat), T_CHANNELS(OutputFormat));
-
-                     cmsDeleteTransform(p);
-                     return NULL;
-                }
-
-
-              SetPrecalculatedTransform(p);
-
-
-       }
-
-       // Re-Identify formats
-       p -> FromInput = _cmsIdentifyInputFormat(p, InputFormat);
-       p -> ToOutput  = _cmsIdentifyOutputFormat(p, OutputFormat);
-
-
-       return p;
-}
-
-
-// Wrapper por simpler non-proofing transforms.
-
-cmsHTRANSFORM LCMSEXPORT cmsCreateTransform(cmsHPROFILE Input,
-                                       DWORD InputFormat,
-                                       cmsHPROFILE Output,
-                                       DWORD OutputFormat,
-                                       int Intent,
-                                       DWORD dwFlags)
-
-{
-       return cmsCreateProofingTransform(Input, InputFormat,
-                                         Output, OutputFormat,
-                                         NULL,
-                                         Intent, INTENT_ABSOLUTE_COLORIMETRIC,
-                                         dwFlags);
-}
-
-
-// Profiles are *NOT* closed
-
-void LCMSEXPORT cmsDeleteTransform(cmsHTRANSFORM hTransform)
-{
-       _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) (LPSTR) hTransform;
-
-       if (p -> Device2PCS)
-              cmsFreeLUT(p -> Device2PCS);
-       if (p -> PCS2Device)
-              cmsFreeLUT(p -> PCS2Device);
-       if (p -> Gamut)
-              cmsFreeLUT(p -> Gamut);
-       if (p -> Preview)
-              cmsFreeLUT(p -> Preview);
-       if (p -> DeviceLink)
-              cmsFreeLUT(p -> DeviceLink);
-       if (p -> InMatShaper)
-              cmsFreeMatShaper(p -> InMatShaper);
-       if (p -> OutMatShaper)
-              cmsFreeMatShaper(p -> OutMatShaper);
-       if (p -> SmeltMatShaper)
-              cmsFreeMatShaper(p -> SmeltMatShaper);
-       if (p ->NamedColorList)
-              cmsFreeNamedColorList(p ->NamedColorList);
-       if (p -> GamutCheck)
-            cmsFreeLUT(p -> GamutCheck);
-
-       LCMS_FREE_LOCK(&p->rwlock);
-
-       _cmsFree((void *) p);
-}
-
-
-// Apply transform code
-void LCMSEXPORT cmsDoTransform(cmsHTRANSFORM Transform,
-                    LPVOID InputBuffer,
-                    LPVOID OutputBuffer, unsigned int Size)
-
-{
-
-            _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) (LPSTR) Transform;
-
-            p -> StrideIn = p -> StrideOut = Size;
-
-            p -> xform(p, InputBuffer, OutputBuffer, Size);
-
-}
-
-
-void LCMSEXPORT cmsSetAlarmCodes(int r, int g, int b)
-{
-       AlarmR = RGB_8_TO_16(r);
-       AlarmG = RGB_8_TO_16(g);
-       AlarmB = RGB_8_TO_16(b);
-}
-
-void LCMSEXPORT cmsGetAlarmCodes(int *r, int *g, int *b)
-{
-       *r = RGB_16_TO_8(AlarmR);
-       *g = RGB_16_TO_8(AlarmG);
-       *b = RGB_16_TO_8(AlarmB);
-}
-
-// Returns TRUE if the profile is implemented as matrix-shaper
-
-LCMSBOOL LCMSEXPORT _cmsIsMatrixShaper(cmsHPROFILE hProfile)
-{
-    switch (cmsGetColorSpace(hProfile)) {
-
-    case icSigGrayData:
-
-        return cmsIsTag(hProfile, icSigGrayTRCTag);
-
-    case icSigRgbData:
-
-        return (cmsIsTag(hProfile, icSigRedColorantTag) &&
-                cmsIsTag(hProfile, icSigGreenColorantTag) &&
-                cmsIsTag(hProfile, icSigBlueColorantTag) &&
-                cmsIsTag(hProfile, icSigRedTRCTag) &&
-                cmsIsTag(hProfile, icSigGreenTRCTag) &&
-                cmsIsTag(hProfile, icSigBlueTRCTag));
-
-    default:
-
-        return FALSE;
-    }
-}
-
-
-LCMSBOOL LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
-                                                int Intent, int UsedDirection)
-{
-
-     icTagSignature* TagTable;
-
-     // Device link profiles only implements the intent in header
-
-     if (cmsGetDeviceClass(hProfile) != icSigLinkClass) {
-
-       switch (UsedDirection) {
-
-       case LCMS_USED_AS_INPUT: TagTable = Device2PCS; break;
-       case LCMS_USED_AS_OUTPUT:TagTable = PCS2Device; break;
-       case LCMS_USED_AS_PROOF: TagTable = Preview; break;
-
-       default:
-        cmsSignalError(LCMS_ERRC_ABORTED, "Unexpected direction (%d)", UsedDirection);
-        return FALSE;
-       }
-
-       if (cmsIsTag(hProfile, TagTable[Intent])) return TRUE;
-       return _cmsIsMatrixShaper(hProfile);
-     }
-
-     return (cmsTakeRenderingIntent(hProfile) == Intent);
-}
-
-// Multiple profile transform.
-static
-int MultiprofileSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
-{
-    cmsHTRANSFORM* Transforms = (cmsHTRANSFORM*) Cargo;
+    cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut;
+    cmsColorSpaceSignature PostColorSpace;
     int i;
 
-    cmsDoTransform(Transforms[0], In, Out, 1);
-
-    for (i=1; Transforms[i]; i++)
-        cmsDoTransform(Transforms[i], Out, Out, 1);
-
-
-
-    return TRUE;
-}
-
-
-static
-int IsAllowedInSingleXform(icProfileClassSignature aClass)
-{
-    return (aClass == icSigInputClass) ||
-           (aClass == icSigDisplayClass) ||
-           (aClass == icSigOutputClass) ||
-           (aClass == icSigColorSpaceClass);
-}
-
-
-// A multiprofile transform does chain several profiles into a single
-// devicelink. It couls also be used to merge named color profiles into
-// a single database.
-
-
-cmsHTRANSFORM LCMSEXPORT cmsCreateMultiprofileTransform(cmsHPROFILE hProfiles[],
-                                                                int nProfiles,
-                                                                DWORD dwInput,
-                                                                DWORD dwOutput,
-                                                                int Intent,
-                                                                DWORD dwFlags)
-{
-    cmsHTRANSFORM Transforms[257];
-    DWORD dwPrecalcFlags = (dwFlags|cmsFLAGS_NOTPRECALC|cmsFLAGS_NOTCACHE);
-    DWORD FormatInput, FormatOutput;
-    cmsHPROFILE hLab, hXYZ, hProfile;
-    icColorSpaceSignature ColorSpace, CurrentColorSpace;
-    icColorSpaceSignature ColorSpaceIn, ColorSpaceOut;
-    LPLUT Grid;
-    int nGridPoints, ChannelsInput, ChannelsOutput = 3, i;
-    _LPcmsTRANSFORM p;
-    int nNamedColor;
-
-    if (nProfiles > 255) {
-        cmsSignalError(LCMS_ERRC_ABORTED, "What are you trying to do with more that 255 profiles?!?, of course aborted");
-        return NULL;
-    }
-
-    // There is a simple case with just two profiles, try to catch it in order of getting
-    // black preservation to work on this function, at least with two profiles.
-
-
-    if (nProfiles == 2) {
-
-        icProfileClassSignature Class1 = cmsGetDeviceClass(hProfiles[0]);
-        icProfileClassSignature Class2 = cmsGetDeviceClass(hProfiles[1]);
+    if (hProfiles[0] == NULL) return FALSE;
 
-        // Only input, output and display are allowed
-
-        if (IsAllowedInSingleXform(Class1) &&
-            IsAllowedInSingleXform(Class2))
-                   return cmsCreateTransform(hProfiles[0], dwInput, hProfiles[1], dwOutput, Intent, dwFlags);
-    }
-
-
-    // Creates a phantom transform for latter filling
-    p = (_LPcmsTRANSFORM) cmsCreateTransform(NULL, dwInput,
-                                             NULL, dwOutput, Intent, cmsFLAGS_NULLTRANSFORM);
-
-    // If user wants null one, give it
-    if (dwFlags & cmsFLAGS_NULLTRANSFORM) return (cmsHPROFILE) p;
-
-    // Is a bunch of named color profiles?
-    nNamedColor = 0;
-    for (i=0; i < nProfiles; i++) {
-        if (cmsGetDeviceClass(hProfiles[i]) == icSigNamedColorClass)
-                nNamedColor++;
-    }
-
-
-    if (nNamedColor == nProfiles) {
-
-            // Yes, only named color. Create a named color-device
-            // and append to named color table
-
-            cmsDeleteTransform((cmsHTRANSFORM) p);
-
-            p = (_LPcmsTRANSFORM) cmsCreateTransform(hProfiles[0], dwInput, NULL, dwOutput, Intent, dwFlags);
-            for (i=1; i < nProfiles; i++) {
-                    cmsReadICCnamedColorList(p, hProfiles[i], icSigNamedColor2Tag);
-            }
-
-            return p;   // Ok, done so far
-    }
-    else
-    if (nNamedColor > 0) {
-
-        cmsDeleteTransform((cmsHTRANSFORM) p);
-        cmsSignalError(LCMS_ERRC_ABORTED, "Could not mix named color profiles with other types in multiprofile transform");
-        return NULL;
-    }
-
-
-    // We will need a 3DCLUT for device link
-    Grid =  cmsAllocLUT();
-    if (!Grid) return NULL;
-
-    // This one is our PCS (Always Lab)
-    hLab  = cmsCreateLabProfile(NULL);
-    hXYZ  = cmsCreateXYZProfile();
-
-    if (!hLab || !hXYZ) goto ErrorCleanup;
-
-    // Take some info....
-
-    p ->EntryColorSpace = CurrentColorSpace = cmsGetColorSpace(hProfiles[0]);
-
+    *Input = PostColorSpace = cmsGetColorSpace(hProfiles[0]);
 
     for (i=0; i < nProfiles; i++) {
 
-        int lIsDeviceLink, lIsInput;
-
-        // Check colorspace
+        cmsHPROFILE hProfile = hProfiles[i];
 
-        hProfile      = hProfiles[i];
-        lIsDeviceLink = (cmsGetDeviceClass(hProfile) == icSigLinkClass);
-        lIsInput      = (CurrentColorSpace != icSigXYZData) &&
-                        (CurrentColorSpace != icSigLabData);
+        int lIsInput = (PostColorSpace != cmsSigXYZData) &&
+                       (PostColorSpace != cmsSigLabData);
+
+        if (hProfile == NULL) return FALSE;
 
         if (lIsInput) {
 
             ColorSpaceIn    = cmsGetColorSpace(hProfile);
             ColorSpaceOut   = cmsGetPCS(hProfile);
-
         }
         else {
 
@@ -1912,136 +486,302 @@
             ColorSpaceOut   = cmsGetColorSpace(hProfile);
         }
 
-        ChannelsInput  = _cmsChannelsOf(ColorSpaceIn);
-        ChannelsOutput = _cmsChannelsOf(ColorSpaceOut);
+        PostColorSpace = ColorSpaceOut;
+    }
+
+    *Output = PostColorSpace;
+
+    return TRUE;
+}
+
+// Check colorspace
+static
+cmsBool  IsProperColorSpace(cmsColorSpaceSignature Check, cmsUInt32Number dwFormat)
+{
+    int Space1 = T_COLORSPACE(dwFormat);
+    int Space2 = _cmsLCMScolorSpace(Check);
+
+    if (Space1 == PT_ANY) return TRUE;
+    if (Space1 == Space2) return TRUE;
+
+    if (Space1 == PT_LabV2 && Space2 == PT_Lab) return TRUE;
+    if (Space1 == PT_Lab   && Space2 == PT_LabV2) return TRUE;
+
+    return FALSE;
+}
+
+// ----------------------------------------------------------------------------------------------------------------
 
-        FormatInput    = BYTES_SH(2)|CHANNELS_SH(ChannelsInput);
-        FormatOutput   = BYTES_SH(2)|CHANNELS_SH(ChannelsOutput);
+// New to lcms 2.0 -- have all parameters available.
+cmsHTRANSFORM CMSEXPORT cmsCreateExtendedTransform(cmsContext ContextID,
+                                                   cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[],
+                                                   cmsBool  BPC[],
+                                                   cmsUInt32Number Intents[],
+                                                   cmsFloat64Number AdaptationStates[],
+                                                   cmsHPROFILE hGamutProfile,
+                                                   cmsUInt32Number nGamutPCSposition,
+                                                   cmsUInt32Number InputFormat,
+                                                   cmsUInt32Number OutputFormat,
+                                                   cmsUInt32Number dwFlags)
+{
+    _cmsTRANSFORM* xform;
+    cmsBool  FloatTransform;
+    cmsColorSpaceSignature EntryColorSpace;
+    cmsColorSpaceSignature ExitColorSpace;
+    cmsPipeline* Lut;
+    cmsUInt32Number LastIntent = Intents[nProfiles-1];
+
+    // If gamut check is requested, make sure we have a gamut profile
+    if (dwFlags & cmsFLAGS_GAMUTCHECK) {
+        if (hGamutProfile == NULL) dwFlags &= ~cmsFLAGS_GAMUTCHECK;
+    }
+
+    // On floating point transforms, inhibit optimizations
+    FloatTransform = (_cmsFormatterIsFloat(InputFormat) && _cmsFormatterIsFloat(OutputFormat));
 
-        ColorSpace = ColorSpaceIn;
+    if (_cmsFormatterIsFloat(InputFormat) || _cmsFormatterIsFloat(OutputFormat))
+        dwFlags |= cmsFLAGS_NOCACHE;
+
+    // Mark entry/exit spaces
+    if (!GetXFormColorSpaces(nProfiles, hProfiles, &EntryColorSpace, &ExitColorSpace)) {
+        cmsSignalError(ContextID, cmsERROR_NULL, "NULL input profiles on transform");
+        return NULL;
+    }
+
+    // Check if proper colorspaces
+    if (!IsProperColorSpace(EntryColorSpace, InputFormat)) {
+        cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "Wrong input color space on transform");
+        return NULL;
+    }
+
+    if (!IsProperColorSpace(ExitColorSpace, OutputFormat)) {
+        cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "Wrong output color space on transform");
+        return NULL;
+    }
+
+    // Create a pipeline with all transformations
+    Lut = _cmsLinkProfiles(ContextID, nProfiles, Intents, hProfiles, BPC, AdaptationStates, dwFlags);
+    if (Lut == NULL) {
+        cmsSignalError(ContextID, cmsERROR_NOT_SUITABLE, "Couldn't link the profiles");
+        return NULL;
+    }
+
+    // Optimize the LUT if possible
+    _cmsOptimizePipeline(&Lut, LastIntent, &InputFormat, &OutputFormat, &dwFlags);
 
 
-        if (ColorSpace == CurrentColorSpace) {
-
-            if (lIsDeviceLink) {
-
-                Transforms[i]  = cmsCreateTransform(hProfile, FormatInput,
-                                                    NULL,     FormatOutput,
-                                                    Intent,   dwPrecalcFlags);
-            }
-
-            else {
+    // All seems ok
+    xform = AllocEmptyTransform(ContextID, InputFormat, OutputFormat, dwFlags);
+    if (xform == NULL) {
+        cmsPipelineFree(Lut);
+        return NULL;
+    }
 
-                if (lIsInput) {
+    // Keep values
+    xform ->EntryColorSpace = EntryColorSpace;
+    xform ->ExitColorSpace  = ExitColorSpace;
+    xform ->Lut             = Lut;
+
 
-                        Transforms[i]  = cmsCreateTransform(hProfile, FormatInput,
-                                                  (ColorSpaceOut == icSigLabData ? hLab : hXYZ), FormatOutput,
-                                                  Intent, dwPrecalcFlags);
-                }
-                else {
-                        Transforms[i]  = cmsCreateTransform((ColorSpaceIn == icSigLabData ? hLab : hXYZ), FormatInput,
-                                                  hProfile, FormatOutput,
-                                                  Intent, dwPrecalcFlags);
-
-                }
-            }
+    // Create a gamut check LUT if requested
+    if (hGamutProfile != NULL && (dwFlags & cmsFLAGS_GAMUTCHECK))
+        xform ->GamutCheck  = _cmsCreateGamutCheckPipeline(ContextID, hProfiles,
+                                                        BPC, Intents,
+                                                        AdaptationStates,
+                                                        nGamutPCSposition,
+                                                        hGamutProfile);
 
 
-        }
-        else  // Can come from pcs?
-        if (CurrentColorSpace == icSigXYZData) {
+    // Try to read input and output colorant table
+    if (cmsIsTag(hProfiles[0], cmsSigColorantTableTag)) {
+
+        // Input table can only come in this way.
+        xform ->InputColorant = cmsDupNamedColorList((cmsNAMEDCOLORLIST*) cmsReadTag(hProfiles[0], cmsSigColorantTableTag));
+    }
 
-            Transforms[i] = cmsCreateTransform(hXYZ, FormatInput,
-                                              hProfile, FormatOutput,
-                                              Intent, dwPrecalcFlags);
+    // Output is a little bit more complex.
+    if (cmsGetDeviceClass(hProfiles[nProfiles-1]) == cmsSigLinkClass) {
+
+        // This tag may exist only on devicelink profiles.
+        if (cmsIsTag(hProfiles[nProfiles-1], cmsSigColorantTableOutTag)) {
+
+            // It may be NULL if error
+            xform ->OutputColorant = cmsDupNamedColorList((cmsNAMEDCOLORLIST*) cmsReadTag(hProfiles[nProfiles-1], cmsSigColorantTableOutTag));
+        }
+
+    } else {
 
+        if (cmsIsTag(hProfiles[nProfiles-1], cmsSigColorantTableTag)) {
+
+            xform -> OutputColorant = cmsDupNamedColorList((cmsNAMEDCOLORLIST*) cmsReadTag(hProfiles[nProfiles-1], cmsSigColorantTableTag));
         }
-        else
-        if (CurrentColorSpace == icSigLabData) {
+    }
 
-            Transforms[i] = cmsCreateTransform(hLab, FormatInput,
-                                              hProfile, FormatOutput,
-                                              Intent, dwPrecalcFlags);
+    // Store the sequence of profiles
+    if (dwFlags & cmsFLAGS_KEEP_SEQUENCE) {
+        xform ->Sequence = _cmsCompileProfileSequence(ContextID, nProfiles, hProfiles);
+    }
+    else
+        xform ->Sequence = NULL;
 
+    // If this is a cached transform, init first value, which is zero (16 bits only)
+    if (!(dwFlags & cmsFLAGS_NOCACHE)) {
+
+        memset(&xform ->CacheIn, 0, sizeof(xform ->CacheIn));
+
+        if (xform ->GamutCheck != NULL) {
+            TransformOnePixelWithGamutCheck(xform, xform ->CacheIn, xform->CacheOut);
         }
         else {
-                cmsSignalError(LCMS_ERRC_ABORTED, "cmsCreateMultiprofileTransform: ColorSpace mismatch");
-                goto ErrorCleanup;
+
+            xform ->Lut ->Eval16Fn(xform ->CacheIn, xform->CacheOut, xform -> Lut->Data);
         }
 
-        if (Transforms[i] == NULL) {
-            cmsSignalError(LCMS_ERRC_ABORTED, "cmsCreateMultiprofileTransform: unable to create transform");
-            goto ErrorCleanup;
-        }
-        CurrentColorSpace = ColorSpaceOut;
-
     }
 
-    p ->ExitColorSpace = CurrentColorSpace;
-    Transforms[i] = NULL;   // End marker
+    return (cmsHTRANSFORM) xform;
+}
 
-    p ->InputProfile  = hProfiles[0];
-    p ->OutputProfile = hProfiles[nProfiles - 1];
-
-    nGridPoints = _cmsReasonableGridpointsByColorspace(p ->EntryColorSpace, dwFlags);
-
-    ChannelsInput  = _cmsChannelsOf(cmsGetColorSpace(p ->InputProfile));
+// Multiprofile transforms: Gamut check is not available here, as it is unclear from which profile the gamut comes.
 
-    Grid = cmsAlloc3DGrid(Grid, nGridPoints, ChannelsInput, ChannelsOutput);
-
-    if (!(dwFlags & cmsFLAGS_NOPRELINEARIZATION))
-           _cmsComputePrelinearizationTablesFromXFORM(Transforms, nProfiles, Grid);
+cmsHTRANSFORM CMSEXPORT cmsCreateMultiprofileTransformTHR(cmsContext ContextID,
+                                                       cmsHPROFILE hProfiles[],
+                                                       cmsUInt32Number nProfiles,
+                                                       cmsUInt32Number InputFormat,
+                                                       cmsUInt32Number OutputFormat,
+                                                       cmsUInt32Number Intent,
+                                                       cmsUInt32Number dwFlags)
+{
+    cmsUInt32Number i;
+    cmsBool BPC[256];
+    cmsUInt32Number Intents[256];
+    cmsFloat64Number AdaptationStates[256];
 
-    // Compute device link on 16-bit basis
-    if (!cmsSample3DGrid(Grid, MultiprofileSampler, (LPVOID) Transforms, Grid -> wFlags)) {
-
-                cmsFreeLUT(Grid);
-                goto ErrorCleanup;
+    if (nProfiles <= 0 || nProfiles > 255) {
+         cmsSignalError(ContextID, cmsERROR_RANGE, "Wrong number of profiles. 1..255 expected, %d found.", nProfiles);
+        return NULL;
     }
 
-    // All ok, store the newly created LUT
-    p -> DeviceLink   = Grid;
-
-    SetPrecalculatedTransform(p);
-
-    for (i=nProfiles-1; i >= 0; --i)
-        cmsDeleteTransform(Transforms[i]);
-
-
-    if (hLab) cmsCloseProfile(hLab);
-    if (hXYZ) cmsCloseProfile(hXYZ);
-
-
-    if (p ->EntryColorSpace == icSigRgbData ||
-        p ->EntryColorSpace == icSigCmyData) {
-
-                    p->DeviceLink -> CLut16params.Interp3D = cmsTetrahedralInterp16;
+    for (i=0; i < nProfiles; i++) {
+        BPC[i] = dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION ? TRUE : FALSE;
+        Intents[i] = Intent;
+        AdaptationStates[i] = GlobalAdaptationState;
     }
 
 
-    if ((Intent != INTENT_ABSOLUTE_COLORIMETRIC) &&
-        !(dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP))
-                            _cmsFixWhiteMisalignment(p);
-
-    return (cmsHTRANSFORM) p;
-
-
-ErrorCleanup:
-
-    if (hLab) cmsCloseProfile(hLab);
-    if (hXYZ) cmsCloseProfile(hXYZ);
-    return NULL;
+    return cmsCreateExtendedTransform(ContextID, nProfiles, hProfiles, BPC, Intents, AdaptationStates, NULL, 0, InputFormat, OutputFormat, dwFlags);
 }
 
 
 
-double LCMSEXPORT cmsSetAdaptationState(double d)
+cmsHTRANSFORM CMSEXPORT cmsCreateMultiprofileTransform(cmsHPROFILE hProfiles[],
+                                                  cmsUInt32Number nProfiles,
+                                                  cmsUInt32Number InputFormat,
+                                                  cmsUInt32Number OutputFormat,
+                                                  cmsUInt32Number Intent,
+                                                  cmsUInt32Number dwFlags)
 {
-    double OldVal = GlobalAdaptationState;
+
+    if (nProfiles <= 0 || nProfiles > 255) {
+         cmsSignalError(NULL, cmsERROR_RANGE, "Wrong number of profiles. 1..255 expected, %d found.", nProfiles);
+         return NULL;
+    }
+
+    return cmsCreateMultiprofileTransformTHR(cmsGetProfileContextID(hProfiles[0]),
+                                                  hProfiles,
+                                                  nProfiles,
+                                                  InputFormat,
+                                                  OutputFormat,
+                                                  Intent,
+                                                  dwFlags);
+}
+
+cmsHTRANSFORM CMSEXPORT cmsCreateTransformTHR(cmsContext ContextID,
+                                              cmsHPROFILE Input,
+                                              cmsUInt32Number InputFormat,
+                                              cmsHPROFILE Output,
+                                              cmsUInt32Number OutputFormat,
+                                              cmsUInt32Number Intent,
+                                              cmsUInt32Number dwFlags)
+{
+
+    cmsHPROFILE hArray[2];
+
+    hArray[0] = Input;
+    hArray[1] = Output;
+
+    return cmsCreateMultiprofileTransformTHR(ContextID, hArray, Output == NULL ? 1 : 2, InputFormat, OutputFormat, Intent, dwFlags);
+}
 
-    if (d >= 0)
-            GlobalAdaptationState = d;
+CMSAPI cmsHTRANSFORM CMSEXPORT cmsCreateTransform(cmsHPROFILE Input,
+                                                  cmsUInt32Number InputFormat,
+                                                  cmsHPROFILE Output,
+                                                  cmsUInt32Number OutputFormat,
+                                                  cmsUInt32Number Intent,
+                                                  cmsUInt32Number dwFlags)
+{
+    return cmsCreateTransformTHR(cmsGetProfileContextID(Input), Input, InputFormat, Output, OutputFormat, Intent, dwFlags);
+}
+
 
-    return OldVal;
+cmsHTRANSFORM CMSEXPORT cmsCreateProofingTransformTHR(cmsContext ContextID,
+                                                   cmsHPROFILE InputProfile,
+                                                   cmsUInt32Number InputFormat,
+                                                   cmsHPROFILE OutputProfile,
+                                                   cmsUInt32Number OutputFormat,
+                                                   cmsHPROFILE ProofingProfile,
+                                                   cmsUInt32Number nIntent,
+                                                   cmsUInt32Number ProofingIntent,
+                                                   cmsUInt32Number dwFlags)
+{
+    cmsHPROFILE hArray[4];
+    cmsUInt32Number Intents[4];
+    cmsBool  BPC[4];
+    cmsFloat64Number Adaptation[4];
+    cmsBool  DoBPC = (dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION) ? TRUE : FALSE;
+
+
+    hArray[0]  = InputProfile; hArray[1] = ProofingProfile; hArray[2]  = ProofingProfile;               hArray[3] = OutputProfile;
+    Intents[0] = nIntent;      Intents[1] = nIntent;        Intents[2] = INTENT_RELATIVE_COLORIMETRIC;  Intents[3] = ProofingIntent;
+    BPC[0]     = DoBPC;        BPC[1] = DoBPC;              BPC[2] = 0;                                 BPC[3] = 0;
+
+    Adaptation[0] = Adaptation[1] = Adaptation[2] = Adaptation[3] = GlobalAdaptationState;
+
+    if (!(dwFlags & (cmsFLAGS_SOFTPROOFING|cmsFLAGS_GAMUTCHECK)))
+        return cmsCreateTransformTHR(ContextID, InputProfile, InputFormat, OutputProfile, OutputFormat, nIntent, dwFlags);
+
+    return cmsCreateExtendedTransform(ContextID, 4, hArray, BPC, Intents, Adaptation,
+                                        ProofingProfile, 1, InputFormat, OutputFormat, dwFlags);
 
 }
+
+
+cmsHTRANSFORM CMSEXPORT cmsCreateProofingTransform(cmsHPROFILE InputProfile,
+                                                   cmsUInt32Number InputFormat,
+                                                   cmsHPROFILE OutputProfile,
+                                                   cmsUInt32Number OutputFormat,
+                                                   cmsHPROFILE ProofingProfile,
+                                                   cmsUInt32Number nIntent,
+                                                   cmsUInt32Number ProofingIntent,
+                                                   cmsUInt32Number dwFlags)
+{
+    return cmsCreateProofingTransformTHR(cmsGetProfileContextID(InputProfile),
+                                                   InputProfile,
+                                                   InputFormat,
+                                                   OutputProfile,
+                                                   OutputFormat,
+                                                   ProofingProfile,
+                                                   nIntent,
+                                                   ProofingIntent,
+                                                   dwFlags);
+}
+
+
+// Grab the ContextID from an open transform. Returns NULL if a NULL transform is passed
+cmsContext CMSEXPORT cmsGetTransformContextID(cmsHTRANSFORM hTransform)
+{
+    _cmsTRANSFORM* xform = (_cmsTRANSFORM*) hTransform;
+
+    if (xform == NULL) return NULL;
+    return xform -> ContextID;
+}
--- a/src/share/native/sun/java2d/cmm/lcms/icc34.h	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1023 +0,0 @@
-/*
- * Copyright (c) 2007, Oracle and/or its affiliates. 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/* Header file guard bands */
-#ifndef ICC_H
-#define ICC_H
-
-/*
- * This version of the header file corresponds to the profile
- * specification version 3.4.
- *
- * All header file entries are pre-fixed with "ic" to help
- * avoid name space collisions. Signatures are pre-fixed with
- * icSig.
- *
- * The structures defined in this header file were created to
- * represent a description of an ICC profile on disk. Rather
- * than use pointers a technique is used where a single byte array
- * was placed at the end of each structure. This allows us in "C"
- * to extend the structure by allocating more data than is needed
- * to account for variable length structures.
- *
- * This also ensures that data following is allocated
- * contiguously and makes it easier to write and read data from
- * the file.
- *
- * For example to allocate space for a 256 count length UCR
- * and BG array, and fill the allocated data.  Note strlen + 1
- * to remember NULL terminator.
- *
-        icUcrBgCurve    *ucrCurve, *bgCurve;
-        int             ucr_nbytes, bg_nbytes, string_bytes;
-        icUcrBg         *ucrBgWrite;
-        char            ucr_string[100], *ucr_char;
-
-        strcpy(ucr_string, "Example ucrBG curves");
-        ucr_nbytes = sizeof(icUInt32Number) +
-                 (UCR_CURVE_SIZE * sizeof(icUInt16Number));
-        bg_nbytes = sizeof(icUInt32Number) +
-                 (BG_CURVE_SIZE * sizeof(icUInt16Number));
-        string_bytes = strlen(ucr_string) + 1;
-
-        ucrBgWrite = (icUcrBg *)malloc(
-                                (ucr_nbytes + bg_nbytes + string_bytes));
-
-        ucrCurve = (icUcrBgCurve *)ucrBgWrite->data;
-        ucrCurve->count = UCR_CURVE_SIZE;
-        for (i=0; i<ucrCurve->count; i++)
-                ucrCurve->curve[i] = (icUInt16Number)i;
-
-        bgCurve = (icUcrBgCurve *)((char *)ucrCurve + ucr_nbytes);
-        bgCurve->count = BG_CURVE_SIZE;
-        for (i=0; i<bgCurve->count; i++)
-                bgCurve->curve[i] = 255 - (icUInt16Number)i;
-
-        ucr_char = (char *)((char *)bgCurve + bg_nbytes);
-        memcpy(ucr_char, ucr_string, string_bytes);
- *
- */
-
-/*
- * Many of the structures contain variable length arrays. This
- * is represented by the use of the convention.
- *
- *      type    data[icAny];
- */
-
-/*------------------------------------------------------------------------*/
-/*
- * Defines used in the specification
- */
-#define icMagicNumber                   0x61637370L     /* 'acsp' */
-#define icVersionNumber                 0x02100000L     /* 2.1.0, BCD */
-
-/* Screening Encodings */
-#define icPrtrDefaultScreensFalse       0x00000000L     /* Bit pos 0 */
-#define icPrtrDefaultScreensTrue        0x00000001L     /* Bit pos 0 */
-#define icLinesPerInch                  0x00000002L     /* Bit pos 1 */
-#define icLinesPerCm                    0x00000000L     /* Bit pos 1 */
-
-/*
- * Device attributes, currently defined values correspond
- * to the low 4 bytes of the 8 byte attribute quantity, see
- * the header for their location.
- */
-#define icReflective                    0x00000000L     /* Bit pos 0 */
-#define icTransparency                  0x00000001L     /* Bit pos 0 */
-#define icGlossy                        0x00000000L     /* Bit pos 1 */
-#define icMatte                         0x00000002L     /* Bit pos 1 */
-
-/*
- * Profile header flags, the low 16 bits are reserved for consortium
- * use.
- */
-#define icEmbeddedProfileFalse          0x00000000L     /* Bit pos 0 */
-#define icEmbeddedProfileTrue           0x00000001L     /* Bit pos 0 */
-#define icUseAnywhere                   0x00000000L     /* Bit pos 1 */
-#define icUseWithEmbeddedDataOnly       0x00000002L     /* Bit pos 1 */
-
-/* Ascii or Binary data */
-#define icAsciiData                     0x00000000L
-#define icBinaryData                    0x00000001L
-
-/*
- * Define used to indicate that this is a variable length array
- */
-#define icAny                           1
-
-
-/*------------------------------------------------------------------------*/
-/*
- * Use this area to translate platform definitions of long
- * etc into icXXX form. The rest of the header uses the icXXX
- * typedefs. Signatures are 4 byte quantities.
- *
- */
-
-
-#ifdef PACKAGE_NAME
-/*
-  June 9, 2003, Adapted for use with configure by Bob Friesenhahn
-  Added the stupid check for autoconf by Marti Maria.
-  PACKAGE_NAME is defined if autoconf is being used
-*/
-
-typedef @UINT8_T@       icUInt8Number;
-typedef @UINT16_T@      icUInt16Number;
-typedef @UINT32_T@      icUInt32Number;
-typedef @UINT32_T@      icUInt64Number[2];
-
-typedef @INT8_T@        icInt8Number;
-typedef @INT16_T@       icInt16Number;
-typedef @INT32_T@       icInt32Number;
-typedef @INT32_T@       icInt64Number[2];
-
-#else
-
-/*
- *Apr-17-2002: Modified by Marti Maria in order to provide wider portability.
- */
-
-#if defined (__digital__) && defined (__unix__)
-
-/* Tru64 */
-
-#include <inttypes.h>
-
-typedef uint8_t   icUInt8Number;
-typedef uint16_t  icUInt16Number;
-typedef uint32_t  icUInt32Number;
-typedef uint32_t  icUInt64Number[2];
-
-typedef int8_t     icInt8Number;
-typedef int16_t    icInt16Number;
-typedef int32_t    icInt32Number;
-typedef int32_t    icInt64Number[2];
-
-#else
-#ifdef __sgi
-#include "sgidefs.h"
-
-
-/*
- * Number definitions
- */
-
-/* Unsigned integer numbers */
-typedef unsigned char   icUInt8Number;
-typedef unsigned short  icUInt16Number;
-typedef __uint32_t      icUInt32Number;
-typedef __uint32_t      icUInt64Number[2];
-
-/* Signed numbers */
-typedef char            icInt8Number;
-typedef short           icInt16Number;
-typedef __int32_t       icInt32Number;
-typedef __int32_t       icInt64Number[2];
-
-
-#else
-#if defined(__GNUC__) || defined(__unix__) || defined(__unix)
-
-#include <sys/types.h>
-
-#if defined(__sun) || defined(__hpux) || defined (__MINGW) || defined(__MINGW32__)
-
-#if defined (__MINGW) || defined(__MINGW32__)
-#include <stdint.h>
-#endif
-
-
-typedef uint8_t   icUInt8Number;
-typedef uint16_t  icUInt16Number;
-typedef uint32_t  icUInt32Number;
-typedef uint32_t  icUInt64Number[2];
-
-#else
-
-/* Unsigned integer numbers */
-typedef u_int8_t   icUInt8Number;
-typedef u_int16_t  icUInt16Number;
-typedef u_int32_t  icUInt32Number;
-typedef u_int32_t  icUInt64Number[2];
-
-#endif
-
-
-/* Signed numbers */
-typedef int8_t     icInt8Number;
-typedef int16_t    icInt16Number;
-typedef int32_t    icInt32Number;
-typedef int32_t    icInt64Number[2];
-
-
-#else /* default definitions */
-
-/*
- * Number definitions
- */
-
-/* Unsigned integer numbers */
-typedef unsigned char   icUInt8Number;
-typedef unsigned short  icUInt16Number;
-typedef unsigned long   icUInt32Number;
-typedef unsigned long   icUInt64Number[2];
-
-/* Signed numbers */
-typedef char            icInt8Number;
-typedef short           icInt16Number;
-typedef long            icInt32Number;
-typedef long            icInt64Number[2];
-
-
-#endif  /* default defs */
-#endif
-#endif
-#endif
-
-/* Base types */
-
-typedef icInt32Number    icSignature;
-typedef icInt32Number    icS15Fixed16Number;
-typedef icUInt32Number   icU16Fixed16Number;
-
-
-/*------------------------------------------------------------------------*/
-/* public tags and sizes */
-typedef enum {
-    icSigAToB0Tag                       = 0x41324230L,  /* 'A2B0' */
-    icSigAToB1Tag                       = 0x41324231L,  /* 'A2B1' */
-    icSigAToB2Tag                       = 0x41324232L,  /* 'A2B2' */
-    icSigBlueColorantTag                = 0x6258595AL,  /* 'bXYZ' */
-    icSigBlueTRCTag                     = 0x62545243L,  /* 'bTRC' */
-    icSigBToA0Tag                       = 0x42324130L,  /* 'B2A0' */
-    icSigBToA1Tag                       = 0x42324131L,  /* 'B2A1' */
-    icSigBToA2Tag                       = 0x42324132L,  /* 'B2A2' */
-    icSigCalibrationDateTimeTag         = 0x63616C74L,  /* 'calt' */
-    icSigCharTargetTag                  = 0x74617267L,  /* 'targ' */
-    icSigCopyrightTag                   = 0x63707274L,  /* 'cprt' */
-    icSigCrdInfoTag                     = 0x63726469L,  /* 'crdi' */
-    icSigDeviceMfgDescTag               = 0x646D6E64L,  /* 'dmnd' */
-    icSigDeviceModelDescTag             = 0x646D6464L,  /* 'dmdd' */
-    icSigGamutTag                       = 0x67616D74L,  /* 'gamt ' */
-    icSigGrayTRCTag                     = 0x6b545243L,  /* 'kTRC' */
-    icSigGreenColorantTag               = 0x6758595AL,  /* 'gXYZ' */
-    icSigGreenTRCTag                    = 0x67545243L,  /* 'gTRC' */
-    icSigLuminanceTag                   = 0x6C756d69L,  /* 'lumi' */
-    icSigMeasurementTag                 = 0x6D656173L,  /* 'meas' */
-    icSigMediaBlackPointTag             = 0x626B7074L,  /* 'bkpt' */
-    icSigMediaWhitePointTag             = 0x77747074L,  /* 'wtpt' */
-    icSigNamedColorTag                  = 0x6E636f6CL,  /* 'ncol'
-                                                         * OBSOLETE, use ncl2 */
-    icSigNamedColor2Tag                 = 0x6E636C32L,  /* 'ncl2' */
-    icSigPreview0Tag                    = 0x70726530L,  /* 'pre0' */
-    icSigPreview1Tag                    = 0x70726531L,  /* 'pre1' */
-    icSigPreview2Tag                    = 0x70726532L,  /* 'pre2' */
-    icSigProfileDescriptionTag          = 0x64657363L,  /* 'desc' */
-    icSigProfileSequenceDescTag         = 0x70736571L,  /* 'pseq' */
-    icSigPs2CRD0Tag                     = 0x70736430L,  /* 'psd0' */
-    icSigPs2CRD1Tag                     = 0x70736431L,  /* 'psd1' */
-    icSigPs2CRD2Tag                     = 0x70736432L,  /* 'psd2' */
-    icSigPs2CRD3Tag                     = 0x70736433L,  /* 'psd3' */
-    icSigPs2CSATag                      = 0x70733273L,  /* 'ps2s' */
-    icSigPs2RenderingIntentTag          = 0x70733269L,  /* 'ps2i' */
-    icSigRedColorantTag                 = 0x7258595AL,  /* 'rXYZ' */
-    icSigRedTRCTag                      = 0x72545243L,  /* 'rTRC' */
-    icSigScreeningDescTag               = 0x73637264L,  /* 'scrd' */
-    icSigScreeningTag                   = 0x7363726EL,  /* 'scrn' */
-    icSigTechnologyTag                  = 0x74656368L,  /* 'tech' */
-    icSigUcrBgTag                       = 0x62666420L,  /* 'bfd ' */
-    icSigViewingCondDescTag             = 0x76756564L,  /* 'vued' */
-    icSigViewingConditionsTag           = 0x76696577L,  /* 'view' */
-    icMaxEnumTag                        = 0xFFFFFFFFL
-} icTagSignature;
-
-/* technology signature descriptions */
-typedef enum {
-    icSigDigitalCamera                  = 0x6463616DL,  /* 'dcam' */
-    icSigFilmScanner                    = 0x6673636EL,  /* 'fscn' */
-    icSigReflectiveScanner              = 0x7273636EL,  /* 'rscn' */
-    icSigInkJetPrinter                  = 0x696A6574L,  /* 'ijet' */
-    icSigThermalWaxPrinter              = 0x74776178L,  /* 'twax' */
-    icSigElectrophotographicPrinter     = 0x6570686FL,  /* 'epho' */
-    icSigElectrostaticPrinter           = 0x65737461L,  /* 'esta' */
-    icSigDyeSublimationPrinter          = 0x64737562L,  /* 'dsub' */
-    icSigPhotographicPaperPrinter       = 0x7270686FL,  /* 'rpho' */
-    icSigFilmWriter                     = 0x6670726EL,  /* 'fprn' */
-    icSigVideoMonitor                   = 0x7669646DL,  /* 'vidm' */
-    icSigVideoCamera                    = 0x76696463L,  /* 'vidc' */
-    icSigProjectionTelevision           = 0x706A7476L,  /* 'pjtv' */
-    icSigCRTDisplay                     = 0x43525420L,  /* 'CRT ' */
-    icSigPMDisplay                      = 0x504D4420L,  /* 'PMD ' */
-    icSigAMDisplay                      = 0x414D4420L,  /* 'AMD ' */
-    icSigPhotoCD                        = 0x4B504344L,  /* 'KPCD' */
-    icSigPhotoImageSetter               = 0x696D6773L,  /* 'imgs' */
-    icSigGravure                        = 0x67726176L,  /* 'grav' */
-    icSigOffsetLithography              = 0x6F666673L,  /* 'offs' */
-    icSigSilkscreen                     = 0x73696C6BL,  /* 'silk' */
-    icSigFlexography                    = 0x666C6578L,  /* 'flex' */
-    icMaxEnumTechnology                 = 0xFFFFFFFFL
-} icTechnologySignature;
-
-/* type signatures */
-typedef enum {
-    icSigCurveType                      = 0x63757276L,  /* 'curv' */
-    icSigDataType                       = 0x64617461L,  /* 'data' */
-    icSigDateTimeType                   = 0x6474696DL,  /* 'dtim' */
-    icSigLut16Type                      = 0x6d667432L,  /* 'mft2' */
-    icSigLut8Type                       = 0x6d667431L,  /* 'mft1' */
-    icSigMeasurementType                = 0x6D656173L,  /* 'meas' */
-    icSigNamedColorType                 = 0x6E636f6CL,  /* 'ncol'
-                                                         * OBSOLETE, use ncl2 */
-    icSigProfileSequenceDescType        = 0x70736571L,  /* 'pseq' */
-    icSigS15Fixed16ArrayType            = 0x73663332L,  /* 'sf32' */
-    icSigScreeningType                  = 0x7363726EL,  /* 'scrn' */
-    icSigSignatureType                  = 0x73696720L,  /* 'sig ' */
-    icSigTextType                       = 0x74657874L,  /* 'text' */
-    icSigTextDescriptionType            = 0x64657363L,  /* 'desc' */
-    icSigU16Fixed16ArrayType            = 0x75663332L,  /* 'uf32' */
-    icSigUcrBgType                      = 0x62666420L,  /* 'bfd ' */
-    icSigUInt16ArrayType                = 0x75693136L,  /* 'ui16' */
-    icSigUInt32ArrayType                = 0x75693332L,  /* 'ui32' */
-    icSigUInt64ArrayType                = 0x75693634L,  /* 'ui64' */
-    icSigUInt8ArrayType                 = 0x75693038L,  /* 'ui08' */
-    icSigViewingConditionsType          = 0x76696577L,  /* 'view' */
-    icSigXYZType                        = 0x58595A20L,  /* 'XYZ ' */
-    icSigXYZArrayType                   = 0x58595A20L,  /* 'XYZ ' */
-    icSigNamedColor2Type                = 0x6E636C32L,  /* 'ncl2' */
-    icSigCrdInfoType                    = 0x63726469L,  /* 'crdi' */
-    icMaxEnumType                       = 0xFFFFFFFFL
-} icTagTypeSignature;
-
-/*
- * Color Space Signatures
- * Note that only icSigXYZData and icSigLabData are valid
- * Profile Connection Spaces (PCSs)
- */
-typedef enum {
-    icSigXYZData                        = 0x58595A20L,  /* 'XYZ ' */
-    icSigLabData                        = 0x4C616220L,  /* 'Lab ' */
-    icSigLuvData                        = 0x4C757620L,  /* 'Luv ' */
-    icSigYCbCrData                      = 0x59436272L,  /* 'YCbr' */
-    icSigYxyData                        = 0x59787920L,  /* 'Yxy ' */
-    icSigRgbData                        = 0x52474220L,  /* 'RGB ' */
-    icSigGrayData                       = 0x47524159L,  /* 'GRAY' */
-    icSigHsvData                        = 0x48535620L,  /* 'HSV ' */
-    icSigHlsData                        = 0x484C5320L,  /* 'HLS ' */
-    icSigCmykData                       = 0x434D594BL,  /* 'CMYK' */
-    icSigCmyData                        = 0x434D5920L,  /* 'CMY ' */
-    icSig2colorData                     = 0x32434C52L,  /* '2CLR' */
-    icSig3colorData                     = 0x33434C52L,  /* '3CLR' */
-    icSig4colorData                     = 0x34434C52L,  /* '4CLR' */
-    icSig5colorData                     = 0x35434C52L,  /* '5CLR' */
-    icSig6colorData                     = 0x36434C52L,  /* '6CLR' */
-    icSig7colorData                     = 0x37434C52L,  /* '7CLR' */
-    icSig8colorData                     = 0x38434C52L,  /* '8CLR' */
-    icSig9colorData                     = 0x39434C52L,  /* '9CLR' */
-    icSig10colorData                    = 0x41434C52L,  /* 'ACLR' */
-    icSig11colorData                    = 0x42434C52L,  /* 'BCLR' */
-    icSig12colorData                    = 0x43434C52L,  /* 'CCLR' */
-    icSig13colorData                    = 0x44434C52L,  /* 'DCLR' */
-    icSig14colorData                    = 0x45434C52L,  /* 'ECLR' */
-    icSig15colorData                    = 0x46434C52L,  /* 'FCLR' */
-    icMaxEnumData                       = 0xFFFFFFFFL
-} icColorSpaceSignature;
-
-/* profileClass enumerations */
-typedef enum {
-    icSigInputClass                     = 0x73636E72L,  /* 'scnr' */
-    icSigDisplayClass                   = 0x6D6E7472L,  /* 'mntr' */
-    icSigOutputClass                    = 0x70727472L,  /* 'prtr' */
-    icSigLinkClass                      = 0x6C696E6BL,  /* 'link' */
-    icSigAbstractClass                  = 0x61627374L,  /* 'abst' */
-    icSigColorSpaceClass                = 0x73706163L,  /* 'spac' */
-    icSigNamedColorClass                = 0x6e6d636cL,  /* 'nmcl' */
-    icMaxEnumClass                      = 0xFFFFFFFFL
-} icProfileClassSignature;
-
-/* Platform Signatures */
-typedef enum {
-    icSigMacintosh                      = 0x4150504CL,  /* 'APPL' */
-    icSigMicrosoft                      = 0x4D534654L,  /* 'MSFT' */
-    icSigSolaris                        = 0x53554E57L,  /* 'SUNW' */
-    icSigSGI                            = 0x53474920L,  /* 'SGI ' */
-    icSigTaligent                       = 0x54474E54L,  /* 'TGNT' */
-    icMaxEnumPlatform                   = 0xFFFFFFFFL
-} icPlatformSignature;
-
-/*------------------------------------------------------------------------*/
-/*
- * Other enums
- */
-
-/* Measurement Flare, used in the measurmentType tag */
-typedef enum {
-    icFlare0                            = 0x00000000L,  /* 0% flare */
-    icFlare100                          = 0x00000001L,  /* 100% flare */
-    icMaxFlare                          = 0xFFFFFFFFL
-} icMeasurementFlare;
-
-/* Measurement Geometry, used in the measurmentType tag */
-typedef enum {
-    icGeometryUnknown                   = 0x00000000L,  /* Unknown */
-    icGeometry045or450                  = 0x00000001L,  /* 0/45, 45/0 */
-    icGeometry0dord0                    = 0x00000002L,  /* 0/d or d/0 */
-    icMaxGeometry                       = 0xFFFFFFFFL
-} icMeasurementGeometry;
-
-/* Rendering Intents, used in the profile header */
-typedef enum {
-    icPerceptual                        = 0,
-    icRelativeColorimetric              = 1,
-    icSaturation                        = 2,
-    icAbsoluteColorimetric              = 3,
-    icMaxEnumIntent                     = 0xFFFFFFFFL
-} icRenderingIntent;
-
-/* Different Spot Shapes currently defined, used for screeningType */
-typedef enum {
-    icSpotShapeUnknown                  = 0,
-    icSpotShapePrinterDefault           = 1,
-    icSpotShapeRound                    = 2,
-    icSpotShapeDiamond                  = 3,
-    icSpotShapeEllipse                  = 4,
-    icSpotShapeLine                     = 5,
-    icSpotShapeSquare                   = 6,
-    icSpotShapeCross                    = 7,
-    icMaxEnumSpot                       = 0xFFFFFFFFL
-} icSpotShape;
-
-/* Standard Observer, used in the measurmentType tag */
-typedef enum {
-    icStdObsUnknown                     = 0x00000000L,  /* Unknown */
-    icStdObs1931TwoDegrees              = 0x00000001L,  /* 2 deg */
-    icStdObs1964TenDegrees              = 0x00000002L,  /* 10 deg */
-    icMaxStdObs                         = 0xFFFFFFFFL
-} icStandardObserver;
-
-/* Pre-defined illuminants, used in measurement and viewing conditions type */
-typedef enum {
-    icIlluminantUnknown                 = 0x00000000L,
-    icIlluminantD50                     = 0x00000001L,
-    icIlluminantD65                     = 0x00000002L,
-    icIlluminantD93                     = 0x00000003L,
-    icIlluminantF2                      = 0x00000004L,
-    icIlluminantD55                     = 0x00000005L,
-    icIlluminantA                       = 0x00000006L,
-    icIlluminantEquiPowerE              = 0x00000007L,
-    icIlluminantF8                      = 0x00000008L,
-    icMaxEnumIluminant                  = 0xFFFFFFFFL
-} icIlluminant;
-
-
-/*------------------------------------------------------------------------*/
-/*
- * Arrays of numbers
- */
-
-/* Int8 Array */
-typedef struct {
-    icInt8Number        data[icAny];    /* Variable array of values */
-} icInt8Array;
-
-/* UInt8 Array */
-typedef struct {
-    icUInt8Number       data[icAny];    /* Variable array of values */
-} icUInt8Array;
-
-/* uInt16 Array */
-typedef struct {
-    icUInt16Number      data[icAny];    /* Variable array of values */
-} icUInt16Array;
-
-/* Int16 Array */
-typedef struct {
-    icInt16Number       data[icAny];    /* Variable array of values */
-} icInt16Array;
-
-/* uInt32 Array */
-typedef struct {
-    icUInt32Number      data[icAny];    /* Variable array of values */
-} icUInt32Array;
-
-/* Int32 Array */
-typedef struct {
-    icInt32Number       data[icAny];    /* Variable array of values */
-} icInt32Array;
-
-/* UInt64 Array */
-typedef struct {
-    icUInt64Number      data[icAny];    /* Variable array of values */
-} icUInt64Array;
-
-/* Int64 Array */
-typedef struct {
-    icInt64Number       data[icAny];    /* Variable array of values */
-} icInt64Array;
-
-/* u16Fixed16 Array */
-typedef struct {
-    icU16Fixed16Number  data[icAny];    /* Variable array of values */
-} icU16Fixed16Array;
-
-/* s15Fixed16 Array */
-typedef struct {
-    icS15Fixed16Number  data[icAny];    /* Variable array of values */
-} icS15Fixed16Array;
-
-/* The base date time number */
-typedef struct {
-    icUInt16Number      year;
-    icUInt16Number      month;
-    icUInt16Number      day;
-    icUInt16Number      hours;
-    icUInt16Number      minutes;
-    icUInt16Number      seconds;
-} icDateTimeNumber;
-
-/* XYZ Number  */
-typedef struct {
-    icS15Fixed16Number  X;
-    icS15Fixed16Number  Y;
-    icS15Fixed16Number  Z;
-} icXYZNumber;
-
-/* XYZ Array */
-typedef struct {
-    icXYZNumber         data[icAny];    /* Variable array of XYZ numbers */
-} icXYZArray;
-
-/* Curve */
-typedef struct {
-    icUInt32Number      count;          /* Number of entries */
-    icUInt16Number      data[icAny];    /* The actual table data, real
-                                         * number is determined by count
-                                         * Interpretation depends on how
-                                         * data is used with a given tag
-                                         */
-} icCurve;
-
-/* Data */
-typedef struct {
-    icUInt32Number      dataFlag;       /* 0 = ascii, 1 = binary */
-    icInt8Number        data[icAny];    /* Data, size from tag */
-} icData;
-
-/* lut16 */
-typedef struct {
-    icUInt8Number       inputChan;      /* Number of input channels */
-    icUInt8Number       outputChan;     /* Number of output channels */
-    icUInt8Number       clutPoints;     /* Number of grid points */
-    icInt8Number        pad;            /* Padding for byte alignment */
-    icS15Fixed16Number  e00;            /* e00 in the 3 * 3 */
-    icS15Fixed16Number  e01;            /* e01 in the 3 * 3 */
-    icS15Fixed16Number  e02;            /* e02 in the 3 * 3 */
-    icS15Fixed16Number  e10;            /* e10 in the 3 * 3 */
-    icS15Fixed16Number  e11;            /* e11 in the 3 * 3 */
-    icS15Fixed16Number  e12;            /* e12 in the 3 * 3 */
-    icS15Fixed16Number  e20;            /* e20 in the 3 * 3 */
-    icS15Fixed16Number  e21;            /* e21 in the 3 * 3 */
-    icS15Fixed16Number  e22;            /* e22 in the 3 * 3 */
-    icUInt16Number      inputEnt;       /* Num of in-table entries */
-    icUInt16Number      outputEnt;      /* Num of out-table entries */
-    icUInt16Number      data[icAny];    /* Data follows see spec */
-/*
- *  Data that follows is of this form
- *
- *  icUInt16Number      inputTable[inputChan][icAny];   * The in-table
- *  icUInt16Number      clutTable[icAny];               * The clut
- *  icUInt16Number      outputTable[outputChan][icAny]; * The out-table
- */
-} icLut16;
-
-/* lut8, input & output tables are always 256 bytes in length */
-typedef struct {
-    icUInt8Number       inputChan;      /* Num of input channels */
-    icUInt8Number       outputChan;     /* Num of output channels */
-    icUInt8Number       clutPoints;     /* Num of grid points */
-    icInt8Number        pad;
-    icS15Fixed16Number  e00;            /* e00 in the 3 * 3 */
-    icS15Fixed16Number  e01;            /* e01 in the 3 * 3 */
-    icS15Fixed16Number  e02;            /* e02 in the 3 * 3 */
-    icS15Fixed16Number  e10;            /* e10 in the 3 * 3 */
-    icS15Fixed16Number  e11;            /* e11 in the 3 * 3 */
-    icS15Fixed16Number  e12;            /* e12 in the 3 * 3 */
-    icS15Fixed16Number  e20;            /* e20 in the 3 * 3 */
-    icS15Fixed16Number  e21;            /* e21 in the 3 * 3 */
-    icS15Fixed16Number  e22;            /* e22 in the 3 * 3 */
-    icUInt8Number       data[icAny];    /* Data follows see spec */
-/*
- *  Data that follows is of this form
- *
- *  icUInt8Number       inputTable[inputChan][256];     * The in-table
- *  icUInt8Number       clutTable[icAny];               * The clut
- *  icUInt8Number       outputTable[outputChan][256];   * The out-table
- */
-} icLut8;
-
-/* Measurement Data */
-typedef struct {
-    icStandardObserver          stdObserver;    /* Standard observer */
-    icXYZNumber                 backing;        /* XYZ for backing */
-    icMeasurementGeometry       geometry;       /* Meas. geometry */
-    icMeasurementFlare          flare;          /* Measurement flare */
-    icIlluminant                illuminant;     /* Illuminant */
-} icMeasurement;
-
-/* Named color */
-
-/*
- * icNamedColor2 takes the place of icNamedColor
- */
-typedef struct {
-    icUInt32Number      vendorFlag;     /* Bottom 16 bits for IC use */
-    icUInt32Number      count;          /* Count of named colors */
-    icUInt32Number      nDeviceCoords;  /* Num of device coordinates */
-    icInt8Number        prefix[32];     /* Prefix for each color name */
-    icInt8Number        suffix[32];     /* Suffix for each color name */
-    icInt8Number        data[icAny];    /* Named color data follows */
-/*
- *  Data that follows is of this form
- *
- * icInt8Number         root1[32];              * Root name for 1st color
- * icUInt16Number       pcsCoords1[icAny];      * PCS coords of 1st color
- * icUInt16Number       deviceCoords1[icAny];   * Dev coords of 1st color
- * icInt8Number         root2[32];              * Root name for 2nd color
- * icUInt16Number       pcsCoords2[icAny];      * PCS coords of 2nd color
- * icUInt16Number       deviceCoords2[icAny];   * Dev coords of 2nd color
- *                      :
- *                      :
- * Repeat for name and PCS and device color coordinates up to (count-1)
- *
- * NOTES:
- * PCS and device space can be determined from the header.
- *
- * PCS coordinates are icUInt16 numbers and are described in Annex A of
- * the ICC spec. Only 16 bit L*a*b* and XYZ are allowed. The number of
- * coordinates is consistent with the headers PCS.
- *
- * Device coordinates are icUInt16 numbers where 0x0000 represents
- * the minimum value and 0xFFFF represents the maximum value.
- * If the nDeviceCoords value is 0 this field is not given.
- */
-} icNamedColor2;
-
-/* Profile sequence structure */
-typedef struct {
-    icSignature                 deviceMfg;      /* Dev Manufacturer */
-    icSignature                 deviceModel;    /* Dev Model */
-    icUInt64Number              attributes;     /* Dev attributes */
-    icTechnologySignature       technology;     /* Technology sig */
-    icInt8Number                data[icAny];    /* Desc text follows */
-/*
- *  Data that follows is of this form, this is an icInt8Number
- *  to avoid problems with a compiler generating  bad code as
- *  these arrays are variable in length.
- *
- * icTextDescription            deviceMfgDesc;  * Manufacturer text
- * icTextDescription            modelDesc;      * Model text
- */
-} icDescStruct;
-
-/* Profile sequence description */
-typedef struct {
-    icUInt32Number      count;          /* Number of descriptions */
-    icUInt8Number       data[icAny];    /* Array of desc structs */
-} icProfileSequenceDesc;
-
-/* textDescription */
-typedef struct {
-    icUInt32Number      count;          /* Description length */
-    icInt8Number        data[icAny];    /* Descriptions follow */
-/*
- *  Data that follows is of this form
- *
- * icInt8Number         desc[count]     * NULL terminated ascii string
- * icUInt32Number       ucLangCode;     * UniCode language code
- * icUInt32Number       ucCount;        * UniCode description length
- * icInt16Number        ucDesc[ucCount];* The UniCode description
- * icUInt16Number       scCode;         * ScriptCode code
- * icUInt8Number        scCount;        * ScriptCode count
- * icInt8Number         scDesc[67];     * ScriptCode Description
- */
-} icTextDescription;
-
-/* Screening Data */
-typedef struct {
-    icS15Fixed16Number  frequency;      /* Frequency */
-    icS15Fixed16Number  angle;          /* Screen angle */
-    icSpotShape         spotShape;      /* Spot Shape encodings below */
-} icScreeningData;
-
-typedef struct {
-    icUInt32Number      screeningFlag;  /* Screening flag */
-    icUInt32Number      channels;       /* Number of channels */
-    icScreeningData     data[icAny];    /* Array of screening data */
-} icScreening;
-
-/* Text Data */
-typedef struct {
-    icInt8Number        data[icAny];    /* Variable array of chars */
-} icText;
-
-/* Structure describing either a UCR or BG curve */
-typedef struct {
-    icUInt32Number      count;          /* Curve length */
-    icUInt16Number      curve[icAny];   /* The array of curve values */
-} icUcrBgCurve;
-
-/* Under color removal, black generation */
-typedef struct {
-    icInt8Number        data[icAny];            /* The Ucr BG data */
-/*
- *  Data that follows is of this form, this is a icInt8Number
- *  to avoid problems with a compiler generating  bad code as
- *  these arrays are variable in length.
- *
- * icUcrBgCurve         ucr;            * Ucr curve
- * icUcrBgCurve         bg;             * Bg curve
- * icInt8Number         string;         * UcrBg description
- */
-} icUcrBg;
-
-/* viewingConditionsType */
-typedef struct {
-    icXYZNumber         illuminant;     /* In candelas per sq. meter */
-    icXYZNumber         surround;       /* In candelas per sq. meter */
-    icIlluminant        stdIluminant;   /* See icIlluminant defines */
-} icViewingCondition;
-
-/* CrdInfo type */
-typedef struct {
-    icUInt32Number      count;          /* Char count includes NULL */
-    icInt8Number        desc[icAny];    /* Null terminated string */
-} icCrdInfo;
-
-/*------------------------------------------------------------------------*/
-/*
- * Tag Type definitions
- */
-
-/*
- * Many of the structures contain variable length arrays. This
- * is represented by the use of the convention.
- *
- *      type    data[icAny];
- */
-
-/* The base part of each tag */
-typedef struct {
-    icTagTypeSignature  sig;            /* Signature */
-    icInt8Number        reserved[4];    /* Reserved, set to 0 */
-} icTagBase;
-
-/* curveType */
-typedef struct {
-    icTagBase           base;           /* Signature, "curv" */
-    icCurve             curve;          /* The curve data */
-} icCurveType;
-
-/* dataType */
-typedef struct {
-    icTagBase           base;           /* Signature, "data" */
-    icData              data;           /* The data structure */
-} icDataType;
-
-/* dateTimeType */
-typedef struct {
-    icTagBase           base;           /* Signature, "dtim" */
-    icDateTimeNumber    date;           /* The date */
-} icDateTimeType;
-
-/* lut16Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "mft2" */
-    icLut16             lut;            /* Lut16 data */
-} icLut16Type;
-
-/* lut8Type, input & output tables are always 256 bytes in length */
-typedef struct {
-    icTagBase           base;           /* Signature, "mft1" */
-    icLut8              lut;            /* Lut8 data */
-} icLut8Type;
-
-/* Measurement Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "meas" */
-    icMeasurement       measurement;    /* Measurement data */
-} icMeasurementType;
-
-/* Named color type */
-/* icNamedColor2Type, replaces icNamedColorType */
-typedef struct {
-    icTagBase           base;           /* Signature, "ncl2" */
-    icNamedColor2       ncolor;         /* Named color data */
-} icNamedColor2Type;
-
-/* Profile sequence description type */
-typedef struct {
-    icTagBase                   base;   /* Signature, "pseq" */
-    icProfileSequenceDesc       desc;   /* The seq description */
-} icProfileSequenceDescType;
-
-/* textDescriptionType */
-typedef struct {
-    icTagBase                   base;   /* Signature, "desc" */
-    icTextDescription           desc;   /* The description */
-} icTextDescriptionType;
-
-/* s15Fixed16Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "sf32" */
-    icS15Fixed16Array   data;           /* Array of values */
-} icS15Fixed16ArrayType;
-
-typedef struct {
-    icTagBase           base;           /* Signature, "scrn" */
-    icScreening         screen;         /* Screening structure */
-} icScreeningType;
-
-/* sigType */
-typedef struct {
-    icTagBase           base;           /* Signature, "sig" */
-    icSignature         signature;      /* The signature data */
-} icSignatureType;
-
-/* textType */
-typedef struct {
-    icTagBase           base;           /* Signature, "text" */
-    icText              data;           /* Variable array of chars */
-} icTextType;
-
-/* u16Fixed16Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "uf32" */
-    icU16Fixed16Array   data;           /* Variable array of values */
-} icU16Fixed16ArrayType;
-
-/* Under color removal, black generation type */
-typedef struct {
-    icTagBase           base;           /* Signature, "bfd " */
-    icUcrBg             data;           /* ucrBg structure */
-} icUcrBgType;
-
-/* uInt16Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "ui16" */
-    icUInt16Array       data;           /* Variable array of values */
-} icUInt16ArrayType;
-
-/* uInt32Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "ui32" */
-    icUInt32Array       data;           /* Variable array of values */
-} icUInt32ArrayType;
-
-/* uInt64Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "ui64" */
-    icUInt64Array       data;           /* Variable array of values */
-} icUInt64ArrayType;
-
-/* uInt8Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "ui08" */
-    icUInt8Array        data;           /* Variable array of values */
-} icUInt8ArrayType;
-
-/* viewingConditionsType */
-typedef struct {
-    icTagBase           base;           /* Signature, "view" */
-    icViewingCondition  view;           /* Viewing conditions */
-} icViewingConditionType;
-
-/* XYZ Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "XYZ" */
-    icXYZArray          data;           /* Variable array of XYZ nums */
-} icXYZType;
-
-/* CRDInfoType where [0] is the CRD product name count and string and
- * [1] -[5] are the rendering intents 0-4 counts and strings
- */
-typedef struct {
-    icTagBase           base;           /* Signature, "crdi" */
-    icCrdInfo           info;           /* 5 sets of counts & strings */
-}icCrdInfoType;
-     /*   icCrdInfo       productName;     PS product count/string */
-     /*   icCrdInfo       CRDName0;        CRD name for intent 0 */
-     /*   icCrdInfo       CRDName1;        CRD name for intent 1 */
-     /*   icCrdInfo       CRDName2;        CRD name for intent 2 */
-     /*   icCrdInfo       CRDName3;        CRD name for intent 3 */
-
-/*------------------------------------------------------------------------*/
-
-/*
- * Lists of tags, tags, profile header and profile structure
- */
-
-/* A tag */
-typedef struct {
-    icTagSignature      sig;            /* The tag signature */
-    icUInt32Number      offset;         /* Start of tag relative to
-                                         * start of header, Spec
-                                         * Clause 5 */
-    icUInt32Number      size;           /* Size in bytes */
-} icTag;
-
-/* A Structure that may be used independently for a list of tags */
-typedef struct {
-    icUInt32Number      count;          /* Num tags in the profile */
-    icTag               tags[icAny];    /* Variable array of tags */
-} icTagList;
-
-/* The Profile header */
-typedef struct {
-    icUInt32Number              size;           /* Prof size in bytes */
-    icSignature                 cmmId;          /* CMM for profile */
-    icUInt32Number              version;        /* Format version */
-    icProfileClassSignature     deviceClass;    /* Type of profile */
-    icColorSpaceSignature       colorSpace;     /* Clr space of data */
-    icColorSpaceSignature       pcs;            /* PCS, XYZ or Lab */
-    icDateTimeNumber            date;           /* Creation Date */
-    icSignature                 magic;          /* icMagicNumber */
-    icPlatformSignature         platform;       /* Primary Platform */
-    icUInt32Number              flags;          /* Various bits */
-    icSignature                 manufacturer;   /* Dev manufacturer */
-    icUInt32Number              model;          /* Dev model number */
-    icUInt64Number              attributes;     /* Device attributes */
-    icUInt32Number              renderingIntent;/* Rendering intent */
-    icXYZNumber                 illuminant;     /* Profile illuminant */
-    icSignature                 creator;        /* Profile creator */
-    icInt8Number                reserved[44];   /* Reserved */
-} icHeader;
-
-/*
- * A profile,
- * we can't use icTagList here because its not at the end of the structure
- */
-typedef struct {
-    icHeader            header;         /* The header */
-    icUInt32Number      count;          /* Num tags in the profile */
-    icInt8Number        data[icAny];    /* The tagTable and tagData */
-/*
- * Data that follows is of the form
- *
- * icTag        tagTable[icAny];        * The tag table
- * icInt8Number tagData[icAny];         * The tag data
- */
-} icProfile;
-
-/*------------------------------------------------------------------------*/
-/* Obsolete entries */
-
-/* icNamedColor was replaced with icNamedColor2 */
-typedef struct {
-    icUInt32Number      vendorFlag;     /* Bottom 16 bits for IC use */
-    icUInt32Number      count;          /* Count of named colors */
-    icInt8Number        data[icAny];    /* Named color data follows */
-/*
- *  Data that follows is of this form
- *
- * icInt8Number         prefix[icAny];  * Prefix
- * icInt8Number         suffix[icAny];  * Suffix
- * icInt8Number         root1[icAny];   * Root name
- * icInt8Number         coords1[icAny]; * Color coordinates
- * icInt8Number         root2[icAny];   * Root name
- * icInt8Number         coords2[icAny]; * Color coordinates
- *                      :
- *                      :
- * Repeat for root name and color coordinates up to (count-1)
- */
-} icNamedColor;
-
-/* icNamedColorType was replaced by icNamedColor2Type */
-typedef struct {
-    icTagBase           base;           /* Signature, "ncol" */
-    icNamedColor        ncolor;         /* Named color data */
-} icNamedColorType;
-
-#endif /* ICC_H */
--- a/src/share/native/sun/java2d/cmm/lcms/lcms.h	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2099 +0,0 @@
-/*
- * 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// This file is available under and governed by the GNU General Public
-// License version 2 only, as published by the Free Software Foundation.
-// However, the following notice accompanied the original version of this
-// file:
-//
-//
-//  Little cms
-//  Copyright (C) 1998-2007 Marti Maria
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the Software
-// is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
-// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// Version 1.18
-
-#ifndef __cms_H
-
-// ********** Configuration toggles ****************************************
-
-//   Optimization mode.
-//
-// Note that USE_ASSEMBLER Is fastest by far, but it is limited to Pentium.
-// USE_FLOAT are the generic floating-point routines. USE_C should work on
-// virtually any machine.
-
-//#define USE_FLOAT        1
-// #define USE_C            1
-#define USE_ASSEMBLER    1
-
-// Define this if you are using this package as a DLL (windows only)
-
-// #define LCMS_DLL     1
-// #define LCMS_DLL_BUILD   1
-
-// Uncomment if you are trying the engine in a non-windows environment
-// like linux, SGI, VAX, FreeBSD, BeOS, etc.
-#define NON_WINDOWS  1
-
-// Uncomment this one if you are using big endian machines (only meaningful
-// when NON_WINDOWS is used)
-// #define USE_BIG_ENDIAN   1
-
-// Uncomment this one if your compiler/machine does support the
-// "long long" type This will speedup fixed point math. (USE_C only)
-#define USE_INT64        1
-
-// Some machines does not have a reliable 'swab' function. Usually
-// leave commented unless the testbed diagnoses the contrary.
-// #define USE_CUSTOM_SWAB   1
-
-// Uncomment this if your compiler supports inline
-#define USE_INLINE  1
-
-// Uncomment this if your compiler doesn't work with fast floor function
-// #define USE_DEFAULT_FLOOR_CONVERSION  1
-
-// Uncomment this line on multithreading environments
-// #define USE_PTHREADS    1
-
-// Uncomment this line if you want lcms to use the black point tag in profile,
-// if commented, lcms will compute the black point by its own.
-// It is safer to leve it commented out
-// #define HONOR_BLACK_POINT_TAG    1
-
-// ********** End of configuration toggles ******************************
-
-#define LCMS_VERSION        118
-
-// Microsoft VisualC++
-
-// Deal with Microsoft's attempt at deprecating C standard runtime functions
-#ifdef _MSC_VER
-#    undef NON_WINDOWS
-#    if (_MSC_VER >= 1400)
-#      ifndef _CRT_SECURE_NO_DEPRECATE
-#        define _CRT_SECURE_NO_DEPRECATE 1
-#      endif
-#    endif
-#endif
-
-// Borland C
-
-#ifdef __BORLANDC__
-#    undef NON_WINDOWS
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <math.h>
-#include <assert.h>
-#include <stdarg.h>
-#include <time.h>
-
-// Metroworks CodeWarrior
-#ifdef __MWERKS__
-#   define unlink remove
-#   if WIN32
-#       define USE_CUSTOM_SWAB 1
-#       undef  NON_WINDOWS
-#   else
-#       define NON_WINDOWS   1
-#   endif
-#endif
-
-
-// Here comes the Non-Windows settings
-
-#ifdef NON_WINDOWS
-
-// Non windows environments. Also avoid indentation on includes.
-
-#ifdef USE_PTHREADS
-#   include <pthread.h>
-typedef    pthread_rwlock_t      LCMS_RWLOCK_T;
-#   define LCMS_CREATE_LOCK(x)       pthread_rwlock_init((x), NULL)
-#   define LCMS_FREE_LOCK(x)         pthread_rwlock_destroy((x))
-#   define LCMS_READ_LOCK(x)             pthread_rwlock_rdlock((x))
-#   define LCMS_WRITE_LOCK(x)        pthread_rwlock_wrlock((x))
-#   define LCMS_UNLOCK(x)            pthread_rwlock_unlock((x))
-#endif
-
-#undef LCMS_DLL
-
-#ifdef  USE_ASSEMBLER
-#  undef  USE_ASSEMBLER
-#  define USE_C               1
-#endif
-
-#ifdef _HOST_BIG_ENDIAN
-#   define USE_BIG_ENDIAN      1
-#endif
-
-#if defined(__sgi__) || defined(__sgi) || defined(__powerpc__) || defined(sparc) || defined(__ppc__) || defined(__s390__) || defined(__s390x__)
-#   define USE_BIG_ENDIAN      1
-#endif
-
-#if TARGET_CPU_PPC
-#   define USE_BIG_ENDIAN   1
-#endif
-
-#if macintosh
-# ifndef __LITTLE_ENDIAN__
-#   define USE_BIG_ENDIAN      1
-# endif
-#endif
-
-#ifdef __BIG_ENDIAN__
-#   define USE_BIG_ENDIAN      1
-#endif
-
-#ifdef WORDS_BIGENDIAN
-#   define USE_BIG_ENDIAN      1
-#endif
-
-#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)
-#  include <sys/types.h>
-#  define USE_INT64           1
-#  define LCMSSLONGLONG       int64_t
-#  define LCMSULONGLONG       u_int64_t
-#endif
-
-#ifdef USE_INT64
-#   ifndef LCMSULONGLONG
-#       define LCMSULONGLONG unsigned long long
-#       define LCMSSLONGLONG long long
-#   endif
-#endif
-
-#if !defined(__INTEGRITY)
-#   include <memory.h>
-#endif
-
-#include <string.h>
-
-#if defined(__GNUC__) || defined(__FreeBSD__)
-#   include <unistd.h>
-#endif
-
-#ifndef LCMS_WIN_TYPES_ALREADY_DEFINED
-
-typedef unsigned char BYTE, *LPBYTE;
-typedef unsigned short WORD, *LPWORD;
-typedef unsigned long DWORD, *LPDWORD;
-typedef char *LPSTR;
-typedef void *LPVOID;
-
-#define ZeroMemory(p,l)     memset((p),0,(l))
-#define CopyMemory(d,s,l)   memcpy((d),(s),(l))
-#define FAR
-
-#ifndef stricmp
-#   define stricmp strcasecmp
-#endif
-
-
-#ifndef FALSE
-#       define FALSE 0
-#endif
-#ifndef TRUE
-#       define TRUE  1
-#endif
-
-#define LOWORD(l)    ((WORD)(l))
-#define HIWORD(l)    ((WORD)((DWORD)(l) >> 16))
-
-#ifndef MAX_PATH
-#       define MAX_PATH     (256)
-#endif
-
-#define cdecl
-#endif
-
-// The specification for "inline" is section 6.7.4 of the C99 standard (ISO/IEC 9899:1999).
-
-#define LCMS_INLINE static inline
-
-#else
-
-// Win32 stuff
-
-#ifndef WIN32_LEAN_AND_MEAN
-#  define WIN32_LEAN_AND_MEAN
-#endif
-
-#include <windows.h>
-
-#ifdef _WIN64
-# ifdef USE_ASSEMBLER
-#    undef  USE_ASSEMBLER
-#    define USE_C           1
-# endif
-#endif
-
-#ifdef  USE_INT64
-#  ifndef LCMSULONGLONG
-#    define LCMSULONGLONG unsigned __int64
-#    define LCMSSLONGLONG __int64
-#  endif
-#endif
-
-// This works for both VC & BorlandC
-#define LCMS_INLINE __inline
-
-#ifdef USE_PTHREADS
-typedef CRITICAL_SECTION LCMS_RWLOCK_T;
-#   define LCMS_CREATE_LOCK(x)       InitializeCriticalSection((x))
-#   define LCMS_FREE_LOCK(x)         DeleteCriticalSection((x))
-#   define LCMS_READ_LOCK(x)             EnterCriticalSection((x))
-#   define LCMS_WRITE_LOCK(x)        EnterCriticalSection((x))
-#   define LCMS_UNLOCK(x)            LeaveCriticalSection((x))
-#endif
-
-#endif
-
-#ifndef USE_PTHREADS
-typedef int LCMS_RWLOCK_T;
-#   define LCMS_CREATE_LOCK(x)
-#   define LCMS_FREE_LOCK(x)
-#   define LCMS_READ_LOCK(x)
-#   define LCMS_WRITE_LOCK(x)
-#   define LCMS_UNLOCK(x)
-#endif
-
-// Base types
-
-typedef int   LCMSBOOL;
-typedef void* LCMSHANDLE;
-
-#include "icc34.h"          // ICC header file
-
-
-// Some tag & type additions
-
-#define lcmsSignature                  ((icSignature)           0x6c636d73L)
-
-#define icSigLuvKData                  ((icColorSpaceSignature) 0x4C75764BL)  // 'LuvK'
-
-#define icSigHexachromeData            ((icColorSpaceSignature) 0x4d434836L)  // MCH6
-#define icSigHeptachromeData           ((icColorSpaceSignature) 0x4d434837L)  // MCH7
-#define icSigOctachromeData            ((icColorSpaceSignature) 0x4d434838L)  // MCH8
-
-#define icSigMCH5Data                  ((icColorSpaceSignature) 0x4d434835L)  // MCH5
-#define icSigMCH6Data                  ((icColorSpaceSignature) 0x4d434836L)  // MCH6
-#define icSigMCH7Data                  ((icColorSpaceSignature) 0x4d434837L)  // MCH7
-#define icSigMCH8Data                  ((icColorSpaceSignature) 0x4d434838L)  // MCH8
-#define icSigMCH9Data                  ((icColorSpaceSignature) 0x4d434839L)  // MCH9
-#define icSigMCHAData                  ((icColorSpaceSignature) 0x4d434841L)  // MCHA
-#define icSigMCHBData                  ((icColorSpaceSignature) 0x4d434842L)  // MCHB
-#define icSigMCHCData                  ((icColorSpaceSignature) 0x4d434843L)  // MCHC
-#define icSigMCHDData                  ((icColorSpaceSignature) 0x4d434844L)  // MCHD
-#define icSigMCHEData                  ((icColorSpaceSignature) 0x4d434845L)  // MCHE
-#define icSigMCHFData                  ((icColorSpaceSignature) 0x4d434846L)  // MCHF
-
-#define icSigChromaticityTag            ((icTagSignature) 0x6368726dL) // As per Addendum 2 to Spec. ICC.1:1998-09
-#define icSigChromaticAdaptationTag     ((icTagSignature) 0x63686164L) // 'chad'
-#define icSigColorantTableTag           ((icTagSignature) 0x636c7274L) // 'clrt'
-#define icSigColorantTableOutTag        ((icTagSignature) 0x636c6f74L) // 'clot'
-
-#define icSigParametricCurveType        ((icTagTypeSignature) 0x70617261L)  // parametric (ICC 4.0)
-#define icSigMultiLocalizedUnicodeType  ((icTagTypeSignature) 0x6D6C7563L)
-#define icSigS15Fixed16ArrayType        ((icTagTypeSignature) 0x73663332L)
-#define icSigChromaticityType           ((icTagTypeSignature) 0x6368726dL)
-#define icSiglutAtoBType                ((icTagTypeSignature) 0x6d414220L)  // mAB
-#define icSiglutBtoAType                ((icTagTypeSignature) 0x6d424120L)  // mBA
-#define icSigColorantTableType          ((icTagTypeSignature) 0x636c7274L)  // clrt
-
-
-typedef struct {
-    icUInt8Number       gridPoints[16]; // Number of grid points in each dimension.
-    icUInt8Number       prec;           // Precision of data elements in bytes.
-    icUInt8Number       pad1;
-    icUInt8Number       pad2;
-    icUInt8Number       pad3;
-    /*icUInt8Number     data[icAny];     Data follows see spec for size */
-} icCLutStruct;
-
-// icLutAtoB
-typedef struct {
-    icUInt8Number       inputChan;      // Number of input channels
-    icUInt8Number       outputChan;     // Number of output channels
-    icUInt8Number       pad1;
-    icUInt8Number       pad2;
-    icUInt32Number      offsetB;        // Offset to first "B" curve
-    icUInt32Number      offsetMat;      // Offset to matrix
-    icUInt32Number      offsetM;        // Offset to first "M" curve
-    icUInt32Number      offsetC;        // Offset to CLUT
-    icUInt32Number      offsetA;        // Offset to first "A" curve
-    /*icUInt8Number     data[icAny];     Data follows see spec for size */
-} icLutAtoB;
-
-// icLutBtoA
-typedef struct {
-    icUInt8Number       inputChan;      // Number of input channels
-    icUInt8Number       outputChan;     // Number of output channels
-    icUInt8Number       pad1;
-    icUInt8Number       pad2;
-    icUInt32Number      offsetB;        // Offset to first "B" curve
-    icUInt32Number      offsetMat;      // Offset to matrix
-    icUInt32Number      offsetM;        // Offset to first "M" curve
-    icUInt32Number      offsetC;        // Offset to CLUT
-    icUInt32Number      offsetA;        // Offset to first "A" curve
-    /*icUInt8Number     data[icAny];     Data follows see spec for size */
-} icLutBtoA;
-
-
-
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// Calling convention
-
-#ifdef NON_WINDOWS
-#  define LCMSEXPORT
-#  define LCMSAPI
-#else
-# ifdef LCMS_DLL
-#   ifdef __BORLANDC__
-#      define LCMSEXPORT __stdcall _export
-#      define LCMSAPI
-#   else
-       // VC++
-#       define LCMSEXPORT  _stdcall
-#       ifdef LCMS_DLL_BUILD
-#           define LCMSAPI     __declspec(dllexport)
-#       else
-#           define LCMSAPI     __declspec(dllimport)
-#       endif
-#   endif
-# else
-#       define LCMSEXPORT cdecl
-#       define LCMSAPI
-# endif
-#endif
-
-#ifdef  USE_ASSEMBLER
-#ifdef __BORLANDC__
-
-#      define ASM     asm
-#      define RET(v)  return(v)
-#else
-      // VC++
-#      define ASM     __asm
-#      define RET(v)  return
-#endif
-#endif
-
-#ifdef _MSC_VER
-#ifndef  stricmp
-#      define stricmp _stricmp
-#endif
-#ifndef unlink
-#      define unlink  _unlink
-#endif
-#ifndef swab
-#      define swab    _swab
-#endif
-#ifndef itoa
-#       define itoa   _itoa
-#endif
-#ifndef fileno
-#       define fileno   _fileno
-#endif
-#ifndef strupr
-#       define strupr   _strupr
-#endif
-#ifndef hypot
-#       define hypot    _hypot
-#endif
-#ifndef snprintf
-#       define snprintf  _snprintf
-#endif
-#ifndef vsnprintf
-#       define vsnprintf  _vsnprintf
-#endif
-
-
-#endif
-
-
-#ifndef M_PI
-#       define M_PI    3.14159265358979323846
-#endif
-
-#ifndef LOGE
-#       define LOGE   0.4342944819
-#endif
-
-// ********** Little cms API ***************************************************
-
-typedef LCMSHANDLE cmsHPROFILE;        // Opaque typedefs to hide internals
-typedef LCMSHANDLE cmsHTRANSFORM;
-
-#define MAXCHANNELS  16                // Maximum number of channels
-
-// Format of pixel is defined by one DWORD, using bit fields as follows
-//
-//            D TTTTT U Y F P X S EEE CCCC BBB
-//
-//            D: Use dither (8 bits only)
-//            T: Pixeltype
-//            F: Flavor  0=MinIsBlack(Chocolate) 1=MinIsWhite(Vanilla)
-//            P: Planar? 0=Chunky, 1=Planar
-//            X: swap 16 bps endianess?
-//            S: Do swap? ie, BGR, KYMC
-//            E: Extra samples
-//            C: Channels (Samples per pixel)
-//            B: Bytes per sample
-//            Y: Swap first - changes ABGR to BGRA and KCMY to CMYK
-
-
-#define DITHER_SH(s)           ((s) << 22)
-#define COLORSPACE_SH(s)       ((s) << 16)
-#define SWAPFIRST_SH(s)        ((s) << 14)
-#define FLAVOR_SH(s)           ((s) << 13)
-#define PLANAR_SH(p)           ((p) << 12)
-#define ENDIAN16_SH(e)         ((e) << 11)
-#define DOSWAP_SH(e)           ((e) << 10)
-#define EXTRA_SH(e)            ((e) << 7)
-#define CHANNELS_SH(c)         ((c) << 3)
-#define BYTES_SH(b)            (b)
-
-// Pixel types
-
-#define PT_ANY       0    // Don't check colorspace
-                          // 1 & 2 are reserved
-#define PT_GRAY      3
-#define PT_RGB       4
-#define PT_CMY       5
-#define PT_CMYK      6
-#define PT_YCbCr     7
-#define PT_YUV       8      // Lu'v'
-#define PT_XYZ       9
-#define PT_Lab       10
-#define PT_YUVK      11     // Lu'v'K
-#define PT_HSV       12
-#define PT_HLS       13
-#define PT_Yxy       14
-#define PT_HiFi      15
-#define PT_HiFi7     16
-#define PT_HiFi8     17
-#define PT_HiFi9     18
-#define PT_HiFi10    19
-#define PT_HiFi11    20
-#define PT_HiFi12    21
-#define PT_HiFi13    22
-#define PT_HiFi14    23
-#define PT_HiFi15    24
-
-#define NOCOLORSPACECHECK(x)    ((x) & 0xFFFF)
-
-// Some (not all!) representations
-
-#ifndef TYPE_RGB_8      // TYPE_RGB_8 is a very common identifier, so don't include ours
-                        // if user has it already defined.
-
-#define TYPE_GRAY_8            (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(1))
-#define TYPE_GRAY_8_REV        (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(1)|FLAVOR_SH(1))
-#define TYPE_GRAY_16           (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(2))
-#define TYPE_GRAY_16_REV       (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(2)|FLAVOR_SH(1))
-#define TYPE_GRAY_16_SE        (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_GRAYA_8           (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(1))
-#define TYPE_GRAYA_16          (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(2))
-#define TYPE_GRAYA_16_SE       (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_GRAYA_8_PLANAR    (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_GRAYA_16_PLANAR   (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(2)|PLANAR_SH(1))
-
-#define TYPE_RGB_8             (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(1))
-#define TYPE_RGB_8_PLANAR      (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_BGR_8             (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_BGR_8_PLANAR      (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1)|PLANAR_SH(1))
-#define TYPE_RGB_16            (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_RGB_16_PLANAR     (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_RGB_16_SE         (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_BGR_16            (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_BGR_16_PLANAR     (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|PLANAR_SH(1))
-#define TYPE_BGR_16_SE         (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-
-#define TYPE_RGBA_8            (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1))
-#define TYPE_RGBA_8_PLANAR     (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_RGBA_16           (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_RGBA_16_PLANAR    (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_RGBA_16_SE        (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
-
-#define TYPE_ARGB_8            (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1)|SWAPFIRST_SH(1))
-#define TYPE_ARGB_16           (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|SWAPFIRST_SH(1))
-
-#define TYPE_ABGR_8            (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_ABGR_16           (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_ABGR_16_PLANAR    (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|PLANAR_SH(1))
-#define TYPE_ABGR_16_SE        (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-
-#define TYPE_BGRA_8            (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1)|SWAPFIRST_SH(1))
-#define TYPE_BGRA_16           (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|SWAPFIRST_SH(1))
-#define TYPE_BGRA_16_SE        (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1)|SWAPFIRST_SH(1))
-
-#define TYPE_CMY_8             (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(1))
-#define TYPE_CMY_8_PLANAR      (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_CMY_16            (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_CMY_16_PLANAR     (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_CMY_16_SE         (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
-
-#define TYPE_CMYK_8            (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1))
-#define TYPE_CMYKA_8           (COLORSPACE_SH(PT_CMYK)|EXTRA_SH(1)|CHANNELS_SH(4)|BYTES_SH(1))
-#define TYPE_CMYK_8_REV        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|FLAVOR_SH(1))
-#define TYPE_YUVK_8            TYPE_CMYK_8_REV
-#define TYPE_CMYK_8_PLANAR     (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_CMYK_16           (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2))
-#define TYPE_CMYK_16_REV       (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|FLAVOR_SH(1))
-#define TYPE_YUVK_16           TYPE_CMYK_16_REV
-#define TYPE_CMYK_16_PLANAR    (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_CMYK_16_SE        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|ENDIAN16_SH(1))
-
-#define TYPE_KYMC_8            (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_KYMC_16           (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_KYMC_16_SE        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-
-#define TYPE_KCMY_8            (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|SWAPFIRST_SH(1))
-#define TYPE_KCMY_8_REV        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|FLAVOR_SH(1)|SWAPFIRST_SH(1))
-#define TYPE_KCMY_16           (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|SWAPFIRST_SH(1))
-#define TYPE_KCMY_16_REV       (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|FLAVOR_SH(1)|SWAPFIRST_SH(1))
-#define TYPE_KCMY_16_SE        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|ENDIAN16_SH(1)|SWAPFIRST_SH(1))
-
-
-// HiFi separations, Thanks to Steven Greaves for providing the code,
-// the colorspace is not checked
-#define TYPE_CMYK5_8           (CHANNELS_SH(5)|BYTES_SH(1))
-#define TYPE_CMYK5_16          (CHANNELS_SH(5)|BYTES_SH(2))
-#define TYPE_CMYK5_16_SE       (CHANNELS_SH(5)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_KYMC5_8           (CHANNELS_SH(5)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_KYMC5_16          (CHANNELS_SH(5)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_KYMC5_16_SE       (CHANNELS_SH(5)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-
-#define TYPE_CMYKcm_8          (CHANNELS_SH(6)|BYTES_SH(1))
-#define TYPE_CMYKcm_8_PLANAR   (CHANNELS_SH(6)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_CMYKcm_16         (CHANNELS_SH(6)|BYTES_SH(2))
-#define TYPE_CMYKcm_16_PLANAR  (CHANNELS_SH(6)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_CMYKcm_16_SE      (CHANNELS_SH(6)|BYTES_SH(2)|ENDIAN16_SH(1))
-
-// Separations with more than 6 channels aren't very standarized,
-// Except most start with CMYK and add other colors, so I just used
-// then total number of channels after CMYK i.e CMYK8_8
-
-#define TYPE_CMYK7_8           (CHANNELS_SH(7)|BYTES_SH(1))
-#define TYPE_CMYK7_16          (CHANNELS_SH(7)|BYTES_SH(2))
-#define TYPE_CMYK7_16_SE       (CHANNELS_SH(7)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_KYMC7_8           (CHANNELS_SH(7)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_KYMC7_16          (CHANNELS_SH(7)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_KYMC7_16_SE       (CHANNELS_SH(7)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-#define TYPE_CMYK8_8           (CHANNELS_SH(8)|BYTES_SH(1))
-#define TYPE_CMYK8_16          (CHANNELS_SH(8)|BYTES_SH(2))
-#define TYPE_CMYK8_16_SE       (CHANNELS_SH(8)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_KYMC8_8           (CHANNELS_SH(8)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_KYMC8_16          (CHANNELS_SH(8)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_KYMC8_16_SE       (CHANNELS_SH(8)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-#define TYPE_CMYK9_8           (CHANNELS_SH(9)|BYTES_SH(1))
-#define TYPE_CMYK9_16          (CHANNELS_SH(9)|BYTES_SH(2))
-#define TYPE_CMYK9_16_SE       (CHANNELS_SH(9)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_KYMC9_8           (CHANNELS_SH(9)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_KYMC9_16          (CHANNELS_SH(9)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_KYMC9_16_SE       (CHANNELS_SH(9)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-#define TYPE_CMYK10_8          (CHANNELS_SH(10)|BYTES_SH(1))
-#define TYPE_CMYK10_16         (CHANNELS_SH(10)|BYTES_SH(2))
-#define TYPE_CMYK10_16_SE      (CHANNELS_SH(10)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_KYMC10_8          (CHANNELS_SH(10)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_KYMC10_16         (CHANNELS_SH(10)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_KYMC10_16_SE      (CHANNELS_SH(10)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-#define TYPE_CMYK11_8          (CHANNELS_SH(11)|BYTES_SH(1))
-#define TYPE_CMYK11_16         (CHANNELS_SH(11)|BYTES_SH(2))
-#define TYPE_CMYK11_16_SE      (CHANNELS_SH(11)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_KYMC11_8          (CHANNELS_SH(11)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_KYMC11_16         (CHANNELS_SH(11)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_KYMC11_16_SE      (CHANNELS_SH(11)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-#define TYPE_CMYK12_8          (CHANNELS_SH(12)|BYTES_SH(1))
-#define TYPE_CMYK12_16         (CHANNELS_SH(12)|BYTES_SH(2))
-#define TYPE_CMYK12_16_SE      (CHANNELS_SH(12)|BYTES_SH(2)|ENDIAN16_SH(1))
-#define TYPE_KYMC12_8          (CHANNELS_SH(12)|BYTES_SH(1)|DOSWAP_SH(1))
-#define TYPE_KYMC12_16         (CHANNELS_SH(12)|BYTES_SH(2)|DOSWAP_SH(1))
-#define TYPE_KYMC12_16_SE      (CHANNELS_SH(12)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
-
-// Colorimetric
-
-#define TYPE_XYZ_16            (COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_Lab_8             (COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(1))
-#define TYPE_ALab_8            (COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)|DOSWAP_SH(1))
-#define TYPE_Lab_16            (COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_Yxy_16            (COLORSPACE_SH(PT_Yxy)|CHANNELS_SH(3)|BYTES_SH(2))
-
-// YCbCr
-
-#define TYPE_YCbCr_8           (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(1))
-#define TYPE_YCbCr_8_PLANAR    (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_YCbCr_16          (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_YCbCr_16_PLANAR   (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_YCbCr_16_SE       (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
-
-// YUV
-
-#define TYPE_YUV_8           (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(1))
-#define TYPE_YUV_8_PLANAR    (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_YUV_16          (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_YUV_16_PLANAR   (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_YUV_16_SE       (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
-
-// HLS
-
-#define TYPE_HLS_8           (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(1))
-#define TYPE_HLS_8_PLANAR    (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_HLS_16          (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_HLS_16_PLANAR   (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_HLS_16_SE       (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
-
-
-// HSV
-
-#define TYPE_HSV_8           (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(1))
-#define TYPE_HSV_8_PLANAR    (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
-#define TYPE_HSV_16          (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(2))
-#define TYPE_HSV_16_PLANAR   (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
-#define TYPE_HSV_16_SE       (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
-
-// Named color index. Only 16 bits allowed (don't check colorspace)
-
-#define TYPE_NAMED_COLOR_INDEX   (CHANNELS_SH(1)|BYTES_SH(2))
-
-// Double values. Painful slow, but sometimes helpful. NOTE THAT 'BYTES' FIELD IS SET TO ZERO!
-
-#define TYPE_XYZ_DBL        (COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(0))
-#define TYPE_Lab_DBL        (COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(0))
-#define TYPE_GRAY_DBL       (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(0))
-#define TYPE_RGB_DBL        (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(0))
-#define TYPE_CMYK_DBL       (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(0))
-
-#endif
-
-
-// Gamma table parameters
-
-typedef struct {
-
-    unsigned int Crc32;  // Has my table been touched?
-
-    // Keep initial parameters for further serialization
-
-    int          Type;
-    double       Params[10];
-
-    }  LCMSGAMMAPARAMS, FAR* LPLCMSGAMMAPARAMS;
-
-// Gamma tables.
-
-typedef struct {
-
-    LCMSGAMMAPARAMS Seed;       // Parameters used for table creation
-
-    // Table-based representation follows
-
-    int  nEntries;
-    WORD GammaTable[1];
-
-    } GAMMATABLE;
-
-typedef GAMMATABLE FAR* LPGAMMATABLE;
-
-// Sampled curves (1D)
-typedef struct {
-
-    int     nItems;
-    double* Values;
-
-    } SAMPLEDCURVE;
-
-typedef SAMPLEDCURVE FAR* LPSAMPLEDCURVE;
-
-// Vectors
-typedef struct {                // Float Vector
-
-    double n[3];
-
-    } VEC3;
-
-typedef VEC3 FAR* LPVEC3;
-
-
-typedef struct {                // Matrix
-
-    VEC3 v[3];
-
-    } MAT3;
-
-typedef MAT3 FAR* LPMAT3;
-
-// Colorspace values
-typedef struct {
-
-        double X;
-        double Y;
-        double Z;
-
-    } cmsCIEXYZ;
-
-typedef cmsCIEXYZ FAR* LPcmsCIEXYZ;
-
-typedef struct {
-
-        double x;
-        double y;
-        double Y;
-
-    } cmsCIExyY;
-
-typedef cmsCIExyY FAR* LPcmsCIExyY;
-
-typedef struct {
-
-        double L;
-        double a;
-        double b;
-
-    } cmsCIELab;
-
-typedef cmsCIELab FAR* LPcmsCIELab;
-
-typedef struct {
-
-        double L;
-        double C;
-        double h;
-
-    } cmsCIELCh;
-
-typedef cmsCIELCh FAR* LPcmsCIELCh;
-
-typedef struct {
-
-        double J;
-        double C;
-        double h;
-
-    } cmsJCh;
-
-typedef cmsJCh FAR* LPcmsJCh;
-
-// Primaries
-typedef struct {
-
-        cmsCIEXYZ  Red;
-        cmsCIEXYZ  Green;
-        cmsCIEXYZ  Blue;
-
-    } cmsCIEXYZTRIPLE;
-
-typedef cmsCIEXYZTRIPLE FAR* LPcmsCIEXYZTRIPLE;
-
-
-typedef struct {
-
-        cmsCIExyY  Red;
-        cmsCIExyY  Green;
-        cmsCIExyY  Blue;
-
-    } cmsCIExyYTRIPLE;
-
-typedef cmsCIExyYTRIPLE FAR* LPcmsCIExyYTRIPLE;
-
-
-
-// Following ICC spec
-
-#define D50X  (0.9642)
-#define D50Y  (1.0)
-#define D50Z  (0.8249)
-
-#define PERCEPTUAL_BLACK_X  (0.00336)
-#define PERCEPTUAL_BLACK_Y  (0.0034731)
-#define PERCEPTUAL_BLACK_Z  (0.00287)
-
-// Does return pointers to constant structs
-
-LCMSAPI LPcmsCIEXYZ LCMSEXPORT cmsD50_XYZ(void);
-LCMSAPI LPcmsCIExyY LCMSEXPORT cmsD50_xyY(void);
-
-
-// Input/Output
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess);
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsOpenProfileFromMem(LPVOID MemPtr, DWORD dwSize);
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile);
-
-// Predefined run-time profiles
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateRGBProfile(LPcmsCIExyY WhitePoint,
-                                        LPcmsCIExyYTRIPLE Primaries,
-                                        LPGAMMATABLE TransferFunction[3]);
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateGrayProfile(LPcmsCIExyY WhitePoint,
-                                              LPGAMMATABLE TransferFunction);
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateLinearizationDeviceLink(icColorSpaceSignature ColorSpace,
-                                                        LPGAMMATABLE TransferFunctions[]);
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateInkLimitingDeviceLink(icColorSpaceSignature ColorSpace,
-                                                      double Limit);
-
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateLabProfile(LPcmsCIExyY WhitePoint);
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateLab4Profile(LPcmsCIExyY WhitePoint);
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateXYZProfile(void);
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreate_sRGBProfile(void);
-
-
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateBCHSWabstractProfile(int nLUTPoints,
-                                                     double Bright,
-                                                     double Contrast,
-                                                     double Hue,
-                                                     double Saturation,
-                                                     int TempSrc,
-                                                     int TempDest);
-
-LCMSAPI cmsHPROFILE   LCMSEXPORT cmsCreateNULLProfile(void);
-
-
-// Colorimetric space conversions
-
-LCMSAPI void          LCMSEXPORT cmsXYZ2xyY(LPcmsCIExyY Dest, const cmsCIEXYZ* Source);
-LCMSAPI void          LCMSEXPORT cmsxyY2XYZ(LPcmsCIEXYZ Dest, const cmsCIExyY* Source);
-LCMSAPI void          LCMSEXPORT cmsXYZ2Lab(LPcmsCIEXYZ WhitePoint, LPcmsCIELab Lab, const cmsCIEXYZ* xyz);
-LCMSAPI void          LCMSEXPORT cmsLab2XYZ(LPcmsCIEXYZ WhitePoint, LPcmsCIEXYZ xyz, const cmsCIELab* Lab);
-LCMSAPI void          LCMSEXPORT cmsLab2LCh(LPcmsCIELCh LCh, const cmsCIELab* Lab);
-LCMSAPI void          LCMSEXPORT cmsLCh2Lab(LPcmsCIELab Lab, const cmsCIELCh* LCh);
-
-
-// CIELab handling
-
-LCMSAPI double        LCMSEXPORT cmsDeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2);
-LCMSAPI double        LCMSEXPORT cmsCIE94DeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2);
-LCMSAPI double        LCMSEXPORT cmsBFDdeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2);
-LCMSAPI double        LCMSEXPORT cmsCMCdeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2);
-LCMSAPI double        LCMSEXPORT cmsCIE2000DeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2, double Kl, double Kc, double Kh);
-
-LCMSAPI void          LCMSEXPORT cmsClampLab(LPcmsCIELab Lab, double amax, double amin, double bmax, double bmin);
-
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsWhitePointFromTemp(int TempK, LPcmsCIExyY WhitePoint);
-
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsAdaptToIlluminant(LPcmsCIEXYZ Result,
-                                                        LPcmsCIEXYZ SourceWhitePt,
-                                                        LPcmsCIEXYZ Illuminant,
-                                                        LPcmsCIEXYZ Value);
-
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsBuildRGB2XYZtransferMatrix(LPMAT3 r,
-                                                        LPcmsCIExyY WhitePoint,
-                                                        LPcmsCIExyYTRIPLE Primaries);
-
-// Viewing conditions
-
-#define AVG_SURROUND_4     0
-#define AVG_SURROUND       1
-#define DIM_SURROUND       2
-#define DARK_SURROUND      3
-#define CUTSHEET_SURROUND  4
-
-#define D_CALCULATE             (-1)
-#define D_CALCULATE_DISCOUNT    (-2)
-
-typedef struct {
-
-              cmsCIEXYZ whitePoint;
-              double    Yb;
-              double    La;
-              int       surround;
-              double    D_value;
-
-    } cmsViewingConditions;
-
-typedef cmsViewingConditions FAR* LPcmsViewingConditions;
-
-// CIECAM97s
-
-LCMSAPI LCMSHANDLE    LCMSEXPORT cmsCIECAM97sInit(LPcmsViewingConditions pVC2);
-LCMSAPI void          LCMSEXPORT cmsCIECAM97sDone(LCMSHANDLE hModel);
-LCMSAPI void          LCMSEXPORT cmsCIECAM97sForward(LCMSHANDLE hModel, LPcmsCIEXYZ pIn, LPcmsJCh pOut);
-LCMSAPI void          LCMSEXPORT cmsCIECAM97sReverse(LCMSHANDLE hModel, LPcmsJCh pIn,    LPcmsCIEXYZ pOut);
-
-
-// CIECAM02
-
-LCMSAPI LCMSHANDLE    LCMSEXPORT cmsCIECAM02Init(LPcmsViewingConditions pVC);
-LCMSAPI void          LCMSEXPORT cmsCIECAM02Done(LCMSHANDLE hModel);
-LCMSAPI void          LCMSEXPORT cmsCIECAM02Forward(LCMSHANDLE hModel, LPcmsCIEXYZ pIn, LPcmsJCh pOut);
-LCMSAPI void          LCMSEXPORT cmsCIECAM02Reverse(LCMSHANDLE hModel, LPcmsJCh pIn,    LPcmsCIEXYZ pOut);
-
-
-// Gamma
-
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsBuildGamma(int nEntries, double Gamma);
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsBuildParametricGamma(int nEntries, int Type, double Params[]);
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsAllocGamma(int nEntries);
-LCMSAPI void          LCMSEXPORT cmsFreeGamma(LPGAMMATABLE Gamma);
-LCMSAPI void          LCMSEXPORT cmsFreeGammaTriple(LPGAMMATABLE Gamma[3]);
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsDupGamma(LPGAMMATABLE Src);
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsReverseGamma(int nResultSamples, LPGAMMATABLE InGamma);
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma,  LPGAMMATABLE OutGamma);
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma,  LPGAMMATABLE OutGamma, int nPoints);
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
-LCMSAPI double        LCMSEXPORT cmsEstimateGamma(LPGAMMATABLE t);
-LCMSAPI double        LCMSEXPORT cmsEstimateGammaEx(LPWORD Table, int nEntries, double Thereshold);
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsReadICCGamma(cmsHPROFILE hProfile, icTagSignature sig);
-LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsReadICCGammaReversed(cmsHPROFILE hProfile, icTagSignature sig);
-
-// Access to Profile data.
-
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeMediaWhitePoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeMediaBlackPoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeIluminant(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeColorants(LPcmsCIEXYZTRIPLE Dest, cmsHPROFILE hProfile);
-LCMSAPI DWORD         LCMSEXPORT cmsTakeHeaderFlags(cmsHPROFILE hProfile);
-LCMSAPI DWORD         LCMSEXPORT cmsTakeHeaderAttributes(cmsHPROFILE hProfile);
-
-LCMSAPI void          LCMSEXPORT cmsSetLanguage(const char LanguageCode[4], const char CountryCode[4]);
-LCMSAPI const char*   LCMSEXPORT cmsTakeProductName(cmsHPROFILE hProfile);
-LCMSAPI const char*   LCMSEXPORT cmsTakeProductDesc(cmsHPROFILE hProfile);
-LCMSAPI const char*   LCMSEXPORT cmsTakeProductInfo(cmsHPROFILE hProfile);
-LCMSAPI const char*   LCMSEXPORT cmsTakeManufacturer(cmsHPROFILE hProfile);
-LCMSAPI const char*   LCMSEXPORT cmsTakeModel(cmsHPROFILE hProfile);
-LCMSAPI const char*   LCMSEXPORT cmsTakeCopyright(cmsHPROFILE hProfile);
-LCMSAPI const BYTE*   LCMSEXPORT cmsTakeProfileID(cmsHPROFILE hProfile);
-
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeCreationDateTime(struct tm *Dest, cmsHPROFILE hProfile);
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeCalibrationDateTime(struct tm *Dest, cmsHPROFILE hProfile);
-
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsIsTag(cmsHPROFILE hProfile, icTagSignature sig);
-LCMSAPI int           LCMSEXPORT cmsTakeRenderingIntent(cmsHPROFILE hProfile);
-
-LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeCharTargetData(cmsHPROFILE hProfile, char** Data, size_t* len);
-
-LCMSAPI int           LCMSEXPORT cmsReadICCTextEx(cmsHPROFILE hProfile, icTagSignature sig, char *Text, size_t size);
-LCMSAPI int           LCMSEXPORT cmsReadICCText(cmsHPROFILE hProfile, icTagSignature sig, char *Text);
-
-
-#define LCMS_DESC_MAX     512
-
-typedef struct {
-
-            icSignature                 deviceMfg;
-            icSignature                 deviceModel;
-            icUInt32Number              attributes[2];
-            icTechnologySignature       technology;
-
-            char Manufacturer[LCMS_DESC_MAX];
-            char Model[LCMS_DESC_MAX];
-
-    } cmsPSEQDESC, FAR *LPcmsPSEQDESC;
-
-typedef struct {
-
-            int n;
-            cmsPSEQDESC seq[1];
-
-    } cmsSEQ, FAR *LPcmsSEQ;
-
-
-LCMSAPI LPcmsSEQ      LCMSEXPORT cmsReadProfileSequenceDescription(cmsHPROFILE hProfile);
-LCMSAPI void          LCMSEXPORT cmsFreeProfileSequenceDescription(LPcmsSEQ pseq);
-
-
-// Translate form/to our notation to ICC
-LCMSAPI icColorSpaceSignature LCMSEXPORT _cmsICCcolorSpace(int OurNotation);
-LCMSAPI int                   LCMSEXPORT _cmsLCMScolorSpace(icColorSpaceSignature ProfileSpace);
-LCMSAPI int                   LCMSEXPORT _cmsChannelsOf(icColorSpaceSignature ColorSpace);
-LCMSAPI LCMSBOOL              LCMSEXPORT _cmsIsMatrixShaper(cmsHPROFILE hProfile);
-
-// How profiles may be used
-#define LCMS_USED_AS_INPUT      0
-#define LCMS_USED_AS_OUTPUT     1
-#define LCMS_USED_AS_PROOF      2
-
-LCMSAPI LCMSBOOL                LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile, int Intent, int UsedDirection);
-
-LCMSAPI icColorSpaceSignature   LCMSEXPORT cmsGetPCS(cmsHPROFILE hProfile);
-LCMSAPI icColorSpaceSignature   LCMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile);
-LCMSAPI icProfileClassSignature LCMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile);
-LCMSAPI DWORD                   LCMSEXPORT cmsGetProfileICCversion(cmsHPROFILE hProfile);
-LCMSAPI void                    LCMSEXPORT cmsSetProfileICCversion(cmsHPROFILE hProfile, DWORD Version);
-LCMSAPI icInt32Number           LCMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile);
-LCMSAPI icTagSignature          LCMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, icInt32Number n);
-
-
-LCMSAPI void          LCMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, icProfileClassSignature sig);
-LCMSAPI void          LCMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, icColorSpaceSignature sig);
-LCMSAPI void          LCMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, icColorSpaceSignature pcs);
-LCMSAPI void          LCMSEXPORT cmsSetRenderingIntent(cmsHPROFILE hProfile, int RenderingIntent);
-LCMSAPI void          LCMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, DWORD Flags);
-LCMSAPI void          LCMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, DWORD Flags);
-LCMSAPI void          LCMSEXPORT cmsSetProfileID(cmsHPROFILE hProfile, LPBYTE ProfileID);
-
-// Intents
-
-#define INTENT_PERCEPTUAL                 0
-#define INTENT_RELATIVE_COLORIMETRIC      1
-#define INTENT_SATURATION                 2
-#define INTENT_ABSOLUTE_COLORIMETRIC      3
-
-// Flags
-
-#define cmsFLAGS_MATRIXINPUT              0x0001
-#define cmsFLAGS_MATRIXOUTPUT             0x0002
-#define cmsFLAGS_MATRIXONLY               (cmsFLAGS_MATRIXINPUT|cmsFLAGS_MATRIXOUTPUT)
-
-#define cmsFLAGS_NOWHITEONWHITEFIXUP      0x0004    // Don't hot fix scum dot
-#define cmsFLAGS_NOPRELINEARIZATION       0x0010    // Don't create prelinearization tables
-                                                    // on precalculated transforms (internal use)
-
-#define cmsFLAGS_GUESSDEVICECLASS         0x0020    // Guess device class (for transform2devicelink)
-
-#define cmsFLAGS_NOTCACHE                 0x0040    // Inhibit 1-pixel cache
-
-#define cmsFLAGS_NOTPRECALC               0x0100
-#define cmsFLAGS_NULLTRANSFORM            0x0200    // Don't transform anyway
-#define cmsFLAGS_HIGHRESPRECALC           0x0400    // Use more memory to give better accurancy
-#define cmsFLAGS_LOWRESPRECALC            0x0800    // Use less memory to minimize resouces
-
-
-#define cmsFLAGS_WHITEBLACKCOMPENSATION   0x2000
-#define cmsFLAGS_BLACKPOINTCOMPENSATION   cmsFLAGS_WHITEBLACKCOMPENSATION
-
-// Proofing flags
-
-#define cmsFLAGS_GAMUTCHECK               0x1000    // Out of Gamut alarm
-#define cmsFLAGS_SOFTPROOFING             0x4000    // Do softproofing
-
-// Black preservation
-
-#define cmsFLAGS_PRESERVEBLACK            0x8000
-
-// CRD special
-
-#define cmsFLAGS_NODEFAULTRESOURCEDEF     0x01000000
-
-// Gridpoints
-
-#define cmsFLAGS_GRIDPOINTS(n)           (((n) & 0xFF) << 16)
-
-
-// Transforms
-
-LCMSAPI cmsHTRANSFORM LCMSEXPORT cmsCreateTransform(cmsHPROFILE Input,
-                                               DWORD InputFormat,
-                                               cmsHPROFILE Output,
-                                               DWORD OutputFormat,
-                                               int Intent,
-                                               DWORD dwFlags);
-
-LCMSAPI cmsHTRANSFORM LCMSEXPORT cmsCreateProofingTransform(cmsHPROFILE Input,
-                                               DWORD InputFormat,
-                                               cmsHPROFILE Output,
-                                               DWORD OutputFormat,
-                                               cmsHPROFILE Proofing,
-                                               int Intent,
-                                               int ProofingIntent,
-                                               DWORD dwFlags);
-
-LCMSAPI cmsHTRANSFORM LCMSEXPORT cmsCreateMultiprofileTransform(cmsHPROFILE hProfiles[],
-                                                                int nProfiles,
-                                                                DWORD InputFormat,
-                                                                DWORD OutputFormat,
-                                                                int Intent,
-                                                                DWORD dwFlags);
-
-LCMSAPI void         LCMSEXPORT cmsDeleteTransform(cmsHTRANSFORM hTransform);
-
-LCMSAPI void         LCMSEXPORT cmsDoTransform(cmsHTRANSFORM Transform,
-                                                 LPVOID InputBuffer,
-                                                 LPVOID OutputBuffer,
-                                                 unsigned int Size);
-
-LCMSAPI void         LCMSEXPORT cmsChangeBuffersFormat(cmsHTRANSFORM hTransform, DWORD InputFormat, DWORD dwOutputFormat);
-
-LCMSAPI void         LCMSEXPORT cmsSetAlarmCodes(int r, int g, int b);
-LCMSAPI void         LCMSEXPORT cmsGetAlarmCodes(int *r, int *g, int *b);
-
-
-// Adaptation state for absolute colorimetric intent
-
-LCMSAPI double       LCMSEXPORT cmsSetAdaptationState(double d);
-
-
-// Primary preservation strategy
-
-#define LCMS_PRESERVE_PURE_K    0
-#define LCMS_PRESERVE_K_PLANE   1
-
-LCMSAPI int LCMSEXPORT cmsSetCMYKPreservationStrategy(int n);
-
-// Named color support
-typedef struct {
-                char Name[MAX_PATH];
-                WORD PCS[3];
-                WORD DeviceColorant[MAXCHANNELS];
-
-
-        } cmsNAMEDCOLOR, FAR* LPcmsNAMEDCOLOR;
-
-typedef struct {
-                int nColors;
-                int Allocated;
-                int ColorantCount;
-                char Prefix[33];
-                char Suffix[33];
-
-                cmsNAMEDCOLOR List[1];
-
-        } cmsNAMEDCOLORLIST, FAR* LPcmsNAMEDCOLORLIST;
-
-// Named color support
-
-LCMSAPI int      LCMSEXPORT cmsNamedColorCount(cmsHTRANSFORM xform);
-LCMSAPI LCMSBOOL LCMSEXPORT cmsNamedColorInfo(cmsHTRANSFORM xform, int nColor, char* Name, char* Prefix, char* Suffix);
-LCMSAPI int      LCMSEXPORT cmsNamedColorIndex(cmsHTRANSFORM xform, const char* Name);
-
-// Colorant tables
-
-LCMSAPI LPcmsNAMEDCOLORLIST LCMSEXPORT cmsReadColorantTable(cmsHPROFILE hProfile, icTagSignature sig);
-
-// Profile creation
-
-LCMSAPI LCMSBOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hProfile, icTagSignature sig, const void* data);
-
-// Converts a transform to a devicelink profile
-LCMSAPI cmsHPROFILE LCMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, DWORD dwFlags);
-
-// Set the 'save as 8-bit' flag
-LCMSAPI void LCMSEXPORT _cmsSetLUTdepth(cmsHPROFILE hProfile, int depth);
-
-
-// Save profile
-LCMSAPI LCMSBOOL LCMSEXPORT _cmsSaveProfile(cmsHPROFILE hProfile, const char* FileName);
-LCMSAPI LCMSBOOL LCMSEXPORT _cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr,
-                                                                size_t* BytesNeeded);
-
-
-
-// PostScript ColorRenderingDictionary and ColorSpaceArray
-
-LCMSAPI DWORD LCMSEXPORT cmsGetPostScriptCSA(cmsHPROFILE hProfile, int Intent, LPVOID Buffer, DWORD dwBufferLen);
-LCMSAPI DWORD LCMSEXPORT cmsGetPostScriptCRD(cmsHPROFILE hProfile, int Intent, LPVOID Buffer, DWORD dwBufferLen);
-LCMSAPI DWORD LCMSEXPORT cmsGetPostScriptCRDEx(cmsHPROFILE hProfile, int Intent, DWORD dwFlags, LPVOID Buffer, DWORD dwBufferLen);
-
-
-// Error handling
-
-#define LCMS_ERROR_ABORT    0
-#define LCMS_ERROR_SHOW     1
-#define LCMS_ERROR_IGNORE   2
-
-LCMSAPI int LCMSEXPORT cmsErrorAction(int nAction);
-
-#define LCMS_ERRC_WARNING        0x1000
-#define LCMS_ERRC_RECOVERABLE    0x2000
-#define LCMS_ERRC_ABORTED        0x3000
-
-typedef int (* cmsErrorHandlerFunction)(int ErrorCode, const char *ErrorText);
-
-LCMSAPI void LCMSEXPORT cmsSetErrorHandler(cmsErrorHandlerFunction Fn);
-
-
-// LUT manipulation
-
-
-typedef struct _lcms_LUT_struc LUT, FAR* LPLUT; // opaque pointer
-
-LCMSAPI LPLUT  LCMSEXPORT cmsAllocLUT(void);
-LCMSAPI LPLUT  LCMSEXPORT cmsAllocLinearTable(LPLUT NewLUT, LPGAMMATABLE Tables[], int nTable);
-LCMSAPI LPLUT  LCMSEXPORT cmsAlloc3DGrid(LPLUT Lut, int clutPoints, int inputChan, int outputChan);
-LCMSAPI LPLUT  LCMSEXPORT cmsSetMatrixLUT(LPLUT Lut, LPMAT3 M);
-LCMSAPI LPLUT  LCMSEXPORT cmsSetMatrixLUT4(LPLUT Lut, LPMAT3 M, LPVEC3 off, DWORD dwFlags);
-LCMSAPI void   LCMSEXPORT cmsFreeLUT(LPLUT Lut);
-LCMSAPI void   LCMSEXPORT cmsEvalLUT(LPLUT Lut, WORD In[], WORD Out[]);
-LCMSAPI double LCMSEXPORT cmsEvalLUTreverse(LPLUT Lut, WORD Target[], WORD Result[], LPWORD Hint);
-LCMSAPI LPLUT  LCMSEXPORT cmsReadICCLut(cmsHPROFILE hProfile, icTagSignature sig);
-LCMSAPI LPLUT  LCMSEXPORT cmsDupLUT(LPLUT Orig);
-
-
-// LUT Sampling
-
-typedef int (* _cmsSAMPLER)(register WORD In[],
-                            register WORD Out[],
-                            register LPVOID Cargo);
-
-#define SAMPLER_HASTL1      LUT_HASTL1
-#define SAMPLER_HASTL2      LUT_HASTL2
-#define SAMPLER_INSPECT     0x01000000
-
-LCMSAPI int LCMSEXPORT cmsSample3DGrid(LPLUT Lut, _cmsSAMPLER Sampler, LPVOID Cargo, DWORD dwFlags);
-
-// Formatters
-
-typedef unsigned char* (* cmsFORMATTER)(register void* CMMcargo,
-                                        register WORD ToUnroll[],
-                                        register LPBYTE Buffer);
-
-LCMSAPI void LCMSEXPORT cmsSetUserFormatters(cmsHTRANSFORM hTransform, DWORD dwInput,  cmsFORMATTER Input,
-                                                               DWORD dwOutput, cmsFORMATTER Output);
-
-LCMSAPI void LCMSEXPORT cmsGetUserFormatters(cmsHTRANSFORM hTransform,
-                                                               LPDWORD InputFormat, cmsFORMATTER* Input,
-                                                               LPDWORD OutputFormat, cmsFORMATTER* Output);
-
-
-// IT8.7 / CGATS.17-200x handling
-
-LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8Alloc(void);
-LCMSAPI void            LCMSEXPORT cmsIT8Free(LCMSHANDLE IT8);
-
-// Tables
-
-LCMSAPI int             LCMSEXPORT cmsIT8TableCount(LCMSHANDLE IT8);
-LCMSAPI int             LCMSEXPORT cmsIT8SetTable(LCMSHANDLE IT8, int nTable);
-
-// Persistence
-LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8LoadFromFile(const char* cFileName);
-LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8LoadFromMem(void *Ptr, size_t len);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE IT8, const char* cFileName);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded);
-
-// Properties
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetSheetType(LCMSHANDLE hIT8);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* cComment);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* cProp, const char *Str);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char* cSubProp, const char *Val);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer);
-
-
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* cProp);
-LCMSAPI double          LCMSEXPORT cmsIT8GetPropertyDbl(LCMSHANDLE hIT8, const char* cProp);
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char *cSubProp);
-LCMSAPI int             LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE hIT8, const char ***PropertyNames);
-LCMSAPI int             LCMSEXPORT cmsIT8EnumPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char*** SubpropertyNames);
-
-// Datasets
-
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetDataRowCol(LCMSHANDLE IT8, int row, int col);
-LCMSAPI double          LCMSEXPORT cmsIT8GetDataRowColDbl(LCMSHANDLE IT8, int row, int col);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col,
-                                                const char* Val);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col,
-                                                double Val);
-
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetData(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
-
-
-LCMSAPI double          LCMSEXPORT cmsIT8GetDataDbl(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetData(LCMSHANDLE IT8, const char* cPatch,
-                                                const char* cSample,
-                                                const char *Val);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
-                                                const char* cSample,
-                                                double Val);
-
-LCMSAPI int             LCMSEXPORT cmsIT8GetDataFormat(LCMSHANDLE hIT8, const char* cSample);
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE IT8, int n, const char *Sample);
-LCMSAPI int             LCMSEXPORT cmsIT8EnumDataFormat(LCMSHANDLE IT8, char ***SampleNames);
-
-
-LCMSAPI const char*     LCMSEXPORT cmsIT8GetPatchName(LCMSHANDLE hIT8, int nPatch, char* buffer);
-LCMSAPI int             LCMSEXPORT cmsIT8GetPatchByName(LCMSHANDLE hIT8, const char *cSample);
-
-// The LABEL extension
-
-LCMSAPI int             LCMSEXPORT cmsIT8SetTableByLabel(LCMSHANDLE hIT8, const char* cSet, const char* cField, const char* ExpectedType);
-
-LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetIndexColumn(LCMSHANDLE hIT8, const char* cSample);
-
-// Formatter for double
-LCMSAPI void            LCMSEXPORT cmsIT8DefineDblFormat(LCMSHANDLE IT8, const char* Formatter);
-
-
-// ***************************************************************************
-// End of Little cms API From here functions are private
-// You can use them only if using static libraries, and at your own risk of
-// be stripped or changed at futures releases.
-
-#ifndef LCMS_APIONLY
-
-
-// Compatibility with anterior versions-- not needed anymore
-//  -- Morge
-
-LCMSAPI void          LCMSEXPORT cmsLabEncoded2Float(LPcmsCIELab Lab, const WORD wLab[3]);
-LCMSAPI void          LCMSEXPORT cmsLabEncoded2Float4(LPcmsCIELab Lab, const WORD wLab[3]);
-LCMSAPI void          LCMSEXPORT cmsFloat2LabEncoded(WORD wLab[3], const cmsCIELab* Lab);
-LCMSAPI void          LCMSEXPORT cmsFloat2LabEncoded4(WORD wLab[3], const cmsCIELab* Lab);
-LCMSAPI void          LCMSEXPORT cmsXYZEncoded2Float(LPcmsCIEXYZ fxyz, const WORD XYZ[3]);
-LCMSAPI void          LCMSEXPORT cmsFloat2XYZEncoded(WORD XYZ[3], const cmsCIEXYZ* fXYZ);
-
-
-// Profiling Extensions --- Would be removed from API in future revisions
-
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddTextTag(cmsHPROFILE hProfile,  icTagSignature sig, const char* Text);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddXYZTag(cmsHPROFILE hProfile,   icTagSignature sig, const cmsCIEXYZ* XYZ);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddLUTTag(cmsHPROFILE hProfile,   icTagSignature sig, const void* lut);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddGammaTag(cmsHPROFILE hProfile, icTagSignature sig, LPGAMMATABLE TransferFunction);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddChromaticityTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIExyYTRIPLE Chrm);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddSequenceDescriptionTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsSEQ PSeq);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddNamedColorTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddDateTimeTag(cmsHPROFILE hProfile, icTagSignature sig, struct tm *DateTime);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddColorantTableTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc);
-LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddChromaticAdaptationTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* mat);
-
-// --------------------------------------------------------------------------------------------------- Inline functions
-
-// Fast floor conversion logic. Thanks to Sree Kotay and Stuart Nixon
-// note than this only works in the range ..-32767...+32767 because
-// mantissa is interpreted as 15.16 fixed point.
-// The union is to avoid pointer aliasing overoptimization.
-
-LCMS_INLINE int _cmsQuickFloor(double val)
-{
-#ifdef USE_DEFAULT_FLOOR_CONVERSION
-    return (int) floor(val);
-#else
-    const double _lcms_double2fixmagic = 68719476736.0 * 1.5;  // 2^36 * 1.5, (52-16=36) uses limited precision to floor
-    union {
-        double val;
-        int halves[2];
-    } temp;
-
-    temp.val = val + _lcms_double2fixmagic;
-
-
-#ifdef USE_BIG_ENDIAN
-    return temp.halves[1] >> 16;
-#else
-    return temp.halves[0] >> 16;
-#endif
-#endif
-}
-
-
-
-// Clamp with saturation
-
-LCMS_INLINE WORD _cmsClampWord(int in)
-{
-       if (in < 0) return 0;
-       if (in > 0xFFFF) return 0xFFFFU;   // Including marker
-       return (WORD) in;
-}
-
-#ifndef LCMS_USER_ALLOC
-
-// Low-level alloc hook
-
-LCMS_INLINE void* _cmsMalloc(size_t size)
-{
-    if (size > ((size_t) 1024*1024*500)) return NULL;  // Never allow over 500Mb
-    if (size < 0) return NULL;              // Prevent signed size_t exploits
-
-    return (void*) malloc(size);
-}
-
-LCMS_INLINE void* _cmsCalloc(size_t nmemb, size_t size)
-{
-    size_t alloc = nmemb * size;
-
-        if (size == 0) {
-                return _cmsMalloc(0);
-        }
-        if (alloc / size != nmemb) {
-        return NULL;
-    }
-    return _cmsMalloc(alloc);
-}
-
-LCMS_INLINE void _cmsFree(void *Ptr)
-{
-    if (Ptr) free(Ptr);
-}
-
-#endif
-
-// ------------------------------------------------------------------------------------------- end of inline functions
-
-// Signal error from inside lcms code
-
-void cdecl cmsSignalError(int ErrorCode, const char *ErrorText, ...);
-
-// Alignment handling (needed in ReadLUT16 and ReadLUT8)
-
-typedef struct {
-        icS15Fixed16Number a;
-        icUInt16Number     b;
-
-       } _cmsTestAlign16;
-
-#define SIZEOF_UINT16_ALIGNED (sizeof(_cmsTestAlign16) - sizeof(icS15Fixed16Number))
-
-typedef struct {
-        icS15Fixed16Number a;
-        icUInt8Number      b;
-
-       } _cmsTestAlign8;
-
-#define SIZEOF_UINT8_ALIGNED (sizeof(_cmsTestAlign8) - sizeof(icS15Fixed16Number))
-
-
-// Fixed point
-
-
-typedef icInt32Number Fixed32;       // Fixed 15.16 whith sign
-
-#define INT_TO_FIXED(x)         ((x)<<16)
-#define DOUBLE_TO_FIXED(x)      ((Fixed32) ((x)*65536.0+0.5))
-#define FIXED_TO_INT(x)         ((x)>>16)
-#define FIXED_REST_TO_INT(x)    ((x)& 0xFFFFU)
-#define FIXED_TO_DOUBLE(x)      (((double)x)/65536.0)
-#define ROUND_FIXED_TO_INT(x)   (((x)+0x8000)>>16)
-
-
-Fixed32 cdecl FixedMul(Fixed32 a, Fixed32 b);
-Fixed32 cdecl FixedSquare(Fixed32 a);
-
-
-#ifdef USE_INLINE
-
-LCMS_INLINE Fixed32 ToFixedDomain(int a)        { return a + ((a + 0x7fff) / 0xffff); }
-LCMS_INLINE int     FromFixedDomain(Fixed32 a)  { return a - ((a + 0x7fff) >> 16); }
-
-#else
-
-Fixed32 cdecl ToFixedDomain(int a);              // (a * 65536.0 / 65535.0)
-int     cdecl FromFixedDomain(Fixed32 a);        // (a * 65535.0 + .5)
-
-#endif
-
-Fixed32 cdecl FixedLERP(Fixed32 a, Fixed32 l, Fixed32 h);
-WORD    cdecl FixedScale(WORD a, Fixed32 s);
-
-// Vector & Matrix operations. I'm using the notation frequently found in
-// literature. Mostly 'Graphic Gems' samples. Not to be same routines.
-
-// Vector members
-
-#define VX      0
-#define VY      1
-#define VZ      2
-
-typedef struct {                // Fixed 15.16 bits vector
-        Fixed32 n[3];
-        } WVEC3, FAR* LPWVEC3;
-
-typedef struct {                // Matrix (Fixed 15.16)
-        WVEC3 v[3];
-        } WMAT3, FAR* LPWMAT3;
-
-
-
-void      cdecl VEC3init(LPVEC3 r, double x, double y, double z);   // double version
-void      cdecl VEC3initF(LPWVEC3 r, double x, double y, double z); // Fix32 version
-void      cdecl VEC3toFix(LPWVEC3 r, LPVEC3 v);
-void      cdecl VEC3fromFix(LPVEC3 r, LPWVEC3 v);
-void      cdecl VEC3scaleFix(LPWORD r, LPWVEC3 Scale);
-void      cdecl VEC3swap(LPVEC3 a, LPVEC3 b);
-void      cdecl VEC3divK(LPVEC3 r, LPVEC3 v, double d);
-void      cdecl VEC3perK(LPVEC3 r, LPVEC3 v, double d);
-void      cdecl VEC3minus(LPVEC3 r, LPVEC3 a, LPVEC3 b);
-void      cdecl VEC3perComp(LPVEC3 r, LPVEC3 a, LPVEC3 b);
-LCMSBOOL  cdecl VEC3equal(LPWVEC3 a, LPWVEC3 b, double Tolerance);
-LCMSBOOL  cdecl VEC3equalF(LPVEC3 a, LPVEC3 b, double Tolerance);
-void      cdecl VEC3scaleAndCut(LPWVEC3 r, LPVEC3 v, double d);
-void      cdecl VEC3cross(LPVEC3 r, LPVEC3 u, LPVEC3 v);
-void      cdecl VEC3saturate(LPVEC3 v);
-double    cdecl VEC3distance(LPVEC3 a, LPVEC3 b);
-double    cdecl VEC3length(LPVEC3 a);
-
-void      cdecl MAT3identity(LPMAT3 a);
-void      cdecl MAT3per(LPMAT3 r, LPMAT3 a, LPMAT3 b);
-void      cdecl MAT3perK(LPMAT3 r, LPMAT3 v, double d);
-int       cdecl MAT3inverse(LPMAT3 a, LPMAT3 b);
-LCMSBOOL  cdecl MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b);
-double    cdecl MAT3det(LPMAT3 m);
-void      cdecl MAT3eval(LPVEC3 r, LPMAT3 a, LPVEC3 v);
-void      cdecl MAT3toFix(LPWMAT3 r, LPMAT3 v);
-void      cdecl MAT3fromFix(LPMAT3 r, LPWMAT3 v);
-void      cdecl MAT3evalW(LPWVEC3 r, LPWMAT3 a, LPWVEC3 v);
-LCMSBOOL  cdecl MAT3isIdentity(LPWMAT3 a, double Tolerance);
-void      cdecl MAT3scaleAndCut(LPWMAT3 r, LPMAT3 v, double d);
-
-// Is a table linear?
-
-int  cdecl cmsIsLinear(WORD Table[], int nEntries);
-
-// I hold this structures describing domain
-// details mainly for optimization purposes.
-
-struct _lcms_l16params_struc;
-
-typedef void (* _cms3DLERP)(WORD Input[],
-                            WORD Output[],
-                            WORD LutTable[],
-                            struct _lcms_l16params_struc* p);
-
-
-
-typedef struct _lcms_l8opt_struc {      // Used on 8 bit interpolations
-
-              unsigned int X0[256], Y0[256], Z0[256];
-              WORD rx[256], ry[256], rz[256];
-
-        } L8PARAMS, FAR* LPL8PARAMS;
-
-typedef struct _lcms_l16params_struc {    // Used on 16 bits interpolations
-
-               int nSamples;       // Valid on all kinds of tables
-               int nInputs;        // != 1 only in 3D interpolation
-               int nOutputs;       // != 1 only in 3D interpolation
-
-               WORD Domain;
-
-               int opta1, opta2;
-               int opta3, opta4;     // Optimization for 3D LUT
-               int opta5, opta6;
-               int opta7, opta8;
-
-               _cms3DLERP Interp3D; // The interpolation routine
-
-                LPL8PARAMS p8;      // Points to some tables for 8-bit speedup
-
-               } L16PARAMS, *LPL16PARAMS;
-
-
-void    cdecl cmsCalcL16Params(int nSamples, LPL16PARAMS p);
-void    cdecl cmsCalcCLUT16Params(int nSamples, int InputChan, int OutputChan, LPL16PARAMS p);
-void    cdecl cmsCalcCLUT16ParamsEx(int nSamples, int InputChan, int OutputChan,
-                                            LCMSBOOL lUseTetrahedral, LPL16PARAMS p);
-
-WORD    cdecl cmsLinearInterpLUT16(WORD Value, WORD LutTable[], LPL16PARAMS p);
-Fixed32 cdecl cmsLinearInterpFixed(WORD Value1, WORD LutTable[], LPL16PARAMS p);
-WORD    cdecl cmsReverseLinearInterpLUT16(WORD Value, WORD LutTable[], LPL16PARAMS p);
-
-void cdecl cmsTrilinearInterp16(WORD Input[],
-                                WORD Output[],
-                                WORD LutTable[],
-                                LPL16PARAMS p);
-
-void cdecl cmsTetrahedralInterp16(WORD Input[],
-                                  WORD Output[],
-                                  WORD LutTable[], LPL16PARAMS p);
-
-void cdecl cmsTetrahedralInterp8(WORD Input[],
-                                 WORD Output[],
-                                 WORD LutTable[],  LPL16PARAMS p);
-
-// LUT handling
-
-#define LUT_HASMATRIX       0x0001        // Do-op Flags
-#define LUT_HASTL1          0x0002
-#define LUT_HASTL2          0x0008
-#define LUT_HAS3DGRID       0x0010
-
-// New in rev 4.0 of ICC spec
-
-#define LUT_HASMATRIX3     0x0020   // Matrix + offset for LutAToB
-#define LUT_HASMATRIX4     0x0040   // Matrix + offset for LutBToA
-
-#define LUT_HASTL3         0x0100   // '3' curves for LutAToB
-#define LUT_HASTL4         0x0200   // '4' curves for LutBToA
-
-// V4 emulation
-
-#define LUT_V4_OUTPUT_EMULATE_V2    0x10000     // Is a V4 output LUT, emulating V2
-#define LUT_V4_INPUT_EMULATE_V2     0x20000     // Is a V4 input LUT, emulating V2
-#define LUT_V2_OUTPUT_EMULATE_V4    0x40000     // Is a V2 output LUT, emulating V4
-#define LUT_V2_INPUT_EMULATE_V4     0x80000     // Is a V2 input LUT, emulating V4
-
-
-struct _lcms_LUT_struc {
-
-               DWORD wFlags;
-               WMAT3 Matrix;                    // 15fixed16 matrix
-
-               unsigned int InputChan;
-               unsigned int OutputChan;
-               unsigned int InputEntries;
-               unsigned int OutputEntries;
-               unsigned int cLutPoints;
-
-
-               LPWORD L1[MAXCHANNELS];          // First linearization
-               LPWORD L2[MAXCHANNELS];          // Last linearization
-
-               LPWORD T;                        // 3D CLUT
-               unsigned int Tsize;              // CLUT size in bytes
-
-              // Parameters & Optimizations
-
-               L16PARAMS In16params;
-               L16PARAMS Out16params;
-               L16PARAMS CLut16params;
-
-               int Intent;                       // Accomplished intent
-
-               // New for Rev 4.0 of spec (reserved)
-
-               WMAT3 Mat3;
-               WVEC3 Ofs3;
-               LPWORD L3[MAXCHANNELS];
-               L16PARAMS L3params;
-               unsigned int L3Entries;
-
-               WMAT3 Mat4;
-               WVEC3 Ofs4;
-               LPWORD L4[MAXCHANNELS];
-               L16PARAMS L4params;
-               unsigned int L4Entries;
-
-               // Gray axes fixup. Only on v2 8-bit Lab LUT
-
-               LCMSBOOL FixGrayAxes;
-
-
-               // Parameters used for curve creation
-
-               LCMSGAMMAPARAMS LCurvesSeed[4][MAXCHANNELS];
-
-
-               }; // LUT, FAR* LPLUT;
-
-
-LCMSBOOL         cdecl _cmsSmoothEndpoints(LPWORD Table, int nEntries);
-
-
-// CRC of gamma tables
-
-unsigned int _cmsCrc32OfGammaTable(LPGAMMATABLE Table);
-
-// Sampled curves
-
-LPSAMPLEDCURVE cdecl cmsAllocSampledCurve(int nItems);
-void           cdecl cmsFreeSampledCurve(LPSAMPLEDCURVE p);
-LPSAMPLEDCURVE cdecl cmsDupSampledCurve(LPSAMPLEDCURVE p);
-
-LPSAMPLEDCURVE cdecl cmsConvertGammaToSampledCurve(LPGAMMATABLE Gamma, int nPoints);
-LPGAMMATABLE   cdecl cmsConvertSampledCurveToGamma(LPSAMPLEDCURVE Sampled, double Max);
-
-void           cdecl cmsEndpointsOfSampledCurve(LPSAMPLEDCURVE p, double* Min, double* Max);
-void           cdecl cmsClampSampledCurve(LPSAMPLEDCURVE p, double Min, double Max);
-LCMSBOOL       cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
-void           cdecl cmsRescaleSampledCurve(LPSAMPLEDCURVE p, double Min, double Max, int nPoints);
-
-LPSAMPLEDCURVE cdecl cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints);
-
-// Shaper/Matrix handling
-
-#define MATSHAPER_HASMATRIX        0x0001        // Do-ops flags
-#define MATSHAPER_HASSHAPER        0x0002
-#define MATSHAPER_INPUT            0x0004        // Behaviour
-#define MATSHAPER_OUTPUT           0x0008
-#define MATSHAPER_HASINPSHAPER     0x0010
-#define MATSHAPER_ALLSMELTED       (MATSHAPER_INPUT|MATSHAPER_OUTPUT)
-
-
-typedef struct {
-               DWORD dwFlags;
-
-               WMAT3 Matrix;
-
-               L16PARAMS p16;       // Primary curve
-               LPWORD L[3];
-
-               L16PARAMS p2_16;     // Secondary curve (used as input in smelted ones)
-               LPWORD L2[3];
-
-               } MATSHAPER, FAR* LPMATSHAPER;
-
-LPMATSHAPER cdecl cmsAllocMatShaper(LPMAT3 matrix, LPGAMMATABLE Shaper[], DWORD Behaviour);
-LPMATSHAPER cdecl cmsAllocMatShaper2(LPMAT3 matrix, LPGAMMATABLE In[], LPGAMMATABLE Out[], DWORD Behaviour);
-
-void        cdecl cmsFreeMatShaper(LPMATSHAPER MatShaper);
-void        cdecl cmsEvalMatShaper(LPMATSHAPER MatShaper, WORD In[], WORD Out[]);
-
-LCMSBOOL    cdecl cmsReadICCMatrixRGB2XYZ(LPMAT3 r, cmsHPROFILE hProfile);
-
-LPMATSHAPER cdecl cmsBuildInputMatrixShaper(cmsHPROFILE InputProfile);
-LPMATSHAPER cdecl cmsBuildOutputMatrixShaper(cmsHPROFILE OutputProfile);
-
-
-
-// White Point & Primary chromas handling
-LCMSBOOL cdecl cmsAdaptationMatrix(LPMAT3 r, LPMAT3 ConeMatrix, LPcmsCIEXYZ FromIll, LPcmsCIEXYZ ToIll);
-LCMSBOOL cdecl cmsAdaptMatrixToD50(LPMAT3 r, LPcmsCIExyY SourceWhitePt);
-LCMSBOOL cdecl cmsAdaptMatrixFromD50(LPMAT3 r, LPcmsCIExyY DestWhitePt);
-
-LCMSBOOL cdecl cmsReadChromaticAdaptationMatrix(LPMAT3 r, cmsHPROFILE hProfile);
-
-// Inter-PCS conversion routines. They assume D50 as white point.
-void cdecl cmsXYZ2LabEncoded(WORD XYZ[3], WORD Lab[3]);
-void cdecl cmsLab2XYZEncoded(WORD Lab[3], WORD XYZ[3]);
-
-// Retrieve text representation of WP
-void cdecl _cmsIdentifyWhitePoint(char *Buffer, LPcmsCIEXYZ WhitePt);
-
-// Quantize to WORD in a (MaxSamples - 1) domain
-WORD cdecl _cmsQuantizeVal(double i, int MaxSamples);
-
-LPcmsNAMEDCOLORLIST  cdecl cmsAllocNamedColorList(int n);
-int                  cdecl cmsReadICCnamedColorList(cmsHTRANSFORM xform, cmsHPROFILE hProfile, icTagSignature sig);
-void                 cdecl cmsFreeNamedColorList(LPcmsNAMEDCOLORLIST List);
-LCMSBOOL             cdecl cmsAppendNamedColor(cmsHTRANSFORM xform, const char* Name, WORD PCS[3], WORD Colorant[MAXCHANNELS]);
-
-
-// I/O
-
-#define MAX_TABLE_TAG       100
-
-// This is the internal struct holding profile details.
-
-typedef struct _lcms_iccprofile_struct {
-
-              void* stream;   // Associated stream. If NULL,
-                              // tags are supposed to be in
-                              // memory rather than in a file.
-
-               // Only most important items found in ICC profile
-
-               icProfileClassSignature DeviceClass;
-               icColorSpaceSignature   ColorSpace;
-               icColorSpaceSignature   PCS;
-               icRenderingIntent       RenderingIntent;
-               icUInt32Number          flags;
-               icUInt32Number          attributes;
-               cmsCIEXYZ               Illuminant;
-
-               // Additions for V4 profiles
-
-               icUInt32Number          Version;
-               MAT3                    ChromaticAdaptation;
-               cmsCIEXYZ               MediaWhitePoint;
-               cmsCIEXYZ               MediaBlackPoint;
-               BYTE                    ProfileID[16];
-
-
-               // Dictionary
-
-               icInt32Number           TagCount;
-               icTagSignature          TagNames[MAX_TABLE_TAG];
-               size_t                  TagSizes[MAX_TABLE_TAG];
-               size_t                  TagOffsets[MAX_TABLE_TAG];
-               LPVOID                  TagPtrs[MAX_TABLE_TAG];
-
-               char                    PhysicalFile[MAX_PATH];
-
-               LCMSBOOL                IsWrite;
-               LCMSBOOL                SaveAs8Bits;
-
-               struct tm               Created;
-
-               // I/O handlers
-
-               size_t   (* Read)(void *buffer, size_t size, size_t count, struct _lcms_iccprofile_struct* Icc);
-
-               LCMSBOOL (* Seek)(struct _lcms_iccprofile_struct* Icc, size_t offset);
-               LCMSBOOL (* Close)(struct _lcms_iccprofile_struct* Icc);
-               size_t   (* Tell)(struct _lcms_iccprofile_struct* Icc);
-               LCMSBOOL  (* Grow)(struct _lcms_iccprofile_struct* Icc, size_t amount);
-
-               // Writting
-
-               LCMSBOOL (* Write)(struct _lcms_iccprofile_struct* Icc, size_t size, LPVOID Ptr);
-
-               size_t UsedSpace;
-
-
-              } LCMSICCPROFILE, FAR* LPLCMSICCPROFILE;
-
-
-// Create an empty template for virtual profiles
-cmsHPROFILE cdecl _cmsCreateProfilePlaceholder(void);
-
-// Search into tag dictionary
-icInt32Number cdecl _cmsSearchTag(LPLCMSICCPROFILE Profile, icTagSignature sig, LCMSBOOL lSignalError);
-
-// Search for a particular tag, replace if found or add new one else
-LPVOID _cmsInitTag(LPLCMSICCPROFILE Icc, icTagSignature sig, size_t size, const void* Init);
-
-
-LPLCMSICCPROFILE cdecl _cmsCreateProfileFromFilePlaceholder(const char* FileName);
-LPLCMSICCPROFILE cdecl _cmsCreateProfileFromMemPlaceholder(LPVOID MemPtr, DWORD dwSize);
-
-void _cmsSetSaveToDisk(LPLCMSICCPROFILE Icc, const char* FileName);
-void _cmsSetSaveToMemory(LPLCMSICCPROFILE Icc, LPVOID MemPtr, size_t dwSize);
-
-
-
-// These macros unpack format specifiers into integers
-
-#define T_DITHER(s)           (((s)>>22)&1)
-#define T_COLORSPACE(s)       (((s)>>16)&31)
-#define T_SWAPFIRST(s)        (((s)>>14)&1)
-#define T_FLAVOR(s)           (((s)>>13)&1)
-#define T_PLANAR(p)           (((p)>>12)&1)
-#define T_ENDIAN16(e)         (((e)>>11)&1)
-#define T_DOSWAP(e)           (((e)>>10)&1)
-#define T_EXTRA(e)            (((e)>>7)&7)
-#define T_CHANNELS(c)         (((c)>>3)&15)
-#define T_BYTES(b)            ((b)&7)
-
-
-
-// Internal XFORM struct
-struct _cmstransform_struct;
-
-// Full xform
-typedef void (* _cmsCOLORCALLBACKFN)(struct _cmstransform_struct *Transform,
-                               LPVOID InputBuffer,
-                               LPVOID OutputBuffer, unsigned int Size);
-
-// intermediate pass, from WORD[] to WORD[]
-
-typedef void   (* _cmsADJFN)(WORD In[], WORD Out[], LPWMAT3 m, LPWVEC3 b);
-
-typedef void   (* _cmsTRANSFN)(struct _cmstransform_struct *Transform,
-                               WORD In[], WORD Out[]);
-
-typedef void   (* _cmsCNVRT)(WORD In[], WORD Out[]);
-
-typedef LPBYTE (* _cmsFIXFN)(register struct _cmstransform_struct *info,
-                             register WORD ToUnroll[],
-                             register LPBYTE Buffer);
-
-
-
-// Transformation
-typedef struct _cmstransform_struct {
-
-                    // Keep formats for further reference
-                    DWORD InputFormat, OutputFormat;
-
-                    DWORD StrideIn, StrideOut;      // Planar support
-
-                    int Intent, ProofIntent;
-                    int DoGamutCheck;
-
-
-                    cmsHPROFILE InputProfile;
-                    cmsHPROFILE OutputProfile;
-                    cmsHPROFILE PreviewProfile;
-
-                    icColorSpaceSignature EntryColorSpace;
-                    icColorSpaceSignature ExitColorSpace;
-
-                    DWORD dwOriginalFlags;      // Flags as specified by user
-
-                    WMAT3 m1, m2;       // Matrix holding inter PCS operation
-                    WVEC3 of1, of2;     // Offset terms
-
-                    _cmsCOLORCALLBACKFN xform;
-
-                    // Steps in xFORM
-
-                    _cmsFIXFN   FromInput;
-                    _cmsTRANSFN FromDevice;
-                    _cmsADJFN   Stage1;
-                    _cmsADJFN   Stage2;
-                    _cmsTRANSFN ToDevice;
-                    _cmsFIXFN   ToOutput;
-
-                    // LUTs
-
-                    LPLUT Device2PCS;
-                    LPLUT PCS2Device;
-                    LPLUT Gamut;         // Gamut check
-                    LPLUT Preview;       // Preview (Proof)
-
-                    LPLUT DeviceLink;    // Precalculated grid - device link profile
-                    LPLUT GamutCheck;    // Precalculated device -> gamut check
-
-                    // Matrix/Shapers
-
-                    LPMATSHAPER InMatShaper;
-                    LPMATSHAPER OutMatShaper;
-                    LPMATSHAPER SmeltMatShaper;
-
-                    // Phase of Lab/XYZ, Abs/Rel
-
-                    int Phase1, Phase2, Phase3;
-
-                    // Named color table
-
-                    LPcmsNAMEDCOLORLIST NamedColorList;
-
-                    // Flag for transform involving v4 profiles
-
-                    LCMSBOOL lInputV4Lab, lOutputV4Lab;
-
-
-                    // 1-pixel cache
-
-                    WORD CacheIn[MAXCHANNELS];
-                    WORD CacheOut[MAXCHANNELS];
-
-                    double AdaptationState; // Figure for v4 incomplete state of adaptation
-
-                    LCMS_RWLOCK_T rwlock;
-
-                   } _cmsTRANSFORM,FAR *_LPcmsTRANSFORM;
-
-
-
-// Packing & Unpacking
-
-_cmsFIXFN cdecl _cmsIdentifyInputFormat(_LPcmsTRANSFORM xform,  DWORD dwInput);
-_cmsFIXFN cdecl _cmsIdentifyOutputFormat(_LPcmsTRANSFORM xform, DWORD dwOutput);
-
-
-// Conversion
-
-#define XYZRel       0
-#define LabRel       1
-
-
-int cdecl cmsChooseCnvrt(int Absolute,
-                 int Phase1, LPcmsCIEXYZ BlackPointIn,
-                             LPcmsCIEXYZ WhitePointIn,
-                             LPcmsCIEXYZ IlluminantIn,
-                             LPMAT3 ChromaticAdaptationMatrixIn,
-
-                 int Phase2, LPcmsCIEXYZ BlackPointOut,
-                             LPcmsCIEXYZ WhitePointOut,
-                             LPcmsCIEXYZ IlluminantOut,
-                             LPMAT3 ChromaticAdaptationMatrixOut,
-                 int DoBPC,
-                 double AdaptationState,
-                 _cmsADJFN *fn1,
-                 LPWMAT3 wm, LPWVEC3 wof);
-
-
-
-// Clamping & Gamut handling
-
-LCMSBOOL cdecl   _cmsEndPointsBySpace(icColorSpaceSignature Space,
-                            WORD **White, WORD **Black, int *nOutputs);
-
-WORD * cdecl _cmsWhiteBySpace(icColorSpaceSignature Space);
-
-
-
-WORD cdecl Clamp_L(Fixed32 in);
-WORD cdecl Clamp_ab(Fixed32 in);
-
-// Detection of black point
-
-#define LCMS_BPFLAGS_D50_ADAPTED    0x0001
-
-int cdecl cmsDetectBlackPoint(LPcmsCIEXYZ BlackPoint, cmsHPROFILE hProfile, int Intent, DWORD dwFlags);
-
-// choose reasonable resolution
-int cdecl _cmsReasonableGridpointsByColorspace(icColorSpaceSignature Colorspace, DWORD dwFlags);
-
-// Precalculate device link
-LPLUT cdecl _cmsPrecalculateDeviceLink(cmsHTRANSFORM h, DWORD dwFlags);
-
-// Precalculate black preserving device link
-LPLUT _cmsPrecalculateBlackPreservingDeviceLink(cmsHTRANSFORM hCMYK2CMYK, DWORD dwFlags);
-
-// Precalculate gamut check
-LPLUT cdecl _cmsPrecalculateGamutCheck(cmsHTRANSFORM h);
-
-// Hot fixes bad profiles
-LCMSBOOL cdecl _cmsFixWhiteMisalignment(_LPcmsTRANSFORM p);
-
-// Marks LUT as 8 bit on input
-LPLUT cdecl _cmsBlessLUT8(LPLUT Lut);
-
-// Compute gamut boundary
-LPLUT cdecl _cmsComputeGamutLUT(cmsHPROFILE hProfile, int Intent);
-
-// Compute softproof
-LPLUT cdecl _cmsComputeSoftProofLUT(cmsHPROFILE hProfile, int nIntent);
-
-// Find a suitable prelinearization tables, matching the given transform
-void cdecl _cmsComputePrelinearizationTablesFromXFORM(cmsHTRANSFORM h[], int nTransforms, LPLUT Grid);
-
-
-// Build a tone curve for K->K' if possible (only works on CMYK)
-LPGAMMATABLE _cmsBuildKToneCurve(cmsHTRANSFORM hCMYK2CMYK, int nPoints);
-
-// Validates a LUT
-LCMSBOOL cdecl _cmsValidateLUT(LPLUT NewLUT);
-
-
-// These are two VITAL macros, from converting between 8 and 16 bit
-// representation.
-
-#define RGB_8_TO_16(rgb) (WORD) ((((WORD) (rgb)) << 8)|(rgb))
-#define RGB_16_TO_8(rgb) (BYTE) ((((rgb) * 65281 + 8388608) >> 24) & 0xFF)
-
-
-#endif  // LCMS_APIONLY
-
-
-#define __cms_H
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/native/sun/java2d/cmm/lcms/lcms2.h	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,1751 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+// Version 2.0
+//
+
+#ifndef _lcms2_H
+
+// ********** Configuration toggles ****************************************
+
+// Uncomment this one if you are using big endian machines
+// #define CMS_USE_BIG_ENDIAN   1
+
+// Uncomment this one if your compiler/machine does NOT support the
+// "long long" type.
+// #define CMS_DONT_USE_INT64        1
+
+// Uncomment this if your compiler doesn't work with fast floor function
+// #define CMS_DONT_USE_FAST_FLOOR 1
+
+// Uncomment this line if your system does not support multithreading
+#define CMS_DONT_USE_PTHREADS    1
+
+// Uncomment this line if you want lcms to use the black point tag in profile,
+// if commented, lcms will compute the black point by its own.
+// It is safer to leave it commented out
+// #define CMS_USE_PROFILE_BLACK_POINT_TAG    1
+
+// Uncomment this line if you are compiling as C++ and want a C++ API
+// #define CMS_USE_CPP_API
+
+// Uncomment this line if you need strict CGATS syntax. Makes CGATS files to
+// require "KEYWORD" on undefined identifiers, keep it comented out unless needed
+// #define CMS_STRICT_CGATS  1
+
+// ********** End of configuration toggles ******************************
+
+// Needed for streams
+#include <stdio.h>
+
+// Needed for portability (C99 per 7.1.2)
+#include <limits.h>
+#include <time.h>
+#include <stddef.h>
+
+#ifndef CMS_USE_CPP_API
+#   ifdef __cplusplus
+extern "C" {
+#   endif
+#endif
+
+// Version/release
+#define LCMS_VERSION        2000
+
+// I will give the chance of redefining basic types for compilers that are not fully C99 compliant
+#ifndef CMS_BASIC_TYPES_ALREADY_DEFINED
+
+// Base types
+typedef unsigned char        cmsUInt8Number;   // That is guaranteed by the C99 spec
+typedef signed char          cmsInt8Number;    // That is guaranteed by the C99 spec
+
+// IEEE float storage numbers
+typedef float                cmsFloat32Number;
+typedef double               cmsFloat64Number;
+
+// 16-bit base types
+#if (USHRT_MAX == 65535U)
+ typedef unsigned short      cmsUInt16Number;
+#elif (UINT_MAX == 65535U)
+ typedef unsigned int        cmsUInt16Number;
+#else
+#  error "Unable to find 16 bits unsigned type, unsupported compiler"
+#endif
+
+#if (SHRT_MAX == 32767)
+  typedef  short             cmsInt16Number;
+#elif (INT_MAX == 32767)
+  typedef  int               cmsInt16Number;
+#else
+#  error "Unable to find 16 bits signed type, unsupported compiler"
+#endif
+
+// 32-bit base type
+#if (UINT_MAX == 4294967295U)
+ typedef unsigned int        cmsUInt32Number;
+#elif (ULONG_MAX == 4294967295U)
+ typedef unsigned long       cmsUInt32Number;
+#else
+#  error "Unable to find 32 bit unsigned type, unsupported compiler"
+#endif
+
+#if (INT_MAX == +2147483647)
+ typedef  int                cmsInt32Number;
+#elif (LONG_MAX == +2147483647)
+ typedef  long               cmsInt32Number;
+#else
+#  error "Unable to find 32 bit signed type, unsupported compiler"
+#endif
+
+// 64-bit base types
+#ifndef CMS_DONT_USE_INT64
+#  if (ULONG_MAX  == 18446744073709551615U)
+    typedef unsigned long   cmsUInt64Number;
+#  elif (ULLONG_MAX == 18446744073709551615U)
+      typedef unsigned long long   cmsUInt64Number;
+#  else
+#     define CMS_DONT_USE_INT64 1
+#  endif
+#  if (LONG_MAX == +9223372036854775807)
+      typedef  long          cmsInt64Number;
+#  elif (LLONG_MAX == +9223372036854775807)
+      typedef  long long     cmsInt64Number;
+#  else
+#     define CMS_DONT_USE_INT64 1
+#  endif
+#endif
+#endif
+
+// In the case 64 bit numbers are not supported by the compiler
+#ifdef CMS_DONT_USE_INT64
+    typedef cmsUInt32Number      cmsUInt64Number[2];
+    typedef cmsInt32Number       cmsInt64Number[2];
+#endif
+
+// Derivative types
+typedef cmsUInt32Number      cmsSignature;
+typedef cmsUInt16Number      cmsU8Fixed8Number;
+typedef cmsInt32Number       cmsS15Fixed16Number;
+typedef cmsUInt32Number      cmsU16Fixed16Number;
+
+// Boolean type, which will be using the native integer
+typedef int                  cmsBool;
+
+// Try to detect windows
+#if defined (_WIN32) || defined(_WIN64) || defined(WIN32) || defined(_WIN32_)
+#  define CMS_IS_WINDOWS_ 1
+#endif
+
+#ifdef _MSC_VER
+#  define CMS_IS_WINDOWS_ 1
+#endif
+
+#ifdef __BORLANDC__
+#  define CMS_IS_WINDOWS_ 1
+#endif
+
+// Try to detect big endian platforms. This list can be endless, so only some checks are performed over here.
+// you can pass this toggle to the compiler by using -DCMS_USE_BIG_ENDIAN or something similar
+
+#if defined(_HOST_BIG_ENDIAN) || defined(__BIG_ENDIAN__) || defined(WORDS_BIGENDIAN)
+#   define CMS_USE_BIG_ENDIAN      1
+#endif
+
+#if defined(__sgi__) || defined(__sgi) || defined(__powerpc__) || defined(sparc)
+#   define CMS_USE_BIG_ENDIAN      1
+#endif
+
+#if defined(__ppc__) || defined(__s390__) || defined(__s390x__)
+#   define CMS_USE_BIG_ENDIAN   1
+#endif
+
+#ifdef TARGET_CPU_PPC
+#   define CMS_USE_BIG_ENDIAN   1
+#endif
+
+#ifdef macintosh
+# ifndef __LITTLE_ENDIAN__
+#   define CMS_USE_BIG_ENDIAN      1
+# endif
+#endif
+
+// Calling convention -- this is hardly platform and compiler dependent
+#ifdef CMS_IS_WINDOWS_
+#  if defined(CMS_DLL) || defined(CMS_DLL_BUILD)
+#     ifdef __BORLANDC__
+#        define CMSEXPORT       __stdcall _export
+#        define CMSAPI
+#     else
+#        define CMSEXPORT      _stdcall
+#        ifdef CMS_DLL_BUILD
+#            define CMSAPI    __declspec(dllexport)
+#        else
+#           define CMSAPI     __declspec(dllimport)
+#       endif
+#     endif
+#  else
+#       define CMSEXPORT
+#       define CMSAPI
+#  endif
+#else
+# define CMSEXPORT
+# define CMSAPI
+#endif
+
+// Some common definitions
+#define cmsMAX_PATH     256
+
+#ifndef FALSE
+#       define FALSE 0
+#endif
+#ifndef TRUE
+#       define TRUE  1
+#endif
+
+// D50 XYZ normalized to Y=1.0
+#define cmsD50X             0.9642
+#define cmsD50Y             1.0
+#define cmsD50Z             0.8249
+
+// V4 perceptual black
+#define cmsPERCEPTUAL_BLACK_X  0.00336
+#define cmsPERCEPTUAL_BLACK_Y  0.0034731
+#define cmsPERCEPTUAL_BLACK_Z  0.00287
+
+// Definitions in ICC spec
+#define cmsMagicNumber      0x61637370     // 'acsp'
+#define lcmsSignature       0x6c636d73     // 'lcms'
+
+
+// Base ICC type definitions
+typedef enum {
+    cmsSigChromaticityType                  = 0x6368726D,  // 'chrm'
+    cmsSigColorantOrderType                 = 0x636C726F,  // 'clro'
+    cmsSigColorantTableType                 = 0x636C7274,  // 'clrt'
+    cmsSigCrdInfoType                       = 0x63726469,  // 'crdi'
+    cmsSigCurveType                         = 0x63757276,  // 'curv'
+    cmsSigDataType                          = 0x64617461,  // 'data'
+    cmsSigDateTimeType                      = 0x6474696D,  // 'dtim'
+    cmsSigDeviceSettingsType                = 0x64657673,  // 'devs'
+    cmsSigLut16Type                         = 0x6d667432,  // 'mft2'
+    cmsSigLut8Type                          = 0x6d667431,  // 'mft1'
+    cmsSigLutAtoBType                       = 0x6d414220,  // 'mAB '
+    cmsSigLutBtoAType                       = 0x6d424120,  // 'mBA '
+    cmsSigMeasurementType                   = 0x6D656173,  // 'meas'
+    cmsSigMultiLocalizedUnicodeType         = 0x6D6C7563,  // 'mluc'
+    cmsSigMultiProcessElementType           = 0x6D706574,  // 'mpet'
+    cmsSigNamedColorType                    = 0x6E636f6C,  // 'ncol' -- DEPRECATED!
+    cmsSigNamedColor2Type                   = 0x6E636C32,  // 'ncl2'
+    cmsSigParametricCurveType               = 0x70617261,  // 'para'
+    cmsSigProfileSequenceDescType           = 0x70736571,  // 'pseq'
+    cmsSigProfileSequenceIdType             = 0x70736964,  // 'psid'
+    cmsSigResponseCurveSet16Type            = 0x72637332,  // 'rcs2'
+    cmsSigS15Fixed16ArrayType               = 0x73663332,  // 'sf32'
+    cmsSigScreeningType                     = 0x7363726E,  // 'scrn'
+    cmsSigSignatureType                     = 0x73696720,  // 'sig '
+    cmsSigTextType                          = 0x74657874,  // 'text'
+    cmsSigTextDescriptionType               = 0x64657363,  // 'desc'
+    cmsSigU16Fixed16ArrayType               = 0x75663332,  // 'uf32'
+    cmsSigUcrBgType                         = 0x62666420,  // 'bfd '
+    cmsSigUInt16ArrayType                   = 0x75693136,  // 'ui16'
+    cmsSigUInt32ArrayType                   = 0x75693332,  // 'ui32'
+    cmsSigUInt64ArrayType                   = 0x75693634,  // 'ui64'
+    cmsSigUInt8ArrayType                    = 0x75693038,  // 'ui08'
+    cmsSigViewingConditionsType             = 0x76696577,  // 'view'
+    cmsSigXYZType                           = 0x58595A20,  // 'XYZ '
+    cmsSigVcgtType                          = 0x76636774   // 'vcgt'
+
+} cmsTagTypeSignature;
+
+// Base ICC tag definitions
+typedef enum {
+    cmsSigAToB0Tag                          = 0x41324230,  // 'A2B0'
+    cmsSigAToB1Tag                          = 0x41324231,  // 'A2B1'
+    cmsSigAToB2Tag                          = 0x41324232,  // 'A2B2'
+    cmsSigBlueColorantTag                   = 0x6258595A,  // 'bXYZ'
+    cmsSigBlueMatrixColumnTag               = 0x6258595A,  // 'bXYZ'
+    cmsSigBlueTRCTag                        = 0x62545243,  // 'bTRC'
+    cmsSigBToA0Tag                          = 0x42324130,  // 'B2A0'
+    cmsSigBToA1Tag                          = 0x42324131,  // 'B2A1'
+    cmsSigBToA2Tag                          = 0x42324132,  // 'B2A2'
+    cmsSigCalibrationDateTimeTag            = 0x63616C74,  // 'calt'
+    cmsSigCharTargetTag                     = 0x74617267,  // 'targ'
+    cmsSigChromaticAdaptationTag            = 0x63686164,  // 'chad'
+    cmsSigChromaticityTag                   = 0x6368726D,  // 'chrm'
+    cmsSigColorantOrderTag                  = 0x636C726F,  // 'clro'
+    cmsSigColorantTableTag                  = 0x636C7274,  // 'clrt'
+    cmsSigColorantTableOutTag               = 0x636C6F74,  // 'clot'
+    cmsSigColorimetricIntentImageStateTag   = 0x63696973,  // 'ciis'
+    cmsSigCopyrightTag                      = 0x63707274,  // 'cprt'
+    cmsSigCrdInfoTag                        = 0x63726469,  // 'crdi'
+    cmsSigDataTag                           = 0x64617461,  // 'data'
+    cmsSigDateTimeTag                       = 0x6474696D,  // 'dtim'
+    cmsSigDeviceMfgDescTag                  = 0x646D6E64,  // 'dmnd'
+    cmsSigDeviceModelDescTag                = 0x646D6464,  // 'dmdd'
+    cmsSigDeviceSettingsTag                 = 0x64657673,  // 'devs'
+    cmsSigDToB0Tag                          = 0x44324230,  // 'D2B0'
+    cmsSigDToB1Tag                          = 0x44324231,  // 'D2B1'
+    cmsSigDToB2Tag                          = 0x44324232,  // 'D2B2'
+    cmsSigDToB3Tag                          = 0x44324233,  // 'D2B3'
+    cmsSigBToD0Tag                          = 0x42324430,  // 'B2D0'
+    cmsSigBToD1Tag                          = 0x42324431,  // 'B2D1'
+    cmsSigBToD2Tag                          = 0x42324432,  // 'B2D2'
+    cmsSigBToD3Tag                          = 0x42324433,  // 'B2D3'
+    cmsSigGamutTag                          = 0x67616D74,  // 'gamt'
+    cmsSigGrayTRCTag                        = 0x6b545243,  // 'kTRC'
+    cmsSigGreenColorantTag                  = 0x6758595A,  // 'gXYZ'
+    cmsSigGreenMatrixColumnTag              = 0x6758595A,  // 'gXYZ'
+    cmsSigGreenTRCTag                       = 0x67545243,  // 'gTRC'
+    cmsSigLuminanceTag                      = 0x6C756d69,  // 'lumi'
+    cmsSigMeasurementTag                    = 0x6D656173,  // 'meas'
+    cmsSigMediaBlackPointTag                = 0x626B7074,  // 'bkpt'
+    cmsSigMediaWhitePointTag                = 0x77747074,  // 'wtpt'
+    cmsSigNamedColorTag                     = 0x6E636f6C,  // 'ncol' // Deprecated by the ICC
+    cmsSigNamedColor2Tag                    = 0x6E636C32,  // 'ncl2'
+    cmsSigOutputResponseTag                 = 0x72657370,  // 'resp'
+    cmsSigPerceptualRenderingIntentGamutTag = 0x72696730,  // 'rig0'
+    cmsSigPreview0Tag                       = 0x70726530,  // 'pre0'
+    cmsSigPreview1Tag                       = 0x70726531,  // 'pre1'
+    cmsSigPreview2Tag                       = 0x70726532,  // 'pre2'
+    cmsSigProfileDescriptionTag             = 0x64657363,  // 'desc'
+    cmsSigProfileSequenceDescTag            = 0x70736571,  // 'pseq'
+    cmsSigProfileSequenceIdTag              = 0x70736964,  // 'psid'
+    cmsSigPs2CRD0Tag                        = 0x70736430,  // 'psd0'
+    cmsSigPs2CRD1Tag                        = 0x70736431,  // 'psd1'
+    cmsSigPs2CRD2Tag                        = 0x70736432,  // 'psd2'
+    cmsSigPs2CRD3Tag                        = 0x70736433,  // 'psd3'
+    cmsSigPs2CSATag                         = 0x70733273,  // 'ps2s'
+    cmsSigPs2RenderingIntentTag             = 0x70733269,  // 'ps2i'
+    cmsSigRedColorantTag                    = 0x7258595A,  // 'rXYZ'
+    cmsSigRedMatrixColumnTag                = 0x7258595A,  // 'rXYZ'
+    cmsSigRedTRCTag                         = 0x72545243,  // 'rTRC'
+    cmsSigSaturationRenderingIntentGamutTag = 0x72696732,  // 'rig2'
+    cmsSigScreeningDescTag                  = 0x73637264,  // 'scrd'
+    cmsSigScreeningTag                      = 0x7363726E,  // 'scrn'
+    cmsSigTechnologyTag                     = 0x74656368,  // 'tech'
+    cmsSigUcrBgTag                          = 0x62666420,  // 'bfd '
+    cmsSigViewingCondDescTag                = 0x76756564,  // 'vued'
+    cmsSigViewingConditionsTag              = 0x76696577,  // 'view'
+    cmsSigVcgtTag                           = 0x76636774   // 'vcgt'
+
+} cmsTagSignature;
+
+
+// ICC Technology tag
+typedef enum {
+    cmsSigDigitalCamera                     = 0x6463616D,  // 'dcam'
+    cmsSigFilmScanner                       = 0x6673636E,  // 'fscn'
+    cmsSigReflectiveScanner                 = 0x7273636E,  // 'rscn'
+    cmsSigInkJetPrinter                     = 0x696A6574,  // 'ijet'
+    cmsSigThermalWaxPrinter                 = 0x74776178,  // 'twax'
+    cmsSigElectrophotographicPrinter        = 0x6570686F,  // 'epho'
+    cmsSigElectrostaticPrinter              = 0x65737461,  // 'esta'
+    cmsSigDyeSublimationPrinter             = 0x64737562,  // 'dsub'
+    cmsSigPhotographicPaperPrinter          = 0x7270686F,  // 'rpho'
+    cmsSigFilmWriter                        = 0x6670726E,  // 'fprn'
+    cmsSigVideoMonitor                      = 0x7669646D,  // 'vidm'
+    cmsSigVideoCamera                       = 0x76696463,  // 'vidc'
+    cmsSigProjectionTelevision              = 0x706A7476,  // 'pjtv'
+    cmsSigCRTDisplay                        = 0x43525420,  // 'CRT '
+    cmsSigPMDisplay                         = 0x504D4420,  // 'PMD '
+    cmsSigAMDisplay                         = 0x414D4420,  // 'AMD '
+    cmsSigPhotoCD                           = 0x4B504344,  // 'KPCD'
+    cmsSigPhotoImageSetter                  = 0x696D6773,  // 'imgs'
+    cmsSigGravure                           = 0x67726176,  // 'grav'
+    cmsSigOffsetLithography                 = 0x6F666673,  // 'offs'
+    cmsSigSilkscreen                        = 0x73696C6B,  // 'silk'
+    cmsSigFlexography                       = 0x666C6578,  // 'flex'
+    cmsSigMotionPictureFilmScanner          = 0x6D706673,  // 'mpfs'
+    cmsSigMotionPictureFilmRecorder         = 0x6D706672,  // 'mpfr'
+    cmsSigDigitalMotionPictureCamera        = 0x646D7063,  // 'dmpc'
+    cmsSigDigitalCinemaProjector            = 0x64636A70,  // 'dcpj'
+
+} cmsTechnologySignature;
+
+
+// ICC Color spaces
+typedef enum {
+    cmsSigXYZData                           = 0x58595A20,  // 'XYZ '
+    cmsSigLabData                           = 0x4C616220,  // 'Lab '
+    cmsSigLuvData                           = 0x4C757620,  // 'Luv '
+    cmsSigYCbCrData                         = 0x59436272,  // 'YCbr'
+    cmsSigYxyData                           = 0x59787920,  // 'Yxy '
+    cmsSigRgbData                           = 0x52474220,  // 'RGB '
+    cmsSigGrayData                          = 0x47524159,  // 'GRAY'
+    cmsSigHsvData                           = 0x48535620,  // 'HSV '
+    cmsSigHlsData                           = 0x484C5320,  // 'HLS '
+    cmsSigCmykData                          = 0x434D594B,  // 'CMYK'
+    cmsSigCmyData                           = 0x434D5920,  // 'CMY '
+    cmsSigMCH1Data                          = 0x4D434831,  // 'MCH1'
+    cmsSigMCH2Data                          = 0x4D434832,  // 'MCH2'
+    cmsSigMCH3Data                          = 0x4D434833,  // 'MCH3'
+    cmsSigMCH4Data                          = 0x4D434834,  // 'MCH4'
+    cmsSigMCH5Data                          = 0x4D434835,  // 'MCH5'
+    cmsSigMCH6Data                          = 0x4D434836,  // 'MCH6'
+    cmsSigMCH7Data                          = 0x4D434837,  // 'MCH7'
+    cmsSigMCH8Data                          = 0x4D434838,  // 'MCH8'
+    cmsSigMCH9Data                          = 0x4D434839,  // 'MCH9'
+    cmsSigMCHAData                          = 0x4D43483A,  // 'MCHA'
+    cmsSigMCHBData                          = 0x4D43483B,  // 'MCHB'
+    cmsSigMCHCData                          = 0x4D43483C,  // 'MCHC'
+    cmsSigMCHDData                          = 0x4D43483D,  // 'MCHD'
+    cmsSigMCHEData                          = 0x4D43483E,  // 'MCHE'
+    cmsSigMCHFData                          = 0x4D43483F,  // 'MCHF'
+    cmsSigNamedData                         = 0x6e6d636c,  // 'nmcl'
+    cmsSig1colorData                        = 0x31434C52,  // '1CLR'
+    cmsSig2colorData                        = 0x32434C52,  // '2CLR'
+    cmsSig3colorData                        = 0x33434C52,  // '3CLR'
+    cmsSig4colorData                        = 0x34434C52,  // '4CLR'
+    cmsSig5colorData                        = 0x35434C52,  // '5CLR'
+    cmsSig6colorData                        = 0x36434C52,  // '6CLR'
+    cmsSig7colorData                        = 0x37434C52,  // '7CLR'
+    cmsSig8colorData                        = 0x38434C52,  // '8CLR'
+    cmsSig9colorData                        = 0x39434C52,  // '9CLR'
+    cmsSig10colorData                       = 0x41434C52,  // 'ACLR'
+    cmsSig11colorData                       = 0x42434C52,  // 'BCLR'
+    cmsSig12colorData                       = 0x43434C52,  // 'CCLR'
+    cmsSig13colorData                       = 0x44434C52,  // 'DCLR'
+    cmsSig14colorData                       = 0x45434C52,  // 'ECLR'
+    cmsSig15colorData                       = 0x46434C52,  // 'FCLR'
+    cmsSigLuvKData                          = 0x4C75764B   // 'LuvK'
+
+} cmsColorSpaceSignature;
+
+// ICC Profile Class
+typedef enum {
+    cmsSigInputClass                        = 0x73636E72,  // 'scnr'
+    cmsSigDisplayClass                      = 0x6D6E7472,  // 'mntr'
+    cmsSigOutputClass                       = 0x70727472,  // 'prtr'
+    cmsSigLinkClass                         = 0x6C696E6B,  // 'link'
+    cmsSigAbstractClass                     = 0x61627374,  // 'abst'
+    cmsSigColorSpaceClass                   = 0x73706163,  // 'spac'
+    cmsSigNamedColorClass                   = 0x6e6d636c,  // 'nmcl'
+
+} cmsProfileClassSignature;
+
+// ICC Platforms
+typedef enum {
+    cmsSigMacintosh                         = 0x4150504C,  // 'APPL'
+    cmsSigMicrosoft                         = 0x4D534654,  // 'MSFT'
+    cmsSigSolaris                           = 0x53554E57,  // 'SUNW'
+    cmsSigSGI                               = 0x53474920,  // 'SGI '
+    cmsSigTaligent                          = 0x54474E54,  // 'TGNT'
+    cmsSigUnices                            = 0x2A6E6978   // '*nix'   // From argyll -- Not official
+
+} cmsPlatformSignature;
+
+// Reference gamut
+#define  cmsSigPerceptualReferenceMediumGamut         0x70726d67  //'prmg'
+
+// For cmsSigColorimetricIntentImageStateTag
+#define  cmsSigSceneColorimetryEstimates              0x73636F65  //'scoe'
+#define  cmsSigSceneAppearanceEstimates               0x73617065  //'sape'
+#define  cmsSigFocalPlaneColorimetryEstimates         0x66706365  //'fpce'
+#define  cmsSigReflectionHardcopyOriginalColorimetry  0x72686F63  //'rhoc'
+#define  cmsSigReflectionPrintOutputColorimetry       0x72706F63  //'rpoc'
+
+// Multi process elements types
+typedef enum {
+    cmsSigCurveSetElemType              = 0x63767374,  //'cvst'
+    cmsSigMatrixElemType                = 0x6D617466,  //'matf'
+    cmsSigCLutElemType                  = 0x636C7574,  //'clut'
+
+    cmsSigBAcsElemType                  = 0x62414353,  // 'bACS'
+    cmsSigEAcsElemType                  = 0x65414353,  // 'eACS'
+
+    // Custom from here, not in the ICC Spec
+    cmsSigXYZ2LabElemType               = 0x6C327820,  // 'l2x '
+    cmsSigLab2XYZElemType               = 0x78326C20,  // 'x2l '
+    cmsSigNamedColorElemType            = 0x6E636C20,  // 'ncl '
+    cmsSigLabV2toV4                     = 0x32203420,  // '2 4 '
+    cmsSigLabV4toV2                     = 0x34203220,  // '4 2 '
+
+    // Identities
+    cmsSigIdentityElemType              = 0x69646E20   // 'idn '
+
+} cmsStageSignature;
+
+// Types of CurveElements
+typedef enum {
+
+    cmsSigFormulaCurveSeg               = 0x70617266, // 'parf'
+    cmsSigSampledCurveSeg               = 0x73616D66, // 'samf'
+    cmsSigSegmentedCurve                = 0x63757266  // 'curf'
+
+} cmsCurveSegSignature;
+
+// Used in ResponseCurveType
+#define  cmsSigStatusA                    0x53746141 //'StaA'
+#define  cmsSigStatusE                    0x53746145 //'StaE'
+#define  cmsSigStatusI                    0x53746149 //'StaI'
+#define  cmsSigStatusT                    0x53746154 //'StaT'
+#define  cmsSigStatusM                    0x5374614D //'StaM'
+#define  cmsSigDN                         0x444E2020 //'DN  '
+#define  cmsSigDNP                        0x444E2050 //'DN P'
+#define  cmsSigDNN                        0x444E4E20 //'DNN '
+#define  cmsSigDNNP                       0x444E4E50 //'DNNP'
+
+// Device attributes, currently defined values correspond to the low 4 bytes
+// of the 8 byte attribute quantity
+#define cmsReflective     0
+#define cmsTransparency   1
+#define cmsGlossy         0
+#define cmsMatte          2
+
+// Common structures in ICC tags
+typedef struct {
+    cmsUInt32Number len;
+    cmsUInt32Number flag;
+    cmsUInt8Number  data[1];
+
+} cmsICCData;
+
+// ICC date time
+typedef struct {
+    cmsUInt16Number      year;
+    cmsUInt16Number      month;
+    cmsUInt16Number      day;
+    cmsUInt16Number      hours;
+    cmsUInt16Number      minutes;
+    cmsUInt16Number      seconds;
+
+} cmsDateTimeNumber;
+
+// ICC XYZ
+typedef struct {
+    cmsS15Fixed16Number  X;
+    cmsS15Fixed16Number  Y;
+    cmsS15Fixed16Number  Z;
+
+} cmsEncodedXYZNumber;
+
+
+// Profile ID as computed by MD5 algorithm
+typedef union {
+    cmsUInt8Number       ID8[16];
+    cmsUInt16Number      ID16[8];
+    cmsUInt32Number      ID32[4];
+
+} cmsProfileID;
+
+
+// ----------------------------------------------------------------------------------------------
+// ICC profile internal base types. Strictly, shouldn't be declared in this header, but maybe
+// somebody want to use this info for accessing profile header directly, so here it is.
+
+// Profile header -- it is 32-bit aligned, so no issues are expected on alignment
+typedef struct {
+    cmsUInt32Number              size;           // Profile size in bytes
+    cmsSignature                 cmmId;          // CMM for this profile
+    cmsUInt32Number              version;        // Format version number
+    cmsProfileClassSignature     deviceClass;    // Type of profile
+    cmsColorSpaceSignature       colorSpace;     // Color space of data
+    cmsColorSpaceSignature       pcs;            // PCS, XYZ or Lab only
+    cmsDateTimeNumber            date;           // Date profile was created
+    cmsSignature                 magic;          // Magic Number to identify an ICC profile
+    cmsPlatformSignature         platform;       // Primary Platform
+    cmsUInt32Number              flags;          // Various bit settings
+    cmsSignature                 manufacturer;   // Device manufacturer
+    cmsUInt32Number              model;          // Device model number
+    cmsUInt64Number              attributes;     // Device attributes
+    cmsUInt32Number              renderingIntent;// Rendering intent
+    cmsEncodedXYZNumber          illuminant;     // Profile illuminant
+    cmsSignature                 creator;        // Profile creator
+    cmsProfileID                 profileID;      // Profile ID using MD5
+    cmsInt8Number                reserved[28];   // Reserved for future use
+
+} cmsICCHeader;
+
+// ICC base tag
+typedef struct {
+    cmsTagTypeSignature  sig;
+    cmsInt8Number        reserved[4];
+
+} cmsTagBase;
+
+// A tag entry in directory
+typedef struct {
+    cmsTagSignature      sig;            // The tag signature
+    cmsUInt32Number      offset;         // Start of tag
+    cmsUInt32Number      size;           // Size in bytes
+
+} cmsTagEntry;
+
+// ----------------------------------------------------------------------------------------------
+
+// Little CMS specific typedefs
+
+typedef void* cmsContext;              // Context identifier for multithreaded environments
+typedef void* cmsHANDLE ;              // Generic handle
+typedef void* cmsHPROFILE;             // Opaque typedefs to hide internals
+typedef void* cmsHTRANSFORM;
+
+#define cmsMAXCHANNELS  16                // Maximum number of channels in ICC profiles
+
+// Format of pixel is defined by one cmsUInt32Number, using bit fields as follows
+//
+//            A O TTTTT U Y F P X S EEE CCCC BBB
+//
+//            A: Floating point -- With this flag we can differentiate 16 bits as float and as int
+//            O: Optimized -- previous optimization already returns the final 8-bit value
+//            T: Pixeltype
+//            F: Flavor  0=MinIsBlack(Chocolate) 1=MinIsWhite(Vanilla)
+//            P: Planar? 0=Chunky, 1=Planar
+//            X: swap 16 bps endianess?
+//            S: Do swap? ie, BGR, KYMC
+//            E: Extra samples
+//            C: Channels (Samples per pixel)
+//            B: bytes per sample
+//            Y: Swap first - changes ABGR to BGRA and KCMY to CMYK
+
+#define FLOAT_SH(a)            ((a) << 22)
+#define OPTIMIZED_SH(s)        ((s) << 21)
+#define COLORSPACE_SH(s)       ((s) << 16)
+#define SWAPFIRST_SH(s)        ((s) << 14)
+#define FLAVOR_SH(s)           ((s) << 13)
+#define PLANAR_SH(p)           ((p) << 12)
+#define ENDIAN16_SH(e)         ((e) << 11)
+#define DOSWAP_SH(e)           ((e) << 10)
+#define EXTRA_SH(e)            ((e) << 7)
+#define CHANNELS_SH(c)         ((c) << 3)
+#define BYTES_SH(b)            (b)
+
+// These macros unpack format specifiers into integers
+#define T_FLOAT(a)            (((a)>>22)&1)
+#define T_OPTIMIZED(o)        (((o)>>21)&1)
+#define T_COLORSPACE(s)       (((s)>>16)&31)
+#define T_SWAPFIRST(s)        (((s)>>14)&1)
+#define T_FLAVOR(s)           (((s)>>13)&1)
+#define T_PLANAR(p)           (((p)>>12)&1)
+#define T_ENDIAN16(e)         (((e)>>11)&1)
+#define T_DOSWAP(e)           (((e)>>10)&1)
+#define T_EXTRA(e)            (((e)>>7)&7)
+#define T_CHANNELS(c)         (((c)>>3)&15)
+#define T_BYTES(b)            ((b)&7)
+
+
+// Pixel types
+#define PT_ANY       0    // Don't check colorspace
+                          // 1 & 2 are reserved
+#define PT_GRAY      3
+#define PT_RGB       4
+#define PT_CMY       5
+#define PT_CMYK      6
+#define PT_YCbCr     7
+#define PT_YUV       8      // Lu'v'
+#define PT_XYZ       9
+#define PT_Lab       10
+#define PT_YUVK      11     // Lu'v'K
+#define PT_HSV       12
+#define PT_HLS       13
+#define PT_Yxy       14
+
+#define PT_MCH1      15
+#define PT_MCH2      16
+#define PT_MCH3      17
+#define PT_MCH4      18
+#define PT_MCH5      19
+#define PT_MCH6      20
+#define PT_MCH7      21
+#define PT_MCH8      22
+#define PT_MCH9      23
+#define PT_MCH10     24
+#define PT_MCH11     25
+#define PT_MCH12     26
+#define PT_MCH13     27
+#define PT_MCH14     28
+#define PT_MCH15     29
+
+#define PT_LabV2     30     // Identical to PT_Lab, but using the V2 old encoding
+
+// Some (not all!) representations
+
+#ifndef TYPE_RGB_8      // TYPE_RGB_8 is a very common identifier, so don't include ours
+                        // if user has it already defined.
+
+#define TYPE_GRAY_8            (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(1))
+#define TYPE_GRAY_8_REV        (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(1)|FLAVOR_SH(1))
+#define TYPE_GRAY_16           (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(2))
+#define TYPE_GRAY_16_REV       (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(2)|FLAVOR_SH(1))
+#define TYPE_GRAY_16_SE        (COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_GRAYA_8           (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(1))
+#define TYPE_GRAYA_16          (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(2))
+#define TYPE_GRAYA_16_SE       (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_GRAYA_8_PLANAR    (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_GRAYA_16_PLANAR   (COLORSPACE_SH(PT_GRAY)|EXTRA_SH(1)|CHANNELS_SH(1)|BYTES_SH(2)|PLANAR_SH(1))
+
+#define TYPE_RGB_8             (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(1))
+#define TYPE_RGB_8_PLANAR      (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_BGR_8             (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_BGR_8_PLANAR      (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1)|PLANAR_SH(1))
+#define TYPE_RGB_16            (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_RGB_16_PLANAR     (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_RGB_16_SE         (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_BGR_16            (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_BGR_16_PLANAR     (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|PLANAR_SH(1))
+#define TYPE_BGR_16_SE         (COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+
+#define TYPE_RGBA_8            (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1))
+#define TYPE_RGBA_8_PLANAR     (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_RGBA_16           (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_RGBA_16_PLANAR    (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_RGBA_16_SE        (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
+
+#define TYPE_ARGB_8            (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1)|SWAPFIRST_SH(1))
+#define TYPE_ARGB_16           (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|SWAPFIRST_SH(1))
+
+#define TYPE_ABGR_8            (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_ABGR_16           (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_ABGR_16_PLANAR    (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|PLANAR_SH(1))
+#define TYPE_ABGR_16_SE        (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+
+#define TYPE_BGRA_8            (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(1)|DOSWAP_SH(1)|SWAPFIRST_SH(1))
+#define TYPE_BGRA_16           (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|DOSWAP_SH(1)|SWAPFIRST_SH(1))
+#define TYPE_BGRA_16_SE        (COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1)|SWAPFIRST_SH(1))
+
+#define TYPE_CMY_8             (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(1))
+#define TYPE_CMY_8_PLANAR      (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_CMY_16            (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_CMY_16_PLANAR     (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_CMY_16_SE         (COLORSPACE_SH(PT_CMY)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
+
+#define TYPE_CMYK_8            (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1))
+#define TYPE_CMYKA_8           (COLORSPACE_SH(PT_CMYK)|EXTRA_SH(1)|CHANNELS_SH(4)|BYTES_SH(1))
+#define TYPE_CMYK_8_REV        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|FLAVOR_SH(1))
+#define TYPE_YUVK_8            TYPE_CMYK_8_REV
+#define TYPE_CMYK_8_PLANAR     (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_CMYK_16           (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2))
+#define TYPE_CMYK_16_REV       (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|FLAVOR_SH(1))
+#define TYPE_YUVK_16           TYPE_CMYK_16_REV
+#define TYPE_CMYK_16_PLANAR    (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_CMYK_16_SE        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|ENDIAN16_SH(1))
+
+#define TYPE_KYMC_8            (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_KYMC_16           (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_KYMC_16_SE        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+
+#define TYPE_KCMY_8            (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|SWAPFIRST_SH(1))
+#define TYPE_KCMY_8_REV        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(1)|FLAVOR_SH(1)|SWAPFIRST_SH(1))
+#define TYPE_KCMY_16           (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|SWAPFIRST_SH(1))
+#define TYPE_KCMY_16_REV       (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|FLAVOR_SH(1)|SWAPFIRST_SH(1))
+#define TYPE_KCMY_16_SE        (COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(2)|ENDIAN16_SH(1)|SWAPFIRST_SH(1))
+
+#define TYPE_CMYK5_8           (COLORSPACE_SH(PT_MCH5)|CHANNELS_SH(5)|BYTES_SH(1))
+#define TYPE_CMYK5_16          (COLORSPACE_SH(PT_MCH5)|CHANNELS_SH(5)|BYTES_SH(2))
+#define TYPE_CMYK5_16_SE       (COLORSPACE_SH(PT_MCH5)|CHANNELS_SH(5)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_KYMC5_8           (COLORSPACE_SH(PT_MCH5)|CHANNELS_SH(5)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_KYMC5_16          (COLORSPACE_SH(PT_MCH5)|CHANNELS_SH(5)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_KYMC5_16_SE       (COLORSPACE_SH(PT_MCH5)|CHANNELS_SH(5)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+#define TYPE_CMYK6_8           (COLORSPACE_SH(PT_MCH6)|CHANNELS_SH(6)|BYTES_SH(1))
+#define TYPE_CMYK6_8_PLANAR    (COLORSPACE_SH(PT_MCH6)|CHANNELS_SH(6)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_CMYK6_16          (COLORSPACE_SH(PT_MCH6)|CHANNELS_SH(6)|BYTES_SH(2))
+#define TYPE_CMYK6_16_PLANAR   (COLORSPACE_SH(PT_MCH6)|CHANNELS_SH(6)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_CMYK6_16_SE       (COLORSPACE_SH(PT_MCH6)|CHANNELS_SH(6)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_CMYK7_8           (COLORSPACE_SH(PT_MCH7)|CHANNELS_SH(7)|BYTES_SH(1))
+#define TYPE_CMYK7_16          (COLORSPACE_SH(PT_MCH7)|CHANNELS_SH(7)|BYTES_SH(2))
+#define TYPE_CMYK7_16_SE       (COLORSPACE_SH(PT_MCH7)|CHANNELS_SH(7)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_KYMC7_8           (COLORSPACE_SH(PT_MCH7)|CHANNELS_SH(7)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_KYMC7_16          (COLORSPACE_SH(PT_MCH7)|CHANNELS_SH(7)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_KYMC7_16_SE       (COLORSPACE_SH(PT_MCH7)|CHANNELS_SH(7)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+#define TYPE_CMYK8_8           (COLORSPACE_SH(PT_MCH8)|CHANNELS_SH(8)|BYTES_SH(1))
+#define TYPE_CMYK8_16          (COLORSPACE_SH(PT_MCH8)|CHANNELS_SH(8)|BYTES_SH(2))
+#define TYPE_CMYK8_16_SE       (COLORSPACE_SH(PT_MCH8)|CHANNELS_SH(8)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_KYMC8_8           (COLORSPACE_SH(PT_MCH8)|CHANNELS_SH(8)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_KYMC8_16          (COLORSPACE_SH(PT_MCH8)|CHANNELS_SH(8)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_KYMC8_16_SE       (COLORSPACE_SH(PT_MCH8)|CHANNELS_SH(8)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+#define TYPE_CMYK9_8           (COLORSPACE_SH(PT_MCH9)|CHANNELS_SH(9)|BYTES_SH(1))
+#define TYPE_CMYK9_16          (COLORSPACE_SH(PT_MCH9)|CHANNELS_SH(9)|BYTES_SH(2))
+#define TYPE_CMYK9_16_SE       (COLORSPACE_SH(PT_MCH9)|CHANNELS_SH(9)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_KYMC9_8           (COLORSPACE_SH(PT_MCH9)|CHANNELS_SH(9)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_KYMC9_16          (COLORSPACE_SH(PT_MCH9)|CHANNELS_SH(9)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_KYMC9_16_SE       (COLORSPACE_SH(PT_MCH9)|CHANNELS_SH(9)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+#define TYPE_CMYK10_8          (COLORSPACE_SH(PT_MCH10)|CHANNELS_SH(10)|BYTES_SH(1))
+#define TYPE_CMYK10_16         (COLORSPACE_SH(PT_MCH10)|CHANNELS_SH(10)|BYTES_SH(2))
+#define TYPE_CMYK10_16_SE      (COLORSPACE_SH(PT_MCH10)|CHANNELS_SH(10)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_KYMC10_8          (COLORSPACE_SH(PT_MCH10)|CHANNELS_SH(10)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_KYMC10_16         (COLORSPACE_SH(PT_MCH10)|CHANNELS_SH(10)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_KYMC10_16_SE      (COLORSPACE_SH(PT_MCH10)|CHANNELS_SH(10)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+#define TYPE_CMYK11_8          (COLORSPACE_SH(PT_MCH11)|CHANNELS_SH(11)|BYTES_SH(1))
+#define TYPE_CMYK11_16         (COLORSPACE_SH(PT_MCH11)|CHANNELS_SH(11)|BYTES_SH(2))
+#define TYPE_CMYK11_16_SE      (COLORSPACE_SH(PT_MCH11)|CHANNELS_SH(11)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_KYMC11_8          (COLORSPACE_SH(PT_MCH11)|CHANNELS_SH(11)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_KYMC11_16         (COLORSPACE_SH(PT_MCH11)|CHANNELS_SH(11)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_KYMC11_16_SE      (COLORSPACE_SH(PT_MCH11)|CHANNELS_SH(11)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+#define TYPE_CMYK12_8          (COLORSPACE_SH(PT_MCH12)|CHANNELS_SH(12)|BYTES_SH(1))
+#define TYPE_CMYK12_16         (COLORSPACE_SH(PT_MCH12)|CHANNELS_SH(12)|BYTES_SH(2))
+#define TYPE_CMYK12_16_SE      (COLORSPACE_SH(PT_MCH12)|CHANNELS_SH(12)|BYTES_SH(2)|ENDIAN16_SH(1))
+#define TYPE_KYMC12_8          (COLORSPACE_SH(PT_MCH12)|CHANNELS_SH(12)|BYTES_SH(1)|DOSWAP_SH(1))
+#define TYPE_KYMC12_16         (COLORSPACE_SH(PT_MCH12)|CHANNELS_SH(12)|BYTES_SH(2)|DOSWAP_SH(1))
+#define TYPE_KYMC12_16_SE      (COLORSPACE_SH(PT_MCH12)|CHANNELS_SH(12)|BYTES_SH(2)|DOSWAP_SH(1)|ENDIAN16_SH(1))
+
+// Colorimetric
+#define TYPE_XYZ_16            (COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_Lab_8             (COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(1))
+#define TYPE_LabV2_8           (COLORSPACE_SH(PT_LabV2)|CHANNELS_SH(3)|BYTES_SH(1))
+
+#define TYPE_ALab_8            (COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)|DOSWAP_SH(1))
+#define TYPE_ALabV2_8          (COLORSPACE_SH(PT_LabV2)|CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)|DOSWAP_SH(1))
+#define TYPE_Lab_16            (COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_LabV2_16          (COLORSPACE_SH(PT_LabV2)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_Yxy_16            (COLORSPACE_SH(PT_Yxy)|CHANNELS_SH(3)|BYTES_SH(2))
+
+// YCbCr
+#define TYPE_YCbCr_8           (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(1))
+#define TYPE_YCbCr_8_PLANAR    (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_YCbCr_16          (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_YCbCr_16_PLANAR   (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_YCbCr_16_SE       (COLORSPACE_SH(PT_YCbCr)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
+
+// YUV
+#define TYPE_YUV_8             (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(1))
+#define TYPE_YUV_8_PLANAR      (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_YUV_16            (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_YUV_16_PLANAR     (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_YUV_16_SE         (COLORSPACE_SH(PT_YUV)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
+
+// HLS
+#define TYPE_HLS_8             (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(1))
+#define TYPE_HLS_8_PLANAR      (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_HLS_16            (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_HLS_16_PLANAR     (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_HLS_16_SE         (COLORSPACE_SH(PT_HLS)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
+
+// HSV
+#define TYPE_HSV_8             (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(1))
+#define TYPE_HSV_8_PLANAR      (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(1)|PLANAR_SH(1))
+#define TYPE_HSV_16            (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(2))
+#define TYPE_HSV_16_PLANAR     (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(2)|PLANAR_SH(1))
+#define TYPE_HSV_16_SE         (COLORSPACE_SH(PT_HSV)|CHANNELS_SH(3)|BYTES_SH(2)|ENDIAN16_SH(1))
+
+// Named color index. Only 16 bits allowed (don't check colorspace)
+#define TYPE_NAMED_COLOR_INDEX (CHANNELS_SH(1)|BYTES_SH(2))
+
+// Float formatters.
+#define TYPE_XYZ_FLT          (FLOAT_SH(1)|COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(4))
+#define TYPE_Lab_FLT          (FLOAT_SH(1)|COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(4))
+#define TYPE_GRAY_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(4))
+#define TYPE_RGB_FLT          (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(4))
+#define TYPE_CMYK_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(4))
+
+// Floating point formatters.
+// NOTE THAT 'BYTES' FIELD IS SET TO ZERO ON DLB because 8 bytes overflows the bitfield
+#define TYPE_XYZ_DBL          (FLOAT_SH(1)|COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(0))
+#define TYPE_Lab_DBL          (FLOAT_SH(1)|COLORSPACE_SH(PT_Lab)|CHANNELS_SH(3)|BYTES_SH(0))
+#define TYPE_GRAY_DBL         (FLOAT_SH(1)|COLORSPACE_SH(PT_GRAY)|CHANNELS_SH(1)|BYTES_SH(0))
+#define TYPE_RGB_DBL          (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(0))
+#define TYPE_CMYK_DBL         (FLOAT_SH(1)|COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(0))
+
+#endif
+
+// Colorspaces
+typedef struct {
+        cmsFloat64Number X;
+        cmsFloat64Number Y;
+        cmsFloat64Number Z;
+
+    } cmsCIEXYZ;
+
+typedef struct {
+        cmsFloat64Number x;
+        cmsFloat64Number y;
+        cmsFloat64Number Y;
+
+    } cmsCIExyY;
+
+typedef struct {
+        cmsFloat64Number L;
+        cmsFloat64Number a;
+        cmsFloat64Number b;
+
+    } cmsCIELab;
+
+typedef struct {
+        cmsFloat64Number L;
+        cmsFloat64Number C;
+        cmsFloat64Number h;
+
+    } cmsCIELCh;
+
+typedef struct {
+        cmsFloat64Number J;
+        cmsFloat64Number C;
+        cmsFloat64Number h;
+
+    } cmsJCh;
+
+typedef struct {
+        cmsCIEXYZ  Red;
+        cmsCIEXYZ  Green;
+        cmsCIEXYZ  Blue;
+
+    } cmsCIEXYZTRIPLE;
+
+typedef struct {
+        cmsCIExyY  Red;
+        cmsCIExyY  Green;
+        cmsCIExyY  Blue;
+
+    } cmsCIExyYTRIPLE;
+
+// Illuminant types for structs below
+#define cmsILLUMINANT_TYPE_UNKNOWN 0x0000000
+#define cmsILLUMINANT_TYPE_D50     0x0000001
+#define cmsILLUMINANT_TYPE_D65     0x0000002
+#define cmsILLUMINANT_TYPE_D93     0x0000003
+#define cmsILLUMINANT_TYPE_F2      0x0000004
+#define cmsILLUMINANT_TYPE_D55     0x0000005
+#define cmsILLUMINANT_TYPE_A       0x0000006
+#define cmsILLUMINANT_TYPE_E       0x0000007
+#define cmsILLUMINANT_TYPE_F8      0x0000008
+
+typedef struct {
+        cmsUInt32Number  Observer;    // 0 = unknown, 1=CIE 1931, 2=CIE 1964
+        cmsCIEXYZ        Backing;     // Value of backing
+        cmsUInt32Number  Geometry;    // 0=unknown, 1=45/0, 0/45 2=0d, d/0
+        cmsFloat64Number Flare;       // 0..1.0
+        cmsUInt32Number  IlluminantType;
+
+    } cmsICCMeasurementConditions;
+
+typedef struct {
+        cmsCIEXYZ       IlluminantXYZ;   // Not the same struct as CAM02,
+        cmsCIEXYZ       SurroundXYZ;     // This is for storing the tag
+        cmsUInt32Number IlluminantType;  // viewing condition
+
+    } cmsICCViewingConditions;
+
+// Support of non-standard functions --------------------------------------------------------------------------------------
+
+CMSAPI int               CMSEXPORT cmsstrcasecmp(const char* s1, const char* s2);
+CMSAPI long int          CMSEXPORT cmsfilelength(FILE* f);
+
+// Plug-In registering  ---------------------------------------------------------------------------------------------------
+
+CMSAPI cmsBool           CMSEXPORT cmsPlugin(void* Plugin);
+CMSAPI void              CMSEXPORT cmsUnregisterPlugins(void);
+
+// Error logging ----------------------------------------------------------------------------------------------------------
+
+// There is no error handling at all. When a function fails, it returns proper value.
+// For example, all create functions does return NULL on failure. Other may return FALSE.
+// It may be interesting, for the developer, to know why the function is failing.
+// for that reason, lcms2 does offer a logging function. This function will get
+// an ENGLISH string with some clues on what is going wrong. You can show this
+// info to the end user if you wish, or just create some sort of log on disk.
+// The logging function should NOT terminate the program, as this obviously can leave
+// unfreed resources. It is the programmer's responsibility to check each function
+// return code to make sure it didn't fail.
+
+#define cmsERROR_UNDEFINED                    0
+#define cmsERROR_FILE                         1
+#define cmsERROR_RANGE                        2
+#define cmsERROR_INTERNAL                     3
+#define cmsERROR_NULL                         4
+#define cmsERROR_READ                         5
+#define cmsERROR_SEEK                         6
+#define cmsERROR_WRITE                        7
+#define cmsERROR_UNKNOWN_EXTENSION            8
+#define cmsERROR_COLORSPACE_CHECK             9
+#define cmsERROR_ALREADY_DEFINED              10
+#define cmsERROR_BAD_SIGNATURE                11
+#define cmsERROR_CORRUPTION_DETECTED          12
+#define cmsERROR_NOT_SUITABLE                 13
+
+// Error logger is called with the ContextID when a message is raised. This gives the
+// chance to know which thread is responsible of the warning and any environment associated
+// with it. Non-multithreading applications may safely ignore this parameter.
+// Note that under certain special circumstances, ContextID may be NULL.
+typedef void  (* cmsLogErrorHandlerFunction)(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text);
+
+// Allows user to set any specific logger
+CMSAPI void              CMSEXPORT cmsSetLogErrorHandler(cmsLogErrorHandlerFunction Fn);
+
+// Conversions --------------------------------------------------------------------------------------------------------------
+
+// Returns pointers to constant structs
+CMSAPI const cmsCIEXYZ*  CMSEXPORT cmsD50_XYZ(void);
+CMSAPI const cmsCIExyY*  CMSEXPORT cmsD50_xyY(void);
+
+// Colorimetric space conversions
+CMSAPI void              CMSEXPORT cmsXYZ2xyY(cmsCIExyY* Dest, const cmsCIEXYZ* Source);
+CMSAPI void              CMSEXPORT cmsxyY2XYZ(cmsCIEXYZ* Dest, const cmsCIExyY* Source);
+CMSAPI void              CMSEXPORT cmsXYZ2Lab(const cmsCIEXYZ* WhitePoint, cmsCIELab* Lab, const cmsCIEXYZ* xyz);
+CMSAPI void              CMSEXPORT cmsLab2XYZ(const cmsCIEXYZ* WhitePoint, cmsCIEXYZ* xyz, const cmsCIELab* Lab);
+CMSAPI void              CMSEXPORT cmsLab2LCh(cmsCIELCh*LCh, const cmsCIELab* Lab);
+CMSAPI void              CMSEXPORT cmsLCh2Lab(cmsCIELab* Lab, const cmsCIELCh* LCh);
+
+// Encoding /Decoding on PCS
+CMSAPI void              CMSEXPORT cmsLabEncoded2Float(cmsCIELab* Lab, const cmsUInt16Number wLab[3]);
+CMSAPI void              CMSEXPORT cmsLabEncoded2FloatV2(cmsCIELab* Lab, const cmsUInt16Number wLab[3]);
+CMSAPI void              CMSEXPORT cmsFloat2LabEncoded(cmsUInt16Number wLab[3], const cmsCIELab* Lab);
+CMSAPI void              CMSEXPORT cmsFloat2LabEncodedV2(cmsUInt16Number wLab[3], const cmsCIELab* Lab);
+CMSAPI void              CMSEXPORT cmsXYZEncoded2Float(cmsCIEXYZ* fxyz, const cmsUInt16Number XYZ[3]);
+CMSAPI void              CMSEXPORT cmsFloat2XYZEncoded(cmsUInt16Number XYZ[3], const cmsCIEXYZ* fXYZ);
+
+// DeltaE metrics
+CMSAPI cmsFloat64Number  CMSEXPORT cmsDeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2);
+CMSAPI cmsFloat64Number  CMSEXPORT cmsCIE94DeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2);
+CMSAPI cmsFloat64Number  CMSEXPORT cmsBFDdeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2);
+CMSAPI cmsFloat64Number  CMSEXPORT cmsCMCdeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2, cmsFloat64Number l, cmsFloat64Number c);
+CMSAPI cmsFloat64Number  CMSEXPORT cmsCIE2000DeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2, cmsFloat64Number Kl, cmsFloat64Number Kc, cmsFloat64Number Kh);
+
+// Temperature <-> Chromaticity (Black body)
+CMSAPI cmsBool           CMSEXPORT cmsWhitePointFromTemp(cmsCIExyY* WhitePoint, cmsFloat64Number  TempK);
+CMSAPI cmsBool           CMSEXPORT cmsTempFromWhitePoint(cmsFloat64Number* TempK, const cmsCIExyY* WhitePoint);
+
+// Chromatic adaptation
+CMSAPI cmsBool           CMSEXPORT cmsAdaptToIlluminant(cmsCIEXYZ* Result, const cmsCIEXYZ* SourceWhitePt,
+                                                                           const cmsCIEXYZ* Illuminant,
+                                                                           const cmsCIEXYZ* Value);
+
+// CIECAM02 ---------------------------------------------------------------------------------------------------
+
+// Viewing conditions. Please note those are CAM model viewing conditions, and not the ICC tag viewing
+// conditions, which I'm naming cmsICCViewingConditions to make differences evident. Unfortunately, the tag
+// cannot deal with surround La, Yb and D value so is basically useless to store CAM02 viewing conditions.
+
+
+#define AVG_SURROUND       1
+#define DIM_SURROUND       2
+#define DARK_SURROUND      3
+#define CUTSHEET_SURROUND  4
+
+#define D_CALCULATE        (-1)
+
+typedef struct {
+    cmsCIEXYZ        whitePoint;
+    cmsFloat64Number Yb;
+    cmsFloat64Number La;
+    int              surround;
+    cmsFloat64Number D_value;
+
+    } cmsViewingConditions;
+
+CMSAPI cmsHANDLE         CMSEXPORT cmsCIECAM02Init(cmsContext ContextID, const cmsViewingConditions* pVC);
+CMSAPI void              CMSEXPORT cmsCIECAM02Done(cmsHANDLE hModel);
+CMSAPI void              CMSEXPORT cmsCIECAM02Forward(cmsHANDLE hModel, const cmsCIEXYZ* pIn, cmsJCh* pOut);
+CMSAPI void              CMSEXPORT cmsCIECAM02Reverse(cmsHANDLE hModel, const cmsJCh* pIn,    cmsCIEXYZ* pOut);
+
+
+// Tone curves -----------------------------------------------------------------------------------------
+
+// This describes a curve segment. For a table of supported types, see the manual. User can increase the number of
+// available types by using a proper plug-in. Parametric segments allow 10 parameters at most
+
+typedef struct {
+    cmsFloat32Number   x0, x1;           // Domain; for x0 < x <= x1
+    cmsInt32Number     Type;             // Parametric type, Type == 0 means sampled segment. Negative values are reserved
+    cmsFloat64Number   Params[10];       // Parameters if Type != 0
+    cmsUInt32Number    nGridPoints;      // Number of grid points if Type == 0
+    cmsFloat32Number*  SampledPoints;    // Points to an array of floats if Type == 0
+
+} cmsCurveSegment;
+
+// The internal representation is none of your business.
+typedef struct _cms_curve_struct cmsToneCurve;
+
+CMSAPI cmsToneCurve*     CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID, cmsInt32Number nSegments, const cmsCurveSegment Segments[]);
+CMSAPI cmsToneCurve*     CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[]);
+CMSAPI cmsToneCurve*     CMSEXPORT cmsBuildGamma(cmsContext ContextID, cmsFloat64Number Gamma);
+CMSAPI cmsToneCurve*     CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsInt32Number nEntries, const cmsUInt16Number values[]);
+CMSAPI cmsToneCurve*     CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[]);
+CMSAPI void              CMSEXPORT cmsFreeToneCurve(cmsToneCurve* Curve);
+CMSAPI void              CMSEXPORT cmsFreeToneCurveTriple(cmsToneCurve* Curve[3]);
+CMSAPI cmsToneCurve*     CMSEXPORT cmsDupToneCurve(const cmsToneCurve* Src);
+CMSAPI cmsToneCurve*     CMSEXPORT cmsReverseToneCurve(const cmsToneCurve* InGamma);
+CMSAPI cmsToneCurve*     CMSEXPORT cmsReverseToneCurveEx(cmsInt32Number nResultSamples, const cmsToneCurve* InGamma);
+CMSAPI cmsToneCurve*     CMSEXPORT cmsJoinToneCurve(cmsContext ContextID, const cmsToneCurve* X,  const cmsToneCurve* Y, cmsUInt32Number nPoints);
+CMSAPI cmsBool           CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda);
+CMSAPI cmsFloat32Number  CMSEXPORT cmsEvalToneCurveFloat(const cmsToneCurve* Curve, cmsFloat32Number v);
+CMSAPI cmsUInt16Number   CMSEXPORT cmsEvalToneCurve16(const cmsToneCurve* Curve, cmsUInt16Number v);
+CMSAPI cmsBool           CMSEXPORT cmsIsToneCurveMultisegment(const cmsToneCurve* InGamma);
+CMSAPI cmsBool           CMSEXPORT cmsIsToneCurveLinear(const cmsToneCurve* Curve);
+CMSAPI cmsBool           CMSEXPORT cmsIsToneCurveMonotonic(const cmsToneCurve* t);
+CMSAPI cmsBool           CMSEXPORT cmsIsToneCurveDescending(const cmsToneCurve* t);
+CMSAPI cmsInt32Number    CMSEXPORT cmsGetToneCurveParametricType(const cmsToneCurve* t);
+CMSAPI cmsFloat64Number  CMSEXPORT cmsEstimateGamma(const cmsToneCurve* t, cmsFloat64Number Precision);
+
+
+// Implements pipelines of multi-processing elements -------------------------------------------------------------
+
+// Nothing to see here, move along
+typedef struct _cmsPipeline_struct cmsPipeline;
+typedef struct _cmsStage_struct cmsStage;
+
+// Those are hi-level pipelines
+CMSAPI cmsPipeline*      CMSEXPORT cmsPipelineAlloc(cmsContext ContextID, cmsUInt32Number InputChannels, cmsUInt32Number OutputChannels);
+CMSAPI void              CMSEXPORT cmsPipelineFree(cmsPipeline* lut);
+CMSAPI cmsPipeline*      CMSEXPORT cmsPipelineDup(const cmsPipeline* Orig);
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsPipelineInputChannels(const cmsPipeline* lut);
+CMSAPI cmsUInt32Number   CMSEXPORT cmsPipelineOutputChannels(const cmsPipeline* lut);
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsPipelineStageCount(const cmsPipeline* lut);
+CMSAPI cmsStage*         CMSEXPORT cmsPipelineGetPtrToFirstStage(const cmsPipeline* lut);
+CMSAPI cmsStage*         CMSEXPORT cmsPipelineGetPtrToLastStage(const cmsPipeline* lut);
+
+CMSAPI void              CMSEXPORT cmsPipelineEval16(const cmsUInt16Number In[], cmsUInt16Number Out[], const cmsPipeline* lut);
+CMSAPI void              CMSEXPORT cmsPipelineEvalFloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsPipeline* lut);
+CMSAPI cmsBool           CMSEXPORT cmsPipelineEvalReverseFloat(cmsFloat32Number Target[], cmsFloat32Number Result[], cmsFloat32Number Hint[], const cmsPipeline* lut);
+CMSAPI cmsBool           CMSEXPORT cmsPipelineCat(cmsPipeline* l1, const cmsPipeline* l2);
+CMSAPI cmsBool           CMSEXPORT cmsPipelineSetSaveAs8bitsFlag(cmsPipeline* lut, cmsBool On);
+
+// Where to place/locate the stages in the pipeline chain
+typedef enum { cmsAT_BEGIN, cmsAT_END } cmsStageLoc;
+
+CMSAPI void              CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe);
+CMSAPI void              CMSEXPORT cmsPipelineUnlinkStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage** mpe);
+
+// This function is quite useful to analyze the structure of a Pipeline and retrieve the Stage elements
+// that conform the Pipeline. It should be called with the Pipeline, the number of expected elements and
+// then a list of expected types followed with a list of double pointers to Stage elements. If
+// the function founds a match with current pipeline, it fills the pointers and returns TRUE
+// if not, returns FALSE without touching anything.
+CMSAPI cmsBool           CMSEXPORT cmsPipelineCheckAndRetreiveStages(const cmsPipeline* Lut, cmsUInt32Number n, ...);
+
+// Matrix has double precision and CLUT has only float precision. That is because an ICC profile can encode
+// matrices with far more precision that CLUTS
+CMSAPI cmsStage*         CMSEXPORT cmsStageAllocIdentity(cmsContext ContextID, cmsUInt32Number nChannels);
+CMSAPI cmsStage*         CMSEXPORT cmsStageAllocToneCurves(cmsContext ContextID, cmsUInt32Number nChannels, cmsToneCurve* const Curves[]);
+CMSAPI cmsStage*         CMSEXPORT cmsStageAllocMatrix(cmsContext ContextID, cmsUInt32Number Rows, cmsUInt32Number Cols, const cmsFloat64Number* Matrix, const cmsFloat64Number* Offset);
+
+CMSAPI cmsStage*         CMSEXPORT cmsStageAllocCLut16bit(cmsContext ContextID, cmsUInt32Number nGridPoints, cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsUInt16Number* Table);
+CMSAPI cmsStage*         CMSEXPORT cmsStageAllocCLutFloat(cmsContext ContextID, cmsUInt32Number nGridPoints, cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsFloat32Number* Table);
+
+CMSAPI cmsStage*         CMSEXPORT cmsStageAllocCLut16bitGranular(cmsContext ContextID, const cmsUInt32Number clutPoints[], cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsUInt16Number* Table);
+CMSAPI cmsStage*         CMSEXPORT cmsStageAllocCLutFloatGranular(cmsContext ContextID, const cmsUInt32Number clutPoints[], cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsFloat32Number* Table);
+
+CMSAPI cmsStage*         CMSEXPORT cmsStageDup(cmsStage* mpe);
+CMSAPI void              CMSEXPORT cmsStageFree(cmsStage* mpe);
+CMSAPI cmsStage*         CMSEXPORT cmsStageNext(const cmsStage* mpe);
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsStageInputChannels(const cmsStage* mpe);
+CMSAPI cmsUInt32Number   CMSEXPORT cmsStageOutputChannels(const cmsStage* mpe);
+CMSAPI cmsStageSignature CMSEXPORT cmsStageType(const cmsStage* mpe);
+CMSAPI void*             CMSEXPORT cmsStageData(const cmsStage* mpe);
+
+// Sampling
+typedef cmsInt32Number (* cmsSAMPLER16)   (register const cmsUInt16Number In[],
+                                            register cmsUInt16Number Out[],
+                                            register void * Cargo);
+
+typedef cmsInt32Number (* cmsSAMPLERFLOAT)(register const cmsFloat32Number In[],
+                                            register cmsFloat32Number Out[],
+                                            register void * Cargo);
+
+// Use this flag to prevent changes being written to destination
+#define SAMPLER_INSPECT     0x01000000
+
+// For CLUT only
+CMSAPI cmsBool           CMSEXPORT cmsStageSampleCLut16bit(cmsStage* mpe,    cmsSAMPLER16 Sampler,    void* Cargo, cmsUInt32Number dwFlags);
+CMSAPI cmsBool           CMSEXPORT cmsStageSampleCLutFloat(cmsStage* mpe, cmsSAMPLERFLOAT Sampler, void* Cargo, cmsUInt32Number dwFlags);
+
+
+// Slicers
+CMSAPI cmsBool           CMSEXPORT cmsSliceSpace16(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
+                                                   cmsSAMPLER16 Sampler, void * Cargo);
+
+CMSAPI cmsBool           CMSEXPORT cmsSliceSpaceFloat(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
+                                                   cmsSAMPLERFLOAT Sampler, void * Cargo);
+
+// Multilocalized Unicode management ---------------------------------------------------------------------------------------
+
+typedef struct _cms_MLU_struct cmsMLU;
+
+#define  cmsNoLanguage "\0\0"
+#define  cmsNoCountry  "\0\0"
+
+CMSAPI cmsMLU*           CMSEXPORT cmsMLUalloc(cmsContext ContextID, cmsUInt32Number nItems);
+CMSAPI void              CMSEXPORT cmsMLUfree(cmsMLU* mlu);
+CMSAPI cmsMLU*           CMSEXPORT cmsMLUdup(const cmsMLU* mlu);
+
+CMSAPI cmsBool           CMSEXPORT cmsMLUsetASCII(cmsMLU* mlu,
+                                                  const char LanguageCode[3], const char CountryCode[3],
+                                                  const char* ASCIIString);
+CMSAPI cmsBool           CMSEXPORT cmsMLUsetWide(cmsMLU* mlu,
+                                                  const char LanguageCode[3], const char CountryCode[3],
+                                                  const wchar_t* WideString);
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsMLUgetASCII(const cmsMLU* mlu,
+                                                  const char LanguageCode[3], const char CountryCode[3],
+                                                  char* Buffer,    cmsUInt32Number BufferSize);
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsMLUgetWide(const cmsMLU* mlu,
+                                                 const char LanguageCode[3], const char CountryCode[3],
+                                                 wchar_t* Buffer, cmsUInt32Number BufferSize);
+
+CMSAPI cmsBool           CMSEXPORT cmsMLUgetTranslation(const cmsMLU* mlu,
+                                                         const char LanguageCode[3], const char CountryCode[3],
+                                                         char ObtainedLanguage[3], char ObtainedCountry[3]);
+
+// Undercolorremoval & black generation -------------------------------------------------------------------------------------
+
+typedef struct {
+        cmsToneCurve* Ucr;
+        cmsToneCurve* Bg;
+        cmsMLU*       Desc;
+
+} cmsUcrBg;
+
+// Screening ----------------------------------------------------------------------------------------------------------------
+
+#define cmsPRINTER_DEFAULT_SCREENS     0x0001
+#define cmsFREQUENCE_UNITS_LINES_CM    0x0000
+#define cmsFREQUENCE_UNITS_LINES_INCH  0x0002
+
+#define cmsSPOT_UNKNOWN         0
+#define cmsSPOT_PRINTER_DEFAULT 1
+#define cmsSPOT_ROUND           2
+#define cmsSPOT_DIAMOND         3
+#define cmsSPOT_ELLIPSE         4
+#define cmsSPOT_LINE            5
+#define cmsSPOT_SQUARE          6
+#define cmsSPOT_CROSS           7
+
+typedef struct {
+    cmsFloat64Number  Frequency;
+    cmsFloat64Number  ScreenAngle;
+    cmsUInt32Number   SpotShape;
+
+} cmsScreeningChannel;
+
+typedef struct {
+    cmsUInt32Number Flag;
+    cmsUInt32Number nChannels;
+    cmsScreeningChannel Channels[cmsMAXCHANNELS];
+
+} cmsScreening;
+
+
+// Named color -----------------------------------------------------------------------------------------------------------------
+
+typedef struct _cms_NAMEDCOLORLIST_struct cmsNAMEDCOLORLIST;
+
+CMSAPI cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID,
+                                                           cmsUInt32Number n,
+                                                           cmsUInt32Number ColorantCount,
+                                                           const char* Prefix, const char* Suffix);
+
+CMSAPI void               CMSEXPORT cmsFreeNamedColorList(cmsNAMEDCOLORLIST* v);
+CMSAPI cmsNAMEDCOLORLIST* CMSEXPORT cmsDupNamedColorList(const cmsNAMEDCOLORLIST* v);
+CMSAPI cmsBool            CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* v, const char* Name,
+                                                            cmsUInt16Number PCS[3],
+                                                            cmsUInt16Number Colorant[cmsMAXCHANNELS]);
+
+CMSAPI cmsUInt32Number    CMSEXPORT cmsNamedColorCount(const cmsNAMEDCOLORLIST* v);
+CMSAPI cmsInt32Number     CMSEXPORT cmsNamedColorIndex(const cmsNAMEDCOLORLIST* v, const char* Name);
+
+CMSAPI cmsBool            CMSEXPORT cmsNamedColorInfo(const cmsNAMEDCOLORLIST* NamedColorList, cmsUInt32Number nColor,
+                                                      char* Name,
+                                                      char* Prefix,
+                                                      char* Suffix,
+                                                      cmsUInt16Number* PCS,
+                                                      cmsUInt16Number* Colorant);
+
+// Retrieve named color list from transform
+CMSAPI cmsNAMEDCOLORLIST* CMSEXPORT cmsGetNamedColorList(cmsHTRANSFORM xform);
+
+// Profile sequence -----------------------------------------------------------------------------------------------------
+
+// Profile sequence descriptor. Some fields come from profile sequence descriptor tag, others
+// come from Profile Sequence Identifier Tag
+typedef struct {
+    cmsSignature           deviceMfg;
+    cmsSignature           deviceModel;
+    cmsUInt64Number        attributes;
+    cmsTechnologySignature technology;
+    cmsProfileID           ProfileID;
+    cmsMLU*                Manufacturer;
+    cmsMLU*                Model;
+    cmsMLU*                Description;
+
+} cmsPSEQDESC;
+
+typedef struct {
+
+    cmsUInt32Number n;
+    cmsContext     ContextID;
+    cmsPSEQDESC*    seq;
+
+} cmsSEQ;
+
+CMSAPI cmsSEQ*           CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n);
+CMSAPI cmsSEQ*           CMSEXPORT cmsDupProfileSequenceDescription(const cmsSEQ* pseq);
+CMSAPI void              CMSEXPORT cmsFreeProfileSequenceDescription(cmsSEQ* pseq);
+
+// Access to Profile data ----------------------------------------------------------------------------------------------
+CMSAPI cmsHPROFILE       CMSEXPORT cmsCreateProfilePlaceholder(cmsContext ContextID);
+
+CMSAPI cmsContext        CMSEXPORT cmsGetProfileContextID(cmsHPROFILE hProfile);
+CMSAPI cmsInt32Number    CMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile);
+CMSAPI cmsTagSignature   CMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, cmsUInt32Number n);
+CMSAPI cmsBool           CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig);
+
+// Read and write pre-formatted data
+CMSAPI void*             CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig);
+CMSAPI cmsBool           CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data);
+CMSAPI cmsBool           CMSEXPORT cmsLinkTag(cmsHPROFILE hProfile, cmsTagSignature sig, cmsTagSignature dest);
+
+// Read and write raw data
+CMSAPI cmsInt32Number    CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, void* Buffer, cmsUInt32Number BufferSize);
+CMSAPI cmsBool           CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data, cmsUInt32Number Size);
+
+// Access header data
+CMSAPI cmsUInt32Number   CMSEXPORT cmsGetHeaderFlags(cmsHPROFILE hProfile);
+CMSAPI void              CMSEXPORT cmsGetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number* Flags);
+CMSAPI void              CMSEXPORT cmsGetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID);
+CMSAPI cmsBool           CMSEXPORT cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile, struct tm *Dest);
+CMSAPI cmsUInt32Number   CMSEXPORT cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile);
+
+CMSAPI void              CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags);
+CMSAPI cmsUInt32Number   CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile);
+CMSAPI void              CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer);
+CMSAPI cmsUInt32Number   CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile);
+CMSAPI void              CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model);
+CMSAPI void              CMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number Flags);
+CMSAPI void              CMSEXPORT cmsSetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID);
+CMSAPI void              CMSEXPORT cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile, cmsUInt32Number RenderingIntent);
+
+CMSAPI cmsColorSpaceSignature
+                         CMSEXPORT cmsGetPCS(cmsHPROFILE hProfile);
+CMSAPI void              CMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, cmsColorSpaceSignature pcs);
+CMSAPI cmsColorSpaceSignature
+                         CMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile);
+CMSAPI void              CMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, cmsColorSpaceSignature sig);
+CMSAPI cmsProfileClassSignature
+                         CMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile);
+CMSAPI void              CMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, cmsProfileClassSignature sig);
+CMSAPI void              CMSEXPORT cmsSetProfileVersion(cmsHPROFILE hProfile, cmsFloat64Number Version);
+CMSAPI cmsFloat64Number  CMSEXPORT cmsGetProfileVersion(cmsHPROFILE hProfile);
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsGetEncodedICCversion(cmsHPROFILE hProfile);
+CMSAPI void              CMSEXPORT cmsSetEncodedICCversion(cmsHPROFILE hProfile, cmsUInt32Number Version);
+
+// How profiles may be used
+#define LCMS_USED_AS_INPUT      0
+#define LCMS_USED_AS_OUTPUT     1
+#define LCMS_USED_AS_PROOF      2
+
+CMSAPI cmsBool           CMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile, cmsUInt32Number Intent, int UsedDirection);
+CMSAPI cmsBool           CMSEXPORT cmsIsMatrixShaper(cmsHPROFILE hProfile);
+CMSAPI cmsBool           CMSEXPORT cmsIsCLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent, int UsedDirection);
+
+// Translate form/to our notation to ICC
+CMSAPI cmsColorSpaceSignature   CMSEXPORT _cmsICCcolorSpace(int OurNotation);
+CMSAPI int                      CMSEXPORT _cmsLCMScolorSpace(cmsColorSpaceSignature ProfileSpace);
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsChannelsOf(cmsColorSpaceSignature ColorSpace);
+
+// Build a suitable formatter for the colorspace of this profile
+CMSAPI cmsUInt32Number   CMSEXPORT cmsFormatterForColorspaceOfProfile(cmsHPROFILE hProfile, cmsUInt32Number nBytes, cmsBool lIsFloat);
+CMSAPI cmsUInt32Number   CMSEXPORT cmsFormatterForPCSOfProfile(cmsHPROFILE hProfile, cmsUInt32Number nBytes, cmsBool lIsFloat);
+
+
+// Localized info
+typedef enum {
+             cmsInfoDescription  = 0,
+             cmsInfoManufacturer = 1,
+             cmsInfoModel        = 2,
+             cmsInfoCopyright    = 3
+} cmsInfoType;
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsGetProfileInfo(cmsHPROFILE hProfile, cmsInfoType Info,
+                                                            const char LanguageCode[3], const char CountryCode[3],
+                                                            wchar_t* Buffer, cmsUInt32Number BufferSize);
+
+CMSAPI cmsUInt32Number   CMSEXPORT cmsGetProfileInfoASCII(cmsHPROFILE hProfile, cmsInfoType Info,
+                                                            const char LanguageCode[3], const char CountryCode[3],
+                                                            char* Buffer, cmsUInt32Number BufferSize);
+
+// IO handlers ----------------------------------------------------------------------------------------------------------
+
+typedef struct _cms_io_handler cmsIOHANDLER;
+
+CMSAPI cmsIOHANDLER*     CMSEXPORT cmsOpenIOhandlerFromFile(cmsContext ContextID, const char* FileName, const char* AccessMode);
+CMSAPI cmsIOHANDLER*     CMSEXPORT cmsOpenIOhandlerFromStream(cmsContext ContextID, FILE* Stream);
+CMSAPI cmsIOHANDLER*     CMSEXPORT cmsOpenIOhandlerFromMem(cmsContext ContextID, void *Buffer, cmsUInt32Number size, const char* AccessMode);
+CMSAPI cmsIOHANDLER*     CMSEXPORT cmsOpenIOhandlerFromNULL(cmsContext ContextID);
+CMSAPI cmsBool           CMSEXPORT cmsCloseIOhandler(cmsIOHANDLER* io);
+
+// MD5 message digest --------------------------------------------------------------------------------------------------
+
+CMSAPI cmsBool           CMSEXPORT cmsMD5computeID(cmsHPROFILE hProfile);
+
+// Profile high level funtions ------------------------------------------------------------------------------------------
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsOpenProfileFromFileTHR(cmsContext ContextID, const char *ICCProfile, const char *sAccess);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsOpenProfileFromStream(FILE* ICCProfile, const char* sAccess);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsOpenProfileFromStreamTHR(cmsContext ContextID, FILE* ICCProfile, const char* sAccess);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsOpenProfileFromMem(const void * MemPtr, cmsUInt32Number dwSize);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsOpenProfileFromMemTHR(cmsContext ContextID, const void * MemPtr, cmsUInt32Number dwSize);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID, cmsIOHANDLER* io);
+CMSAPI cmsBool          CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile);
+
+CMSAPI cmsBool          CMSEXPORT cmsSaveProfileToFile(cmsHPROFILE hProfile, const char* FileName);
+CMSAPI cmsBool          CMSEXPORT cmsSaveProfileToStream(cmsHPROFILE hProfile, FILE* Stream);
+CMSAPI cmsBool          CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUInt32Number* BytesNeeded);
+CMSAPI cmsUInt32Number  CMSEXPORT cmsSaveProfileToIOhandler(cmsHPROFILE hProfile, cmsIOHANDLER* io);
+
+// Predefined virtual profiles ------------------------------------------------------------------------------------------
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateRGBProfileTHR(cmsContext ContextID,
+                                                   const cmsCIExyY* WhitePoint,
+                                                   const cmsCIExyYTRIPLE* Primaries,
+                                                   cmsToneCurve* const TransferFunction[3]);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateRGBProfile(const cmsCIExyY* WhitePoint,
+                                                   const cmsCIExyYTRIPLE* Primaries,
+                                                   cmsToneCurve* const TransferFunction[3]);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateGrayProfileTHR(cmsContext ContextID,
+                                                    const cmsCIExyY* WhitePoint,
+                                                    const cmsToneCurve* TransferFunction);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateGrayProfile(const cmsCIExyY* WhitePoint,
+                                                    const cmsToneCurve* TransferFunction);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateLinearizationDeviceLinkTHR(cmsContext ContextID,
+                                                                cmsColorSpaceSignature ColorSpace,
+                                                                cmsToneCurve* const TransferFunctions[]);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateLinearizationDeviceLink(cmsColorSpaceSignature ColorSpace,
+                                                                cmsToneCurve* const TransferFunctions[]);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateInkLimitingDeviceLinkTHR(cmsContext ContextID,
+                                                              cmsColorSpaceSignature ColorSpace, cmsFloat64Number Limit);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateInkLimitingDeviceLink(cmsColorSpaceSignature ColorSpace, cmsFloat64Number Limit);
+
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateLab2ProfileTHR(cmsContext ContextID, const cmsCIExyY* WhitePoint);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateLab2Profile(const cmsCIExyY* WhitePoint);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateLab4ProfileTHR(cmsContext ContextID, const cmsCIExyY* WhitePoint);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateLab4Profile(const cmsCIExyY* WhitePoint);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateXYZProfileTHR(cmsContext ContextID);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateXYZProfile(void);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreate_sRGBProfileTHR(cmsContext ContextID);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreate_sRGBProfile(void);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateBCHSWabstractProfileTHR(cmsContext ContextID,
+                                                             int nLUTPoints,
+                                                             cmsFloat64Number Bright,
+                                                             cmsFloat64Number Contrast,
+                                                             cmsFloat64Number Hue,
+                                                             cmsFloat64Number Saturation,
+                                                             int TempSrc,
+                                                             int TempDest);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateBCHSWabstractProfile(int nLUTPoints,
+                                                             cmsFloat64Number Bright,
+                                                             cmsFloat64Number Contrast,
+                                                             cmsFloat64Number Hue,
+                                                             cmsFloat64Number Saturation,
+                                                             int TempSrc,
+                                                             int TempDest);
+
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateNULLProfileTHR(cmsContext ContextID);
+CMSAPI cmsHPROFILE      CMSEXPORT cmsCreateNULLProfile(void);
+
+// Converts a transform to a devicelink profile
+CMSAPI cmsHPROFILE      CMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, cmsFloat64Number Version, cmsUInt32Number dwFlags);
+
+// Intents ----------------------------------------------------------------------------------------------
+
+// ICC Intents
+#define INTENT_PERCEPTUAL                              0
+#define INTENT_RELATIVE_COLORIMETRIC                   1
+#define INTENT_SATURATION                              2
+#define INTENT_ABSOLUTE_COLORIMETRIC                   3
+
+// Non-ICC intents
+#define INTENT_PRESERVE_K_ONLY_PERCEPTUAL             10
+#define INTENT_PRESERVE_K_ONLY_RELATIVE_COLORIMETRIC  11
+#define INTENT_PRESERVE_K_ONLY_SATURATION             12
+#define INTENT_PRESERVE_K_PLANE_PERCEPTUAL            13
+#define INTENT_PRESERVE_K_PLANE_RELATIVE_COLORIMETRIC 14
+#define INTENT_PRESERVE_K_PLANE_SATURATION            15
+
+// Call with NULL as parameters to get the intent count
+CMSAPI cmsUInt32Number  CMSEXPORT cmsGetSupportedIntents(cmsUInt32Number nMax, cmsUInt32Number* Codes, char** Descriptions);
+
+// Flags
+
+#define cmsFLAGS_NOCACHE                  0x0040    // Inhibit 1-pixel cache
+#define cmsFLAGS_NOOPTIMIZE               0x0100    // Inhibit optimizations
+#define cmsFLAGS_NULLTRANSFORM            0x0200    // Don't transform anyway
+
+
+// Proofing flags
+#define cmsFLAGS_GAMUTCHECK               0x1000    // Out of Gamut alarm
+#define cmsFLAGS_SOFTPROOFING             0x4000    // Do softproofing
+
+// Misc
+#define cmsFLAGS_BLACKPOINTCOMPENSATION   0x2000
+#define cmsFLAGS_NOWHITEONWHITEFIXUP      0x0004    // Don't fix scum dot
+#define cmsFLAGS_HIGHRESPRECALC           0x0400    // Use more memory to give better accurancy
+#define cmsFLAGS_LOWRESPRECALC            0x0800    // Use less memory to minimize resouces
+
+// For devicelink creation
+#define cmsFLAGS_8BITS_DEVICELINK         0x0008   // Create 8 bits devicelinks
+#define cmsFLAGS_GUESSDEVICECLASS         0x0020   // Guess device class (for transform2devicelink)
+#define cmsFLAGS_KEEP_SEQUENCE            0x0080   // Keep profile sequence for devicelink creation
+
+// Specific to a particular optimizations
+#define cmsFLAGS_FORCE_CLUT               0x0002    // Force CLUT optimization
+#define cmsFLAGS_CLUT_POST_LINEARIZATION  0x0001    // create postlinearization tables if possible
+#define cmsFLAGS_CLUT_PRE_LINEARIZATION   0x0010    // create prelinearization tables if possible
+
+// Fine-tune control over number of gridpoints
+#define cmsFLAGS_GRIDPOINTS(n)           (((n) & 0xFF) << 16)
+
+// CRD special
+#define cmsFLAGS_NODEFAULTRESOURCEDEF     0x01000000
+
+// Transforms ---------------------------------------------------------------------------------------------------
+
+CMSAPI cmsHTRANSFORM    CMSEXPORT cmsCreateTransformTHR(cmsContext ContextID,
+                                                  cmsHPROFILE Input,
+                                                  cmsUInt32Number InputFormat,
+                                                  cmsHPROFILE Output,
+                                                  cmsUInt32Number OutputFormat,
+                                                  cmsUInt32Number Intent,
+                                                  cmsUInt32Number dwFlags);
+
+CMSAPI cmsHTRANSFORM    CMSEXPORT cmsCreateTransform(cmsHPROFILE Input,
+                                                  cmsUInt32Number InputFormat,
+                                                  cmsHPROFILE Output,
+                                                  cmsUInt32Number OutputFormat,
+                                                  cmsUInt32Number Intent,
+                                                  cmsUInt32Number dwFlags);
+
+CMSAPI cmsHTRANSFORM    CMSEXPORT cmsCreateProofingTransformTHR(cmsContext ContextID,
+                                                  cmsHPROFILE Input,
+                                                  cmsUInt32Number InputFormat,
+                                                  cmsHPROFILE Output,
+                                                  cmsUInt32Number OutputFormat,
+                                                  cmsHPROFILE Proofing,
+                                                  cmsUInt32Number Intent,
+                                                  cmsUInt32Number ProofingIntent,
+                                                  cmsUInt32Number dwFlags);
+
+CMSAPI cmsHTRANSFORM    CMSEXPORT cmsCreateProofingTransform(cmsHPROFILE Input,
+                                                  cmsUInt32Number InputFormat,
+                                                  cmsHPROFILE Output,
+                                                  cmsUInt32Number OutputFormat,
+                                                  cmsHPROFILE Proofing,
+                                                  cmsUInt32Number Intent,
+                                                  cmsUInt32Number ProofingIntent,
+                                                  cmsUInt32Number dwFlags);
+
+CMSAPI cmsHTRANSFORM    CMSEXPORT cmsCreateMultiprofileTransformTHR(cmsContext ContextID,
+                                                  cmsHPROFILE hProfiles[],
+                                                  cmsUInt32Number nProfiles,
+                                                  cmsUInt32Number InputFormat,
+                                                  cmsUInt32Number OutputFormat,
+                                                  cmsUInt32Number Intent,
+                                                  cmsUInt32Number dwFlags);
+
+
+CMSAPI cmsHTRANSFORM    CMSEXPORT cmsCreateMultiprofileTransform(cmsHPROFILE hProfiles[],
+                                                  cmsUInt32Number nProfiles,
+                                                  cmsUInt32Number InputFormat,
+                                                  cmsUInt32Number OutputFormat,
+                                                  cmsUInt32Number Intent,
+                                                  cmsUInt32Number dwFlags);
+
+
+CMSAPI cmsHTRANSFORM    CMSEXPORT cmsCreateExtendedTransform(cmsContext ContextID,
+                                                   cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[],
+                                                   cmsBool  BPC[],
+                                                   cmsUInt32Number Intents[],
+                                                   cmsFloat64Number AdaptationStates[],
+                                                   cmsHPROFILE hGamutProfile,
+                                                   cmsUInt32Number nGamutPCSposition,
+                                                   cmsUInt32Number InputFormat,
+                                                   cmsUInt32Number OutputFormat,
+                                                   cmsUInt32Number dwFlags);
+
+CMSAPI void             CMSEXPORT cmsDeleteTransform(cmsHTRANSFORM hTransform);
+
+CMSAPI void             CMSEXPORT cmsDoTransform(cmsHTRANSFORM Transform,
+                                                 const void * InputBuffer,
+                                                 void * OutputBuffer,
+                                                 cmsUInt32Number Size);
+
+CMSAPI void             CMSEXPORT cmsSetAlarmCodes(cmsUInt16Number NewAlarm[cmsMAXCHANNELS]);
+CMSAPI void             CMSEXPORT cmsGetAlarmCodes(cmsUInt16Number NewAlarm[cmsMAXCHANNELS]);
+
+// Adaptation state for absolute colorimetric intent
+CMSAPI cmsFloat64Number CMSEXPORT cmsSetAdaptationState(cmsFloat64Number d);
+
+CMSAPI cmsContext       CMSEXPORT cmsGetTransformContextID(cmsHTRANSFORM hTransform);
+
+
+// PostScript ColorRenderingDictionary and ColorSpaceArray ----------------------------------------------------
+
+typedef enum { cmsPS_RESOURCE_CSA, cmsPS_RESOURCE_CRD } cmsPSResourceType;
+
+// lcms2 unified method to access postscript color resources
+CMSAPI cmsUInt32Number  CMSEXPORT cmsGetPostScriptColorResource(cmsContext ContextID,
+                                                                cmsPSResourceType Type,
+                                                                cmsHPROFILE hProfile,
+                                                                cmsUInt32Number Intent,
+                                                                cmsUInt32Number dwFlags,
+                                                                cmsIOHANDLER* io);
+
+CMSAPI cmsUInt32Number  CMSEXPORT cmsGetPostScriptCSA(cmsContext ContextID, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags, void* Buffer, cmsUInt32Number dwBufferLen);
+CMSAPI cmsUInt32Number  CMSEXPORT cmsGetPostScriptCRD(cmsContext ContextID, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags, void* Buffer, cmsUInt32Number dwBufferLen);
+
+
+// IT8.7 / CGATS.17-200x handling -----------------------------------------------------------------------------
+
+CMSAPI cmsHANDLE        CMSEXPORT cmsIT8Alloc(cmsContext ContextID);
+CMSAPI void             CMSEXPORT cmsIT8Free(cmsHANDLE hIT8);
+
+// Tables
+CMSAPI cmsUInt32Number  CMSEXPORT cmsIT8TableCount(cmsHANDLE hIT8);
+CMSAPI cmsInt32Number   CMSEXPORT cmsIT8SetTable(cmsHANDLE hIT8, cmsUInt32Number nTable);
+
+// Persistence
+CMSAPI cmsHANDLE        CMSEXPORT cmsIT8LoadFromFile(cmsContext ContextID, const char* cFileName);
+CMSAPI cmsHANDLE        CMSEXPORT cmsIT8LoadFromMem(cmsContext ContextID, void *Ptr, cmsUInt32Number len);
+// CMSAPI cmsHANDLE        CMSEXPORT cmsIT8LoadFromIOhandler(cmsContext ContextID, cmsIOHANDLER* io);
+
+CMSAPI cmsBool          CMSEXPORT cmsIT8SaveToFile(cmsHANDLE hIT8, const char* cFileName);
+CMSAPI cmsBool          CMSEXPORT cmsIT8SaveToMem(cmsHANDLE hIT8, void *MemPtr, cmsUInt32Number* BytesNeeded);
+
+// Properties
+CMSAPI const char*      CMSEXPORT cmsIT8GetSheetType(cmsHANDLE hIT8);
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetSheetType(cmsHANDLE hIT8, const char* Type);
+
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetComment(cmsHANDLE hIT8, const char* cComment);
+
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetPropertyStr(cmsHANDLE hIT8, const char* cProp, const char *Str);
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetPropertyDbl(cmsHANDLE hIT8, const char* cProp, cmsFloat64Number Val);
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetPropertyHex(cmsHANDLE hIT8, const char* cProp, cmsUInt32Number Val);
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetPropertyUncooked(cmsHANDLE hIT8, const char* Key, const char* Buffer);
+
+
+CMSAPI const char*      CMSEXPORT cmsIT8GetProperty(cmsHANDLE hIT8, const char* cProp);
+CMSAPI cmsFloat64Number CMSEXPORT cmsIT8GetPropertyDbl(cmsHANDLE hIT8, const char* cProp);
+CMSAPI cmsUInt32Number  CMSEXPORT cmsIT8EnumProperties(cmsHANDLE hIT8, char ***PropertyNames);
+
+// Datasets
+CMSAPI const char*      CMSEXPORT cmsIT8GetDataRowCol(cmsHANDLE hIT8, int row, int col);
+CMSAPI cmsFloat64Number CMSEXPORT cmsIT8GetDataRowColDbl(cmsHANDLE hIT8, int row, int col);
+
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetDataRowCol(cmsHANDLE hIT8, int row, int col,
+                                                const char* Val);
+
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetDataRowColDbl(cmsHANDLE hIT8, int row, int col,
+                                                cmsFloat64Number Val);
+
+CMSAPI const char*      CMSEXPORT cmsIT8GetData(cmsHANDLE hIT8, const char* cPatch, const char* cSample);
+
+
+CMSAPI cmsFloat64Number CMSEXPORT cmsIT8GetDataDbl(cmsHANDLE hIT8, const char* cPatch, const char* cSample);
+
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetData(cmsHANDLE hIT8, const char* cPatch,
+                                                const char* cSample,
+                                                const char *Val);
+
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetDataDbl(cmsHANDLE hIT8, const char* cPatch,
+                                                const char* cSample,
+                                                cmsFloat64Number Val);
+
+CMSAPI int              CMSEXPORT cmsIT8FindDataFormat(cmsHANDLE hIT8, const char* cSample);
+CMSAPI cmsBool          CMSEXPORT cmsIT8SetDataFormat(cmsHANDLE hIT8, int n, const char *Sample);
+CMSAPI int              CMSEXPORT cmsIT8EnumDataFormat(cmsHANDLE hIT8, char ***SampleNames);
+
+CMSAPI const char*      CMSEXPORT cmsIT8GetPatchName(cmsHANDLE hIT8, int nPatch, char* buffer);
+
+// The LABEL extension
+CMSAPI int              CMSEXPORT cmsIT8SetTableByLabel(cmsHANDLE hIT8, const char* cSet, const char* cField, const char* ExpectedType);
+
+// Formatter for double
+CMSAPI void             CMSEXPORT cmsIT8DefineDblFormat(cmsHANDLE hIT8, const char* Formatter);
+
+// Gamut boundary description routines ------------------------------------------------------------------------------
+
+CMSAPI cmsHANDLE        CMSEXPORT cmsGBDAlloc(cmsContext ContextID);
+CMSAPI void             CMSEXPORT cmsGBDFree(cmsHANDLE hGBD);
+CMSAPI cmsBool          CMSEXPORT cmsGDBAddPoint(cmsHANDLE hGBD, const cmsCIELab* Lab);
+CMSAPI cmsBool          CMSEXPORT cmsGDBCompute(cmsHANDLE  hGDB, cmsUInt32Number dwFlags);
+CMSAPI cmsBool          CMSEXPORT cmsGDBCheckPoint(cmsHANDLE hGBD, const cmsCIELab* Lab);
+
+// Feature detection  ----------------------------------------------------------------------------------------------
+
+// Estimate the black point
+CMSAPI cmsBool          CMSEXPORT cmsDetectBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags);
+
+// Estimate total area coverage
+CMSAPI cmsFloat64Number CMSEXPORT cmsDetectTAC(cmsHPROFILE hProfile);
+
+
+// Poor man's gamut mapping
+CMSAPI cmsBool          CMSEXPORT cmsDesaturateLab(cmsCIELab* Lab,
+                                                   double amax, double amin,
+                                                   double bmax, double bmin);
+
+#ifndef CMS_USE_CPP_API
+#   ifdef __cplusplus
+    }
+#   endif
+#endif
+
+#define _lcms2_H
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,678 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+
+#ifndef _lcms_internal_H
+
+// Include plug-in foundation
+#ifndef _lcms_plugin_H
+#   include "lcms2_plugin.h"
+#endif
+
+// ctype is part of C99 as per 7.1.2
+#include <ctype.h>
+
+// assert macro is part of C99 as per 7.2
+#include <assert.h>
+
+// Some needed constants
+#ifndef M_PI
+#       define M_PI        3.14159265358979323846
+#endif
+
+#ifndef M_LOG10E
+#       define M_LOG10E    0.434294481903251827651
+#endif
+
+// BorlandC 5.5 is broken on that
+#ifdef __BORLANDC__
+#define sinf(x) (float)sin((float)x)
+#define sqrtf(x) (float)sqrt((float)x)
+#endif
+
+
+// Alignment of ICC file format uses 4 bytes (cmsUInt32Number)
+#define _cmsSIZEOFLONGMINUS1    (sizeof(cmsUInt32Number)-1)
+#define _cmsALIGNLONG(x) (((x)+_cmsSIZEOFLONGMINUS1) & ~(_cmsSIZEOFLONGMINUS1))
+
+// Maximum encodeable values in floating point
+#define MAX_ENCODEABLE_XYZ  (1.0 + 32767.0/32768.0)
+#define MIN_ENCODEABLE_ab2  (-128.0)
+#define MAX_ENCODEABLE_ab2  ((65535.0/256.0) - 128.0)
+#define MIN_ENCODEABLE_ab4  (-128.0)
+#define MAX_ENCODEABLE_ab4  (127.0)
+
+// Maximum of channels for internal pipeline evaluation
+#define MAX_STAGE_CHANNELS      128
+
+// Unused parameter warning supression
+#define cmsUNUSED_PARAMETER(x) ((void)x)
+
+// The specification for "inline" is section 6.7.4 of the C99 standard (ISO/IEC 9899:1999).
+// unfortunately VisualC++ does not conform that
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+#   define cmsINLINE __inline
+#else
+#   define cmsINLINE static inline
+#endif
+
+// Other replacement functions
+#ifdef _MSC_VER
+# ifndef snprintf
+#       define snprintf  _snprintf
+# endif
+# ifndef vsnprintf
+#       define vsnprintf  _vsnprintf
+# endif
+#endif
+
+// Pthreads. In windows we use the native WIN32 API instead
+#ifdef CMS_DONT_USE_PTHREADS
+typedef int LCMS_RWLOCK_T;
+#   define LCMS_CREATE_LOCK(x)
+#   define LCMS_FREE_LOCK(x)
+#   define LCMS_READ_LOCK(x)
+#   define LCMS_WRITE_LOCK(x)
+#   define LCMS_UNLOCK(x)
+#else
+#ifdef CMS_IS_WINDOWS_
+#   ifndef WIN32_LEAN_AND_MEAN
+#       define WIN32_LEAN_AND_MEAN
+#   endif
+#   include <windows.h>
+    typedef CRITICAL_SECTION LCMS_RWLOCK_T;
+#   define LCMS_CREATE_LOCK(x)       InitializeCriticalSection((x))
+#   define LCMS_FREE_LOCK(x)         DeleteCriticalSection((x))
+#   define LCMS_READ_LOCK(x)         EnterCriticalSection((x))
+#   define LCMS_WRITE_LOCK(x)        EnterCriticalSection((x))
+#   define LCMS_UNLOCK(x)            LeaveCriticalSection((x))
+#else
+#   include <pthread.h>
+    typedef    pthread_rwlock_t      LCMS_RWLOCK_T;
+#   define LCMS_CREATE_LOCK(x)       pthread_rwlock_init((x), NULL)
+#   define LCMS_FREE_LOCK(x)         pthread_rwlock_destroy((x))
+#   define LCMS_READ_LOCK(x)         pthread_rwlock_rdlock((x))
+#   define LCMS_WRITE_LOCK(x)        pthread_rwlock_wrlock((x))
+#   define LCMS_UNLOCK(x)            pthread_rwlock_unlock((x))
+#endif
+#endif
+
+// A fast way to convert from/to 16 <-> 8 bits
+#define FROM_8_TO_16(rgb) (cmsUInt16Number) ((((cmsUInt16Number) (rgb)) << 8)|(rgb))
+#define FROM_16_TO_8(rgb) (cmsUInt8Number) ((((rgb) * 65281 + 8388608) >> 24) & 0xFF)
+
+// Code analysis is broken on asserts
+#ifdef _MSC_VER
+#    if (_MSC_VER >= 1500)
+#            define _cmsAssert(a)  { assert((a)); __analysis_assume((a)); }
+#     else
+#            define _cmsAssert(a)   assert((a))
+#     endif
+#else
+#      define _cmsAssert(a)   assert((a))
+#endif
+
+//---------------------------------------------------------------------------------
+
+// Determinant lower than that are assumed zero (used on matrix invert)
+#define MATRIX_DET_TOLERANCE    0.0001
+
+//---------------------------------------------------------------------------------
+
+// Fixed point
+#define FIXED_TO_INT(x)         ((x)>>16)
+#define FIXED_REST_TO_INT(x)    ((x)&0xFFFFU)
+#define ROUND_FIXED_TO_INT(x)   (((x)+0x8000)>>16)
+
+cmsINLINE cmsS15Fixed16Number _cmsToFixedDomain(int a)                   { return a + ((a + 0x7fff) / 0xffff); }
+cmsINLINE int                 _cmsFromFixedDomain(cmsS15Fixed16Number a) { return a - ((a + 0x7fff) >> 16); }
+
+// -----------------------------------------------------------------------------------------------------------
+
+// Fast floor conversion logic. Thanks to Sree Kotay and Stuart Nixon
+// note than this only works in the range ..-32767...+32767 because
+// mantissa is interpreted as 15.16 fixed point.
+// The union is to avoid pointer aliasing overoptimization.
+cmsINLINE int _cmsQuickFloor(cmsFloat64Number val)
+{
+#ifdef CMS_DONT_USE_FAST_FLOOR
+    return (int) floor(val);
+#else
+    const cmsFloat64Number _lcms_double2fixmagic = 68719476736.0 * 1.5;  // 2^36 * 1.5, (52-16=36) uses limited precision to floor
+    union {
+        cmsFloat64Number val;
+        int halves[2];
+    } temp;
+
+    temp.val = val + _lcms_double2fixmagic;
+
+#ifdef CMS_USE_BIG_ENDIAN
+    return temp.halves[1] >> 16;
+#else
+    return temp.halves[0] >> 16;
+#endif
+#endif
+}
+
+// Fast floor restricted to 0..65535.0
+cmsINLINE cmsUInt16Number _cmsQuickFloorWord(cmsFloat64Number d)
+{
+    return (cmsUInt16Number) _cmsQuickFloor(d - 32767.0) + 32767U;
+}
+
+// Floor to word, taking care of saturation
+cmsINLINE cmsUInt16Number _cmsQuickSaturateWord(cmsFloat64Number d)
+{
+    d += 0.5;
+    if (d <= 0) return 0;
+    if (d >= 65535.0) return 0xffff;
+
+    return _cmsQuickFloorWord(d);
+}
+
+// Plug-In registering ---------------------------------------------------------------
+
+// Specialized function for plug-in memory management. No pairing free() since whole pool is freed at once.
+void* _cmsPluginMalloc(cmsUInt32Number size);
+
+// Memory management
+cmsBool   _cmsRegisterMemHandlerPlugin(cmsPluginBase* Plugin);
+
+// Interpolation
+cmsBool  _cmsRegisterInterpPlugin(cmsPluginBase* Plugin);
+
+// Parametric curves
+cmsBool  _cmsRegisterParametricCurvesPlugin(cmsPluginBase* Plugin);
+
+// Formatters management
+cmsBool  _cmsRegisterFormattersPlugin(cmsPluginBase* Plugin);
+
+// Tag type management
+cmsBool  _cmsRegisterTagTypePlugin(cmsPluginBase* Plugin);
+
+// Tag management
+cmsBool  _cmsRegisterTagPlugin(cmsPluginBase* Plugin);
+
+// Intent management
+cmsBool  _cmsRegisterRenderingIntentPlugin(cmsPluginBase* Plugin);
+
+// Multi Process elements
+cmsBool  _cmsRegisterMultiProcessElementPlugin(cmsPluginBase* Plugin);
+
+// Optimization
+cmsBool  _cmsRegisterOptimizationPlugin(cmsPluginBase* Plugin);
+
+
+// ---------------------------------------------------------------------------------------------------------
+
+// Suballocators. Those are blocks of memory that is freed at the end on whole block.
+typedef struct _cmsSubAllocator_chunk_st {
+
+    cmsUInt8Number* Block;
+    cmsUInt32Number BlockSize;
+    cmsUInt32Number Used;
+
+    struct _cmsSubAllocator_chunk_st* next;
+
+} _cmsSubAllocator_chunk;
+
+
+typedef struct {
+
+    cmsContext ContextID;
+    _cmsSubAllocator_chunk* h;
+
+} _cmsSubAllocator;
+
+
+_cmsSubAllocator* _cmsCreateSubAlloc(cmsContext ContextID, cmsUInt32Number Initial);
+void              _cmsSubAllocDestroy(_cmsSubAllocator* s);
+void*             _cmsSubAlloc(_cmsSubAllocator* s, cmsUInt32Number size);
+
+// ----------------------------------------------------------------------------------
+
+// MLU internal representation
+typedef struct {
+
+    cmsUInt16Number Language;
+    cmsUInt16Number Country;
+
+    cmsUInt32Number StrW;       // Offset to current unicode string
+    cmsUInt32Number Len;        // Lenght in bytes
+
+} _cmsMLUentry;
+
+struct _cms_MLU_struct {
+
+    cmsContext ContextID;
+
+    // The directory
+    int AllocatedEntries;
+    int UsedEntries;
+    _cmsMLUentry* Entries;     // Array of pointers to strings allocated in MemPool
+
+    // The Pool
+    cmsUInt32Number PoolSize;  // The maximum allocated size
+    cmsUInt32Number PoolUsed;  // The used size
+    void*  MemPool;            // Pointer to begin of memory pool
+};
+
+// Named color list internal representation
+typedef struct {
+
+    char Name[cmsMAX_PATH];
+    cmsUInt16Number PCS[3];
+    cmsUInt16Number DeviceColorant[cmsMAXCHANNELS];
+
+} _cmsNAMEDCOLOR;
+
+struct _cms_NAMEDCOLORLIST_struct {
+
+    cmsUInt32Number nColors;
+    cmsUInt32Number Allocated;
+    cmsUInt32Number ColorantCount;
+
+    char Prefix[33];      // Prefix and suffix are defined to be 32 characters at most
+    char Suffix[33];
+
+    _cmsNAMEDCOLOR* List;
+
+    cmsContext ContextID;
+};
+
+
+// ----------------------------------------------------------------------------------
+
+// This is the internal struct holding profile details.
+
+// Maximum supported tags in a profile
+#define MAX_TABLE_TAG       100
+
+typedef struct _cms_iccprofile_struct {
+
+    // I/O handler
+    cmsIOHANDLER*            IOhandler;
+
+    // The thread ID
+    cmsContext               ContextID;
+
+    // Creation time
+    struct tm                Created;
+
+    // Only most important items found in ICC profiles
+    cmsUInt32Number          Version;
+    cmsProfileClassSignature DeviceClass;
+    cmsColorSpaceSignature   ColorSpace;
+    cmsColorSpaceSignature   PCS;
+    cmsUInt32Number          RenderingIntent;
+    cmsUInt32Number          flags;
+    cmsUInt32Number          manufacturer, model;
+    cmsUInt64Number          attributes;
+
+    cmsProfileID             ProfileID;
+
+    // Dictionary
+    cmsUInt32Number          TagCount;
+    cmsTagSignature          TagNames[MAX_TABLE_TAG];
+    cmsTagSignature          TagLinked[MAX_TABLE_TAG];           // The tag to wich is linked (0=none)
+    cmsUInt32Number          TagSizes[MAX_TABLE_TAG];            // Size on disk
+    cmsUInt32Number          TagOffsets[MAX_TABLE_TAG];
+    cmsBool                  TagSaveAsRaw[MAX_TABLE_TAG];        // True to write uncooked
+    void *                   TagPtrs[MAX_TABLE_TAG];
+    cmsTagTypeHandler*       TagTypeHandlers[MAX_TABLE_TAG];     // Same structure may be serialized on different types
+                                                                 // depending on profile version, so we keep track of the                                                             // type handler for each tag in the list.
+    // Special
+    cmsBool                  IsWrite;
+
+} _cmsICCPROFILE;
+
+// IO helpers for profiles
+cmsBool              _cmsReadHeader(_cmsICCPROFILE* Icc);
+cmsBool              _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace);
+int                  _cmsSearchTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, cmsBool lFollowLinks);
+
+// Tag types
+cmsTagTypeHandler*   _cmsGetTagTypeHandler(cmsTagTypeSignature sig);
+cmsTagTypeSignature  _cmsGetTagTrueType(cmsHPROFILE hProfile, cmsTagSignature sig);
+cmsTagDescriptor*    _cmsGetTagDescriptor(cmsTagSignature sig);
+
+// Error logging ---------------------------------------------------------------------------------------------------------
+
+void                 _cmsTagSignature2String(char String[5], cmsTagSignature sig);
+
+// Interpolation ---------------------------------------------------------------------------------------------------------
+
+cmsInterpParams*     _cmsComputeInterpParams(cmsContext ContextID, int nSamples, int InputChan, int OutputChan, const void* Table, cmsUInt32Number dwFlags);
+cmsInterpParams*     _cmsComputeInterpParamsEx(cmsContext ContextID, const cmsUInt32Number nSamples[], int InputChan, int OutputChan, const void* Table, cmsUInt32Number dwFlags);
+void                 _cmsFreeInterpParams(cmsInterpParams* p);
+
+// Curves ----------------------------------------------------------------------------------------------------------------
+
+// This struct holds information about a segment, plus a pointer to the function that implements the evaluation.
+// In the case of table-based, Eval pointer is set to NULL
+
+// The gamma function main structure
+struct _cms_curve_struct {
+
+    cmsInterpParams*  InterpParams;  // Private optimizations for interpolation
+
+    cmsUInt32Number   nSegments;     // Number of segments in the curve. Zero for a 16-bit based tables
+    cmsCurveSegment*  Segments;      // The segments
+    cmsInterpParams** SegInterp;     // Array of private optimizations for interpolation in table-based segments
+
+    cmsParametricCurveEvaluator* Evals;  // Evaluators (one per segment)
+
+    // 16 bit Table-based representation follows
+    cmsUInt32Number    nEntries;      // Number of table elements
+    cmsUInt16Number*   Table16;       // The table itself.
+};
+
+
+//  Pipelines & Stages ---------------------------------------------------------------------------------------------
+
+// A single stage
+struct _cmsStage_struct {
+
+    cmsContext          ContextID;
+
+    cmsStageSignature   Type;           // Identifies the stage
+    cmsStageSignature   Implements;     // Identifies the *function* of the stage (for optimizations)
+
+    cmsUInt32Number     InputChannels;  // Input channels -- for optimization purposes
+    cmsUInt32Number     OutputChannels; // Output channels -- for optimization purposes
+
+    _cmsStageEvalFn     EvalPtr;        // Points to fn that evaluates the stage (always in floating point)
+    _cmsStageDupElemFn  DupElemPtr;     // Points to a fn that duplicates the *data* of the stage
+    _cmsStageFreeElemFn FreePtr;        // Points to a fn that sets the *data* of the stage free
+
+    // A generic pointer to whatever memory needed by the stage
+    void*               Data;
+
+    // Maintains linked list (used internally)
+    struct _cmsStage_struct* Next;
+};
+
+// Data kept in "Element" member of cmsStage
+
+// Curves
+typedef struct {
+    cmsUInt32Number nCurves;
+    cmsToneCurve**  TheCurves;
+
+} _cmsStageToneCurvesData;
+
+// Matrix
+typedef struct {
+    cmsFloat64Number*  Double;          // floating point for the matrix
+    cmsFloat64Number*  Offset;          // The offset
+
+} _cmsStageMatrixData;
+
+// CLUT
+typedef struct {
+
+    union {                       // Can have only one of both representations at same time
+        cmsUInt16Number*  T;      // Points to the table 16 bits table
+        cmsFloat32Number* TFloat; // Points to the cmsFloat32Number table
+
+    } Tab;
+
+    cmsInterpParams* Params;
+    cmsUInt32Number  nEntries;
+    cmsBool          HasFloatValues;
+
+} _cmsStageCLutData;
+
+
+// Special Stages (cannot be saved)
+cmsStage*        _cmsStageAllocLab2XYZ(cmsContext ContextID);
+cmsStage*        _cmsStageAllocXYZ2Lab(cmsContext ContextID);
+cmsStage*        _cmsStageAllocLabPrelin(cmsContext ContextID);
+cmsStage*        _cmsStageAllocLabV2ToV4(cmsContext ContextID);
+cmsStage*        _cmsStageAllocLabV2ToV4curves(cmsContext ContextID);
+cmsStage*        _cmsStageAllocLabV4ToV2(cmsContext ContextID);
+cmsStage*        _cmsStageAllocNamedColor(cmsNAMEDCOLORLIST* NamedColorList);
+cmsStage*        _cmsStageAllocIdentityCurves(cmsContext ContextID, int nChannels);
+cmsStage*        _cmsStageAllocIdentityCLut(cmsContext ContextID, int nChan);
+
+// For curve set only
+cmsToneCurve**     _cmsStageGetPtrToCurveSet(const cmsStage* mpe);
+
+
+// Pipeline Evaluator (in floating point)
+typedef void (* _cmsPipelineEvalFloatFn)(const cmsFloat32Number In[],
+                                         cmsFloat32Number Out[],
+                                         const void* Data);
+
+struct _cmsPipeline_struct {
+
+    cmsStage* Elements;                                // Points to elements chain
+    cmsUInt32Number InputChannels, OutputChannels;
+
+    // Data & evaluators
+    void *Data;
+
+   _cmsOPTeval16Fn         Eval16Fn;
+   _cmsPipelineEvalFloatFn EvalFloatFn;
+   _cmsOPTfreeDataFn       FreeDataFn;
+   _cmsOPTdupDataFn        DupDataFn;
+
+    cmsContext ContextID;            // Environment
+
+    cmsBool  SaveAs8Bits;            // Implemntation-specific: save as 8 bits if possible
+};
+
+// LUT reading & creation -------------------------------------------------------------------------------------------
+
+// Read tags using low-level function, provide necessary glue code to adapt versions, etc. All those return a brand new copy
+// of the LUTS, since ownership of original is up to the profile. The user should free allocated resources.
+
+cmsPipeline*      _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent);
+cmsPipeline*      _cmsReadOutputLUT(cmsHPROFILE hProfile, int Intent);
+cmsPipeline*      _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent);
+
+// Special values
+cmsBool           _cmsReadMediaWhitePoint(cmsCIEXYZ* Dest, cmsHPROFILE hProfile);
+cmsBool           _cmsReadCHAD(cmsMAT3* Dest, cmsHPROFILE hProfile);
+
+// Profile linker --------------------------------------------------------------------------------------------------
+
+cmsPipeline* _cmsLinkProfiles(cmsContext         ContextID,
+                              cmsUInt32Number    nProfiles,
+                              cmsUInt32Number    TheIntents[],
+                              cmsHPROFILE        hProfiles[],
+                              cmsBool            BPC[],
+                              cmsFloat64Number   AdaptationStates[],
+                              cmsUInt32Number    dwFlags);
+
+// Sequence --------------------------------------------------------------------------------------------------------
+
+cmsSEQ* _cmsReadProfileSequence(cmsHPROFILE hProfile);
+cmsBool _cmsWriteProfileSequence(cmsHPROFILE hProfile, const cmsSEQ* seq);
+cmsSEQ* _cmsCompileProfileSequence(cmsContext ContextID, cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[]);
+
+
+// LUT optimization ------------------------------------------------------------------------------------------------
+
+cmsUInt16Number  _cmsQuantizeVal(cmsFloat64Number i, int MaxSamples);
+int              _cmsReasonableGridpointsByColorspace(cmsColorSpaceSignature Colorspace, cmsUInt32Number dwFlags);
+
+cmsBool          _cmsEndPointsBySpace(cmsColorSpaceSignature Space,
+                                      cmsUInt16Number **White,
+                                      cmsUInt16Number **Black,
+                                      cmsUInt32Number *nOutputs);
+
+cmsBool          _cmsOptimizePipeline(cmsPipeline**    Lut,
+                                      int              Intent,
+                                      cmsUInt32Number* InputFormat,
+                                      cmsUInt32Number* OutputFormat,
+                                      cmsUInt32Number* dwFlags );
+
+
+// Hi level LUT building ----------------------------------------------------------------------------------------------
+
+cmsPipeline*     _cmsCreateGamutCheckPipeline(cmsContext ContextID,
+                                              cmsHPROFILE hProfiles[],
+                                              cmsBool  BPC[],
+                                              cmsUInt32Number Intents[],
+                                              cmsFloat64Number AdaptationStates[],
+                                              cmsUInt32Number nGamutPCSposition,
+                                              cmsHPROFILE hGamut);
+
+
+// Formatters ------------------------------------------------------------------------------------------------------------
+
+cmsBool         _cmsFormatterIsFloat(cmsUInt32Number Type);
+cmsBool         _cmsFormatterIs8bit(cmsUInt32Number Type);
+
+cmsFormatter    _cmsGetFormatter(cmsUInt32Number Type,          // Specific type, i.e. TYPE_RGB_8
+                                 cmsFormatterDirection Dir,
+                                 cmsUInt32Number dwFlags);
+
+
+// Transform logic ------------------------------------------------------------------------------------------------------
+
+struct _cmstransform_struct;
+
+// Full xform
+typedef void (* _cmsTransformFn)(struct _cmstransform_struct *Transform,
+                                 const void* InputBuffer,
+                                 void* OutputBuffer, cmsUInt32Number Size);
+
+typedef struct {
+
+    cmsUInt32Number InputFormat, OutputFormat; // Keep formats for further reference
+    cmsUInt32Number StrideIn, StrideOut;       // Planar support
+
+} cmsFormatterInfo;
+
+// Transformation
+typedef struct _cmstransform_struct {
+
+    cmsUInt32Number InputFormat, OutputFormat; // Keep formats for further reference
+
+    // Points to transform code
+    _cmsTransformFn xform;
+
+    // Formatters, cannot be embedded into LUT because cache
+    cmsFormatter16 FromInput;
+    cmsFormatter16 ToOutput;
+
+    cmsFormatterFloat FromInputFloat;
+    cmsFormatterFloat ToOutputFloat;
+
+    // 1-pixel cache (16 bits only)
+    cmsUInt16Number CacheIn[cmsMAXCHANNELS];
+    cmsUInt16Number CacheOut[cmsMAXCHANNELS];
+
+    // Semaphor for cache
+    LCMS_RWLOCK_T rwlock;
+
+    // A MPE LUT holding the full (optimized) transform
+    cmsPipeline* Lut;
+
+    // A MPE LUT holding the gamut check. It goes from the input space to bilevel
+    cmsPipeline* GamutCheck;
+
+    // Colorant tables
+    cmsNAMEDCOLORLIST* InputColorant;       // Input Colorant table
+    cmsNAMEDCOLORLIST* OutputColorant;      // Colorant table (for n chans > CMYK)
+
+    // Informational only
+    cmsColorSpaceSignature EntryColorSpace;
+    cmsColorSpaceSignature ExitColorSpace;
+
+    // Profiles used to create the transform
+    cmsSEQ* Sequence;
+
+    cmsUInt32Number  dwOriginalFlags;
+    cmsFloat64Number AdaptationState;
+
+    // The intent of this transform. That is usually the last intent in the profilechain, but may differ
+    cmsUInt32Number RenderingIntent;
+
+    // An id that uniquely identifies the running context. May be null.
+    cmsContext ContextID;
+
+} _cmsTRANSFORM;
+
+// --------------------------------------------------------------------------------------------------
+
+cmsHTRANSFORM _cmsChain2Lab(cmsContext             ContextID,
+                            cmsUInt32Number        nProfiles,
+                            cmsUInt32Number        InputFormat,
+                            cmsUInt32Number        OutputFormat,
+                            const cmsUInt32Number  Intents[],
+                            const cmsHPROFILE      hProfiles[],
+                            const cmsBool          BPC[],
+                            const cmsFloat64Number AdaptationStates[],
+                            cmsUInt32Number        dwFlags);
+
+
+cmsToneCurve* _cmsBuildKToneCurve(cmsContext       ContextID,
+                            cmsUInt32Number        nPoints,
+                            cmsUInt32Number        nProfiles,
+                            const cmsUInt32Number  Intents[],
+                            const cmsHPROFILE      hProfiles[],
+                            const cmsBool          BPC[],
+                            const cmsFloat64Number AdaptationStates[],
+                            cmsUInt32Number        dwFlags);
+
+cmsBool   _cmsAdaptationMatrix(cmsMAT3* r, const cmsMAT3* ConeMatrix, const cmsCIEXYZ* FromIll, const cmsCIEXYZ* ToIll);
+
+cmsBool   _cmsBuildRGB2XYZtransferMatrix(cmsMAT3* r, const cmsCIExyY* WhitePoint, const cmsCIExyYTRIPLE* Primaries);
+
+
+#define _lcms_internal_H
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,562 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This file is available under and governed by the GNU General Public
+// License version 2 only, as published by the Free Software Foundation.
+// However, the following notice accompanied the original version of this
+// file:
+//
+//---------------------------------------------------------------------------------
+//
+//  Little Color Management System
+//  Copyright (c) 1998-2010 Marti Maria Saguer
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+//---------------------------------------------------------------------------------
+//
+// This is the plug-in header file. Normal LittleCMS clients should not use it.
+// It is provided for plug-in writters that may want to access the support
+// functions to do low level operations. All plug-in related structures
+// are defined here. Including this file forces to include the standard API too.
+
+#ifndef _lcms_plugin_H
+
+// Deal with Microsoft's attempt at deprecating C standard runtime functions
+#ifdef _MSC_VER
+#    if (_MSC_VER >= 1400)
+#      ifndef _CRT_SECURE_NO_DEPRECATE
+#        define _CRT_SECURE_NO_DEPRECATE
+#      endif
+#      ifndef _CRT_SECURE_NO_WARNINGS
+#        define _CRT_SECURE_NO_WARNINGS
+#      endif
+#    endif
+#endif
+
+#ifndef _lcms2_H
+#include "lcms2.h"
+#endif
+
+// We need some standard C functions.
+#include <stdlib.h>
+#include <math.h>
+#include <stdarg.h>
+#include <memory.h>
+#include <string.h>
+
+
+#ifndef CMS_USE_CPP_API
+#   ifdef __cplusplus
+extern "C" {
+#   endif
+#endif
+
+// Vector & Matrix operations -----------------------------------------------------------------------
+
+// Axis of the matrix/array. No specific meaning at all.
+#define VX      0
+#define VY      1
+#define VZ      2
+
+// Vectors
+typedef struct {
+    cmsFloat64Number n[3];
+
+    } cmsVEC3;
+
+// 3x3 Matrix
+typedef struct {
+    cmsVEC3 v[3];
+
+    } cmsMAT3;
+
+CMSAPI void               CMSEXPORT _cmsVEC3init(cmsVEC3* r, cmsFloat64Number x, cmsFloat64Number y, cmsFloat64Number z);
+CMSAPI void               CMSEXPORT _cmsVEC3minus(cmsVEC3* r, const cmsVEC3* a, const cmsVEC3* b);
+CMSAPI void               CMSEXPORT _cmsVEC3cross(cmsVEC3* r, const cmsVEC3* u, const cmsVEC3* v);
+CMSAPI cmsFloat64Number   CMSEXPORT _cmsVEC3dot(const cmsVEC3* u, const cmsVEC3* v);
+CMSAPI cmsFloat64Number   CMSEXPORT _cmsVEC3length(const cmsVEC3* a);
+CMSAPI cmsFloat64Number   CMSEXPORT _cmsVEC3distance(const cmsVEC3* a, const cmsVEC3* b);
+
+CMSAPI void               CMSEXPORT _cmsMAT3identity(cmsMAT3* a);
+CMSAPI cmsBool            CMSEXPORT _cmsMAT3isIdentity(const cmsMAT3* a);
+CMSAPI void               CMSEXPORT _cmsMAT3per(cmsMAT3* r, const cmsMAT3* a, const cmsMAT3* b);
+CMSAPI cmsBool            CMSEXPORT _cmsMAT3inverse(const cmsMAT3* a, cmsMAT3* b);
+CMSAPI cmsBool            CMSEXPORT _cmsMAT3solve(cmsVEC3* x, cmsMAT3* a, cmsVEC3* b);
+CMSAPI void               CMSEXPORT _cmsMAT3eval(cmsVEC3* r, const cmsMAT3* a, const cmsVEC3* v);
+
+
+// Error logging  -------------------------------------------------------------------------------------
+
+CMSAPI void               CMSEXPORT  cmsSignalError(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *ErrorText, ...);
+
+// Memory management ----------------------------------------------------------------------------------
+
+CMSAPI void*              CMSEXPORT _cmsMalloc(cmsContext ContextID, cmsUInt32Number size);
+CMSAPI void*              CMSEXPORT _cmsMallocZero(cmsContext ContextID, cmsUInt32Number size);
+CMSAPI void*              CMSEXPORT _cmsCalloc(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size);
+CMSAPI void*              CMSEXPORT _cmsRealloc(cmsContext ContextID, void* Ptr, cmsUInt32Number NewSize);
+CMSAPI void               CMSEXPORT _cmsFree(cmsContext ContextID, void* Ptr);
+CMSAPI void*              CMSEXPORT _cmsDupMem(cmsContext ContextID, const void* Org, cmsUInt32Number size);
+
+// I/O handler ----------------------------------------------------------------------------------
+
+struct _cms_io_handler {
+
+    void* stream;   // Associated stream, which is implemented differently depending on media.
+
+    cmsContext        ContextID;
+    cmsUInt32Number   UsedSpace;
+    char              PhysicalFile[cmsMAX_PATH];
+
+    cmsUInt32Number   (* Read)(struct _cms_io_handler* iohandler, void *Buffer,
+                                                                  cmsUInt32Number size,
+                                                                  cmsUInt32Number count);
+    cmsBool           (* Seek)(struct _cms_io_handler* iohandler, cmsUInt32Number offset);
+    cmsBool           (* Close)(struct _cms_io_handler* iohandler);
+    cmsUInt32Number   (* Tell)(struct _cms_io_handler* iohandler);
+    cmsBool           (* Write)(struct _cms_io_handler* iohandler, cmsUInt32Number size,
+                                                                   const void* Buffer);
+};
+
+// Endianess adjust functions
+CMSAPI cmsUInt16Number   CMSEXPORT  _cmsAdjustEndianess16(cmsUInt16Number Word);
+CMSAPI cmsUInt32Number   CMSEXPORT  _cmsAdjustEndianess32(cmsUInt32Number Value);
+CMSAPI void              CMSEXPORT  _cmsAdjustEndianess64(cmsUInt64Number* Result, cmsUInt64Number QWord);
+
+// Helper IO functions
+CMSAPI cmsBool           CMSEXPORT  _cmsReadUInt8Number(cmsIOHANDLER* io,  cmsUInt8Number* n);
+CMSAPI cmsBool           CMSEXPORT  _cmsReadUInt16Number(cmsIOHANDLER* io, cmsUInt16Number* n);
+CMSAPI cmsBool           CMSEXPORT  _cmsReadUInt32Number(cmsIOHANDLER* io, cmsUInt32Number* n);
+CMSAPI cmsBool           CMSEXPORT  _cmsReadFloat32Number(cmsIOHANDLER* io, cmsFloat32Number* n);
+CMSAPI cmsBool           CMSEXPORT  _cmsReadUInt64Number(cmsIOHANDLER* io, cmsUInt64Number* n);
+CMSAPI cmsBool           CMSEXPORT  _cmsRead15Fixed16Number(cmsIOHANDLER* io, cmsFloat64Number* n);
+CMSAPI cmsBool           CMSEXPORT  _cmsReadXYZNumber(cmsIOHANDLER* io, cmsCIEXYZ* XYZ);
+CMSAPI cmsBool           CMSEXPORT  _cmsReadUInt16Array(cmsIOHANDLER* io, cmsUInt32Number n, cmsUInt16Number* Array);
+
+CMSAPI cmsBool           CMSEXPORT  _cmsWriteUInt8Number(cmsIOHANDLER* io, cmsUInt8Number n);
+CMSAPI cmsBool           CMSEXPORT  _cmsWriteUInt16Number(cmsIOHANDLER* io, cmsUInt16Number n);
+CMSAPI cmsBool           CMSEXPORT  _cmsWriteUInt32Number(cmsIOHANDLER* io, cmsUInt32Number n);
+CMSAPI cmsBool           CMSEXPORT  _cmsWriteFloat32Number(cmsIOHANDLER* io, cmsFloat32Number n);
+CMSAPI cmsBool           CMSEXPORT  _cmsWriteUInt64Number(cmsIOHANDLER* io, cmsUInt64Number n);
+CMSAPI cmsBool           CMSEXPORT  _cmsWrite15Fixed16Number(cmsIOHANDLER* io, cmsFloat64Number n);
+CMSAPI cmsBool           CMSEXPORT  _cmsWriteXYZNumber(cmsIOHANDLER* io, const cmsCIEXYZ* XYZ);
+CMSAPI cmsBool           CMSEXPORT  _cmsWriteUInt16Array(cmsIOHANDLER* io, cmsUInt32Number n, const cmsUInt16Number* Array);
+
+// ICC base tag
+typedef struct {
+    cmsTagTypeSignature  sig;
+    cmsInt8Number        reserved[4];
+
+} _cmsTagBase;
+
+// Type base helper functions
+CMSAPI cmsTagTypeSignature  CMSEXPORT _cmsReadTypeBase(cmsIOHANDLER* io);
+CMSAPI cmsBool              CMSEXPORT _cmsWriteTypeBase(cmsIOHANDLER* io, cmsTagTypeSignature sig);
+
+// Alignment functions
+CMSAPI cmsBool             CMSEXPORT _cmsReadAlignment(cmsIOHANDLER* io);
+CMSAPI cmsBool             CMSEXPORT _cmsWriteAlignment(cmsIOHANDLER* io);
+
+// To deal with text streams. 2K at most
+CMSAPI cmsBool             CMSEXPORT _cmsIOPrintf(cmsIOHANDLER* io, const char* frm, ...);
+
+// Fixed point helper functions
+CMSAPI cmsFloat64Number    CMSEXPORT _cms8Fixed8toDouble(cmsUInt16Number fixed8);
+CMSAPI cmsUInt16Number     CMSEXPORT _cmsDoubleTo8Fixed8(cmsFloat64Number val);
+
+CMSAPI cmsFloat64Number    CMSEXPORT _cms15Fixed16toDouble(cmsS15Fixed16Number fix32);
+CMSAPI cmsS15Fixed16Number CMSEXPORT _cmsDoubleTo15Fixed16(cmsFloat64Number v);
+
+// Date/time helper functions
+CMSAPI void                CMSEXPORT _cmsEncodeDateTimeNumber(cmsDateTimeNumber *Dest, const struct tm *Source);
+CMSAPI void                CMSEXPORT _cmsDecodeDateTimeNumber(const cmsDateTimeNumber *Source, struct tm *Dest);
+
+
+//----------------------------------------------------------------------------------------------------------
+
+// Plug-in foundation
+#define cmsPluginMagicNumber                 0x61637070     // 'acpp'
+
+#define cmsPluginMemHandlerSig               0x6D656D48     // 'memH'
+#define cmsPluginInterpolationSig            0x696E7048     // 'inpH'
+#define cmsPluginParametricCurveSig          0x70617248     // 'parH'
+#define cmsPluginFormattersSig               0x66726D48     // 'frmH
+#define cmsPluginTagTypeSig                  0x74797048     // 'typH'
+#define cmsPluginTagSig                      0x74616748     // 'tagH'
+#define cmsPluginRenderingIntentSig          0x696E7448     // 'intH'
+#define cmsPluginMultiProcessElementSig      0x6D706548     // 'mpeH'
+#define cmsPluginOptimizationSig             0x6F707448     // 'optH'
+
+typedef struct _cmsPluginBaseStruct {
+
+        cmsUInt32Number                Magic;               // 'acpp' signature
+        cmsUInt32Number                ExpectedVersion;     // Expected version of LittleCMS
+        cmsUInt32Number                Type;                // Type of plug-in
+        struct _cmsPluginBaseStruct*   Next;                // For multiple plugin definition. NULL for end of list.
+
+} cmsPluginBase;
+
+// Maximum number of types in a plugin array
+#define MAX_TYPES_IN_LCMS_PLUGIN    20
+
+//----------------------------------------------------------------------------------------------------------
+
+// Memory handler. Each new plug-in type replaces current behaviour
+typedef struct {
+
+        cmsPluginBase base;
+
+        // Required
+        void * (* MallocPtr)(cmsContext ContextID, cmsUInt32Number size);
+        void   (* FreePtr)(cmsContext ContextID, void *Ptr);
+        void * (* ReallocPtr)(cmsContext ContextID, void* Ptr, cmsUInt32Number NewSize);
+
+        // Optional
+        void * (* MallocZeroPtr)(cmsContext ContextID, cmsUInt32Number size);
+        void * (* CallocPtr)(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size);
+        void * (* DupPtr)(cmsContext ContextID, const void* Org, cmsUInt32Number size);
+
+} cmsPluginMemHandler;
+
+
+// ------------------------------------------------------------------------------------------------------------------
+
+// Interpolation. 16 bits and floating point versions.
+struct _cms_interp_struc;
+
+// Interpolation callbacks
+
+// 16 bits forward interpolation. This function performs precision-limited linear interpolation
+// and is supposed to be quite fast. Implementation may be tetrahedral or trilinear, and plug-ins may
+// choose to implement any other interpolation algorithm.
+typedef void (* _cmsInterpFn16)(register const cmsUInt16Number Input[],
+                                register cmsUInt16Number Output[],
+                                register const struct _cms_interp_struc* p);
+
+// Floating point forward interpolation. Full precision interpolation using floats. This is not a
+// time critical function. Implementation may be tetrahedral or trilinear, and plug-ins may
+// choose to implement any other interpolation algorithm.
+typedef void (* _cmsInterpFnFloat)(cmsFloat32Number const Input[],
+                                   cmsFloat32Number Output[],
+                                   const struct _cms_interp_struc* p);
+
+
+
+// This type holds a pointer to an interpolator that can be either 16 bits or float
+typedef union {
+    _cmsInterpFn16       Lerp16;            // Forward interpolation in 16 bits
+    _cmsInterpFnFloat    LerpFloat;         // Forward interpolation in floating point
+} cmsInterpFunction;
+
+// Flags for interpolator selection
+#define CMS_LERP_FLAGS_16BITS             0x0000        // The default
+#define CMS_LERP_FLAGS_FLOAT              0x0001        // Requires different implementation
+#define CMS_LERP_FLAGS_TRILINEAR          0x0100        // Hint only
+
+
+#define MAX_INPUT_DIMENSIONS 8
+
+typedef struct _cms_interp_struc {  // Used on all interpolations. Supplied by lcms2 when calling the interpolation function
+
+    cmsContext ContextID;     // The calling thread
+
+    cmsUInt32Number dwFlags;  // Keep original flags
+    cmsUInt32Number nInputs;  // != 1 only in 3D interpolation
+    cmsUInt32Number nOutputs; // != 1 only in 3D interpolation
+
+    cmsUInt32Number nSamples[MAX_INPUT_DIMENSIONS];  // Valid on all kinds of tables
+    cmsUInt32Number Domain[MAX_INPUT_DIMENSIONS];    // Domain = nSamples - 1
+
+    cmsUInt32Number opta[MAX_INPUT_DIMENSIONS];     // Optimization for 3D CLUT. This is the number of nodes premultiplied for each
+                                                    // dimension. For example, in 7 nodes, 7, 7^2 , 7^3, 7^4, etc. On non-regular
+                                                    // Samplings may vary according of the number of nodes for each dimension.
+
+    const void *Table;                // Points to the actual interpolation table
+    cmsInterpFunction Interpolation;  // Points to the function to do the interpolation
+
+ } cmsInterpParams;
+
+// Interpolators factory
+typedef cmsInterpFunction (* cmsInterpFnFactory)(cmsUInt32Number nInputChannels, cmsUInt32Number nOutputChannels, cmsUInt32Number dwFlags);
+
+// The plug-in
+typedef struct {
+    cmsPluginBase base;
+
+    // Points to a user-supplied function which implements the factory
+    cmsInterpFnFactory InterpolatorsFactory;
+
+} cmsPluginInterpolation;
+
+//----------------------------------------------------------------------------------------------------------
+
+// Parametric curves. A negative type means same function but analytically inverted. Max. number of params is 10
+
+// Evaluator callback for user-suplied parametric curves. May implement more than one type
+typedef  cmsFloat64Number (* cmsParametricCurveEvaluator)(cmsInt32Number Type, const cmsFloat64Number Params[10], cmsFloat64Number R);
+
+// Plug-in may implement an arbitrary number of parametric curves
+typedef struct {
+    cmsPluginBase base;
+
+    cmsUInt32Number nFunctions;                                     // Number of supported functions
+    cmsUInt32Number FunctionTypes[MAX_TYPES_IN_LCMS_PLUGIN];        // The identification types
+    cmsUInt32Number ParameterCount[MAX_TYPES_IN_LCMS_PLUGIN];       // Number of parameters for each function
+
+    cmsParametricCurveEvaluator    Evaluator;                       // The evaluator
+
+} cmsPluginParametricCurves;
+//----------------------------------------------------------------------------------------------------------
+
+// Formatters. This plug-in adds new handlers, replacing them if they already exist. Formatters dealing with
+// cmsFloat32Number (bps = 4) or double (bps = 0) types are requested via FormatterFloat callback. Others come across
+// Formatter16 callback
+
+struct _cmstransform_struct;
+
+typedef cmsUInt8Number* (* cmsFormatter16)(register struct _cmstransform_struct* CMMcargo,
+                                           register cmsUInt16Number Values[],
+                                           register cmsUInt8Number*  Buffer,
+                                           register cmsUInt32Number  Stride);
+
+typedef cmsUInt8Number* (* cmsFormatterFloat)(struct _cmstransform_struct* CMMcargo,
+                                              cmsFloat32Number Values[],
+                                              cmsUInt8Number*  Buffer,
+                                              cmsUInt32Number  Stride);
+
+// This type holds a pointer to a formatter that can be either 16 bits or cmsFloat32Number
+typedef union {
+    cmsFormatter16    Fmt16;
+    cmsFormatterFloat FmtFloat;
+
+} cmsFormatter;
+
+#define CMS_PACK_FLAGS_16BITS       0x0000
+#define CMS_PACK_FLAGS_FLOAT        0x0001
+
+typedef enum { cmsFormatterInput=0, cmsFormatterOutput=1 } cmsFormatterDirection;
+
+typedef cmsFormatter (* cmsFormatterFactory)(cmsUInt32Number Type,           // Specific type, i.e. TYPE_RGB_8
+                                             cmsFormatterDirection Dir,
+                                             cmsUInt32Number dwFlags);      // precision
+
+// Plug-in may implement an arbitrary number of formatters
+typedef struct {
+    cmsPluginBase          base;
+    cmsFormatterFactory    FormattersFactory;
+
+} cmsPluginFormatters;
+
+//----------------------------------------------------------------------------------------------------------
+
+// Tag type handler. Each type is free to return anything it wants, and it is up to the caller to
+// know in advance what is the type contained in the tag.
+typedef struct _cms_typehandler_struct {
+
+        cmsTagTypeSignature Signature;     // The signature of the type
+
+        // Allocates and reads items
+        void *   (* ReadPtr)(struct _cms_typehandler_struct* self,
+                             cmsIOHANDLER*      io,
+                             cmsUInt32Number*   nItems,
+                             cmsUInt32Number    SizeOfTag);
+
+        // Writes n Items
+        cmsBool  (* WritePtr)(struct _cms_typehandler_struct* self,
+                              cmsIOHANDLER*     io,
+                              void*             Ptr,
+                              cmsUInt32Number   nItems);
+
+        // Duplicate an item or array of items
+        void*   (* DupPtr)(struct _cms_typehandler_struct* self,
+                           const void *Ptr,
+                           cmsUInt32Number n);
+
+        // Free all resources
+        void    (* FreePtr)(struct _cms_typehandler_struct* self,
+                            void *Ptr);
+
+        // The calling thread
+        cmsContext     ContextID;
+
+} cmsTagTypeHandler;
+
+// Each plug-in implements a single type
+typedef struct {
+        cmsPluginBase      base;
+        cmsTagTypeHandler  Handler;
+
+} cmsPluginTagType;
+
+//----------------------------------------------------------------------------------------------------------
+
+// This is the tag plugin, which identifies tags. For writing, a pointer to function is provided.
+// This function should return the desired type for this tag, given the version of profile
+// and the data being serialized.
+typedef struct {
+
+    cmsUInt32Number     ElemCount;          // If this tag needs an array, how many elements should keep
+
+    // For reading.
+    cmsUInt32Number     nSupportedTypes;    // In how many types this tag can come (MAX_TYPES_IN_LCMS_PLUGIN maximum)
+    cmsTagTypeSignature SupportedTypes[MAX_TYPES_IN_LCMS_PLUGIN];
+
+    // For writting
+    cmsTagTypeSignature (* DecideType)(cmsFloat64Number ICCVersion, const void *Data);
+
+} cmsTagDescriptor;
+
+// Plug-in implements a single tag
+typedef struct {
+    cmsPluginBase    base;
+
+    cmsTagSignature  Signature;
+    cmsTagDescriptor Descriptor;
+
+} cmsPluginTag;
+
+//----------------------------------------------------------------------------------------------------------
+
+// Custom intents. This function should join all profiles specified in the array in
+// a single LUT. Any custom intent in the chain redirects to custom function. If more than
+// one custom intent is found, the one located first is invoked. Usually users should use only one
+// custom intent, so mixing custom intents in same multiprofile transform is not supported.
+
+typedef cmsPipeline* (* cmsIntentFn)( cmsContext       ContextID,
+                                      cmsUInt32Number  nProfiles,
+                                      cmsUInt32Number  Intents[],
+                                      cmsHPROFILE      hProfiles[],
+                                      cmsBool          BPC[],
+                                      cmsFloat64Number AdaptationStates[],
+                                      cmsUInt32Number  dwFlags);
+
+
+// Each plug-in defines a single intent number.
+typedef struct {
+    cmsPluginBase     base;
+    cmsUInt32Number   Intent;
+    cmsIntentFn       Link;
+    char              Description[256];
+
+} cmsPluginRenderingIntent;
+
+
+// The default ICC intents (perceptual, saturation, rel.col and abs.col)
+CMSAPI cmsPipeline*  CMSEXPORT _cmsDefaultICCintents(cmsContext       ContextID,
+                                                     cmsUInt32Number  nProfiles,
+                                                     cmsUInt32Number  Intents[],
+                                                     cmsHPROFILE      hProfiles[],
+                                                     cmsBool          BPC[],
+                                                     cmsFloat64Number AdaptationStates[],
+                                                     cmsUInt32Number  dwFlags);
+
+
+//----------------------------------------------------------------------------------------------------------
+
+// Pipelines, Multi Process Elements.
+
+typedef void (* _cmsStageEvalFn)     (const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage* mpe);
+typedef void*(* _cmsStageDupElemFn)  (cmsStage* mpe);
+typedef void (* _cmsStageFreeElemFn) (cmsStage* mpe);
+
+
+// This function allocates a generic MPE
+CMSAPI cmsStage* CMSEXPORT _cmsStageAllocPlaceholder(cmsContext ContextID,
+                                cmsStageSignature     Type,
+                                cmsUInt32Number       InputChannels,
+                                cmsUInt32Number       OutputChannels,
+                                _cmsStageEvalFn       EvalPtr,            // Points to fn that evaluates the element (always in floating point)
+                                _cmsStageDupElemFn    DupElemPtr,         // Points to a fn that duplicates the stage
+                                _cmsStageFreeElemFn   FreePtr,            // Points to a fn that sets the element free
+                                void*                 Data);              // A generic pointer to whatever memory needed by the element
+typedef struct {
+      cmsPluginBase     base;
+      cmsTagTypeHandler Handler;
+
+}  cmsPluginMultiProcessElement;
+
+//----------------------------------------------------------------------------------------------------------
+// Optimization. Using this plug-in, additional optimization strategies may be implemented.
+// The function should return TRUE if any optimization is done on the LUT, this terminates
+// the optimization  search. Or FALSE if it is unable to optimize and want to give a chance
+// to the rest of optimizers.
+
+typedef void     (* _cmsOPTeval16Fn)(register const cmsUInt16Number In[],
+                                     register cmsUInt16Number Out[],
+                                     register const void* Data);
+
+typedef void     (* _cmsOPTfreeDataFn)(cmsContext ContextID, void* Data);
+typedef void*    (* _cmsOPTdupDataFn)(cmsContext ContextID, const void* Data);
+
+
+typedef cmsBool  (* _cmsOPToptimizeFn)(cmsPipeline** Lut,
+                                       cmsUInt32Number  Intent,
+                                       cmsUInt32Number* InputFormat,
+                                       cmsUInt32Number* OutputFormat,
+                                       cmsUInt32Number* dwFlags);
+
+// This function may be used to set the optional evaluator and a block of private data. If private data is being used, an optional
+// duplicator and free functions should also be specified in order to duplicate the LUT construct. Use NULL to inhibit such functionality.
+
+CMSAPI void CMSEXPORT _cmsPipelineSetOptimizationParameters(cmsPipeline* Lut,
+                                               _cmsOPTeval16Fn Eval16,
+                                               void* PrivateData,
+                                               _cmsOPTfreeDataFn FreePrivateDataFn,
+                                               _cmsOPTdupDataFn DupPrivateDataFn);
+
+typedef struct {
+      cmsPluginBase     base;
+
+      // Optimize entry point
+      _cmsOPToptimizeFn  OptimizePtr;
+
+}  cmsPluginOptimization;
+
+//----------------------------------------------------------------------------------------------------------
+
+#ifndef CMS_USE_CPP_API
+#   ifdef __cplusplus
+    }
+#   endif
+#endif
+
+#define _lcms_plugin_H
+#endif
--- a/src/solaris/bin/java_md.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/bin/java_md.c	Fri Sep 24 16:41:32 2010 -0700
@@ -535,7 +535,7 @@
 GetApplicationHome(char *buf, jint bufsize)
 {
     if (execname != NULL) {
-        JLI_StrNCpy(buf, execname, bufsize-1);
+        JLI_Snprintf(buf, bufsize, "%s", execname);
         buf[bufsize-1] = '\0';
     } else {
         return JNI_FALSE;
--- a/src/solaris/classes/java/lang/UNIXProcess.java.linux	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/java/lang/UNIXProcess.java.linux	Fri Sep 24 16:41:32 2010 -0700
@@ -39,6 +39,7 @@
 import java.util.concurrent.Executor;
 import java.util.concurrent.ThreadFactory;
 import java.security.AccessController;
+import static java.security.AccessController.doPrivileged;
 import java.security.PrivilegedAction;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
@@ -94,14 +95,13 @@
         private final static ThreadGroup group = getRootThreadGroup();
 
         private static ThreadGroup getRootThreadGroup() {
-            return AccessController.doPrivileged
-            (new PrivilegedAction<ThreadGroup> () {
-            public ThreadGroup run() {
-                ThreadGroup root = Thread.currentThread().getThreadGroup();
-                while (root.getParent() != null)
-                    root = root.getParent();
-                return root;
-            }});
+            return doPrivileged(new PrivilegedAction<ThreadGroup> () {
+                public ThreadGroup run() {
+                    ThreadGroup root = Thread.currentThread().getThreadGroup();
+                    while (root.getParent() != null)
+                        root = root.getParent();
+                    return root;
+                }});
         }
 
         public Thread newThread(Runnable grimReaper) {
@@ -117,8 +117,12 @@
     /**
      * The thread pool of "process reaper" daemon threads.
      */
-    private static final Executor processReaperExecutor
-        = Executors.newCachedThreadPool(new ProcessReaperThreadFactory());
+    private static final Executor processReaperExecutor =
+        doPrivileged(new PrivilegedAction<Executor>() {
+            public Executor run() {
+                return Executors.newCachedThreadPool
+                    (new ProcessReaperThreadFactory());
+            }});
 
     UNIXProcess(final byte[] prog,
                 final byte[] argBlock, final int argc,
@@ -136,8 +140,7 @@
                           redirectErrorStream);
 
         try {
-            AccessController.doPrivileged
-            (new PrivilegedExceptionAction<Void>() {
+            doPrivileged(new PrivilegedExceptionAction<Void>() {
                 public Void run() throws IOException {
                     initStreams(fds);
                     return null;
--- a/src/solaris/classes/sun/net/NetHooks.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/net/NetHooks.java	Fri Sep 24 16:41:32 2010 -0700
@@ -73,28 +73,7 @@
      * be changed to use the ServiceLoader facility to allow the deployment of
      * other providers.
      */
-    private static Provider loadProvider(final String cn) {
-        return AccessController
-            .doPrivileged(new PrivilegedAction<Provider>() {
-                @Override public Provider run() {
-                    Class<Provider> c;
-                    try {
-                        c = (Class<Provider>)Class.forName(cn, true, null);
-                    } catch (ClassNotFoundException x) {
-                        return null;
-                    }
-                    try {
-                        return c.newInstance();
-                    } catch (IllegalAccessException x) {
-                        throw new AssertionError(x);
-                    } catch (InstantiationException x) {
-                        throw new AssertionError(x);
-                    }
-            }});
-    }
-    private static final Provider provider = AccessController
-        .doPrivileged(new GetPropertyAction("os.name")).equals("SunOS") ?
-            loadProvider("sun.net.spi.SdpProvider") : null;
+    private static final Provider provider = new sun.net.sdp.SdpProvider();
 
     /**
      * Invoke prior to binding a TCP socket.
@@ -104,8 +83,7 @@
                                      int port)
         throws IOException
     {
-        if (provider != null)
-            provider.implBeforeTcpBind(fdObj, address, port);
+        provider.implBeforeTcpBind(fdObj, address, port);
     }
 
     /**
@@ -116,7 +94,6 @@
                                         int port)
         throws IOException
     {
-        if (provider != null)
-            provider.implBeforeTcpConnect(fdObj, address, port);
+        provider.implBeforeTcpConnect(fdObj, address, port);
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/solaris/classes/sun/net/sdp/SdpProvider.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,335 @@
+/*
+ * Copyright (c) 2009, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.net.sdp;
+
+import sun.net.NetHooks;
+import java.net.InetAddress;
+import java.net.Inet4Address;
+import java.net.UnknownHostException;
+import java.util.*;
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.security.AccessController;
+
+import sun.net.sdp.SdpSupport;
+import sun.security.action.GetPropertyAction;
+
+/**
+ * A NetHooks provider that converts sockets from the TCP to SDP protocol prior
+ * to binding or connecting.
+ */
+
+public class SdpProvider extends NetHooks.Provider {
+    // maximum port
+    private static final int MAX_PORT = 65535;
+
+    // indicates if SDP is enabled and the rules for when the protocol is used
+    private final boolean enabled;
+    private final List<Rule> rules;
+
+    // logging for debug purposes
+    private PrintStream log;
+
+    public SdpProvider() {
+        // if this property is not defined then there is nothing to do.
+        String file = AccessController.doPrivileged(
+            new GetPropertyAction("com.sun.sdp.conf"));
+        if (file == null) {
+            this.enabled = false;
+            this.rules = null;
+            return;
+        }
+
+        // load configuration file
+        List<Rule> list = null;
+        if (file != null) {
+            try {
+                list = loadRulesFromFile(file);
+            } catch (IOException e) {
+                fail("Error reading %s: %s", file, e.getMessage());
+            }
+        }
+
+        // check if debugging is enabled
+        PrintStream out = null;
+        String logfile = AccessController.doPrivileged(
+            new GetPropertyAction("com.sun.sdp.debug"));
+        if (logfile != null) {
+            out = System.out;
+            if (logfile.length() > 0) {
+                try {
+                    out = new PrintStream(logfile);
+                } catch (IOException ignore) { }
+            }
+        }
+
+        this.enabled = !list.isEmpty();
+        this.rules = list;
+        this.log = out;
+    }
+
+    // supported actions
+    private static enum Action {
+        BIND,
+        CONNECT;
+    }
+
+    // a rule for matching a bind or connect request
+    private static interface Rule {
+        boolean match(Action action, InetAddress address, int port);
+    }
+
+    // rule to match port[-end]
+    private static class PortRangeRule implements Rule {
+        private final Action action;
+        private final int portStart;
+        private final int portEnd;
+        PortRangeRule(Action action, int portStart, int portEnd) {
+            this.action = action;
+            this.portStart = portStart;
+            this.portEnd = portEnd;
+        }
+        Action action() {
+            return action;
+        }
+        @Override
+        public boolean match(Action action, InetAddress address, int port) {
+            return (action == this.action &&
+                    port >= this.portStart &&
+                    port <= this.portEnd);
+        }
+    }
+
+    // rule to match address[/prefix] port[-end]
+    private static class AddressPortRangeRule extends PortRangeRule {
+        private final byte[] addressAsBytes;
+        private final int prefixByteCount;
+        private final byte mask;
+        AddressPortRangeRule(Action action, InetAddress address,
+                             int prefix, int port, int end)
+        {
+            super(action, port, end);
+            this.addressAsBytes = address.getAddress();
+            this.prefixByteCount = prefix >> 3;
+            this.mask = (byte)(0xff << (8 - (prefix % 8)));
+        }
+        @Override
+        public boolean match(Action action, InetAddress address, int port) {
+            if (action != action())
+                return false;
+            byte[] candidate = address.getAddress();
+            // same address type?
+            if (candidate.length != addressAsBytes.length)
+                return false;
+            // check bytes
+            for (int i=0; i<prefixByteCount; i++) {
+                if (candidate[i] != addressAsBytes[i])
+                    return false;
+            }
+            // check remaining bits
+            if ((prefixByteCount < addressAsBytes.length) &&
+                ((candidate[prefixByteCount] & mask) !=
+                 (addressAsBytes[prefixByteCount] & mask)))
+                    return false;
+            return super.match(action, address, port);
+        }
+    }
+
+    // parses port:[-end]
+    private static int[] parsePortRange(String s) {
+        int pos = s.indexOf('-');
+        try {
+            int[] result = new int[2];
+            if (pos < 0) {
+                boolean all = s.equals("*");
+                result[0] = all ? 0 : Integer.parseInt(s);
+                result[1] = all ? MAX_PORT : result[0];
+            } else {
+                String low = s.substring(0, pos);
+                if (low.length() == 0) low = "*";
+                String high = s.substring(pos+1);
+                if (high.length() == 0) high = "*";
+                result[0] = low.equals("*") ? 0 : Integer.parseInt(low);
+                result[1] = high.equals("*") ? MAX_PORT : Integer.parseInt(high);
+            }
+            return result;
+        } catch (NumberFormatException e) {
+            return new int[0];
+        }
+    }
+
+    private static void fail(String msg, Object... args) {
+        Formatter f = new Formatter();
+        f.format(msg, args);
+        throw new RuntimeException(f.out().toString());
+    }
+
+    // loads rules from the given file
+    // Each non-blank/non-comment line must have the format:
+    // ("bind" | "connect") 1*LWSP-char (hostname | ipaddress["/" prefix])
+    //     1*LWSP-char ("*" | port) [ "-" ("*" | port) ]
+    private static List<Rule> loadRulesFromFile(String file)
+        throws IOException
+    {
+        Scanner scanner = new Scanner(new File(file));
+        try {
+            List<Rule> result = new ArrayList<Rule>();
+            while (scanner.hasNextLine()) {
+                String line = scanner.nextLine().trim();
+
+                // skip blank lines and comments
+                if (line.length() == 0 || line.charAt(0) == '#')
+                    continue;
+
+                // must have 3 fields
+                String[] s = line.split("\\s+");
+                if (s.length != 3) {
+                    fail("Malformed line '%s'", line);
+                    continue;
+                }
+
+                // first field is the action ("bind" or "connect")
+                Action action = null;
+                for (Action a: Action.values()) {
+                    if (s[0].equalsIgnoreCase(a.name())) {
+                        action = a;
+                        break;
+                    }
+                }
+                if (action == null) {
+                    fail("Action '%s' not recognized", s[0]);
+                    continue;
+                }
+
+                // * port[-end]
+                int[] ports = parsePortRange(s[2]);
+                if (ports.length == 0) {
+                    fail("Malformed port range '%s'", s[2]);
+                    continue;
+                }
+
+                // match all addresses
+                if (s[1].equals("*")) {
+                    result.add(new PortRangeRule(action, ports[0], ports[1]));
+                    continue;
+                }
+
+                // hostname | ipaddress[/prefix]
+                int pos = s[1].indexOf('/');
+                try {
+                    if (pos < 0) {
+                        // hostname or ipaddress (no prefix)
+                        InetAddress[] addresses = InetAddress.getAllByName(s[1]);
+                        for (InetAddress address: addresses) {
+                            int prefix =
+                                (address instanceof Inet4Address) ? 32 : 128;
+                            result.add(new AddressPortRangeRule(action, address,
+                                prefix, ports[0], ports[1]));
+                        }
+                    } else {
+                        // ipaddress/prefix
+                        InetAddress address = InetAddress
+                            .getByName(s[1].substring(0, pos));
+                        int prefix = -1;
+                        try {
+                            prefix = Integer.parseInt(s[1].substring(pos+1));
+                            if (address instanceof Inet4Address) {
+                                // must be 1-31
+                                if (prefix < 0 || prefix > 32) prefix = -1;
+                            } else {
+                                // must be 1-128
+                                if (prefix < 0 || prefix > 128) prefix = -1;
+                            }
+                        } catch (NumberFormatException e) {
+                        }
+
+                        if (prefix > 0) {
+                            result.add(new AddressPortRangeRule(action,
+                                        address, prefix, ports[0], ports[1]));
+                        } else {
+                            fail("Malformed prefix '%s'", s[1]);
+                            continue;
+                        }
+                    }
+                } catch (UnknownHostException uhe) {
+                    fail("Unknown host or malformed IP address '%s'", s[1]);
+                    continue;
+                }
+            }
+            return result;
+        } finally {
+            scanner.close();
+        }
+    }
+
+    // converts unbound TCP socket to a SDP socket if it matches the rules
+    private void convertTcpToSdpIfMatch(FileDescriptor fdObj,
+                                               Action action,
+                                               InetAddress address,
+                                               int port)
+        throws IOException
+    {
+        boolean matched = false;
+        for (Rule rule: rules) {
+            if (rule.match(action, address, port)) {
+                SdpSupport.convertSocket(fdObj);
+                matched = true;
+                break;
+            }
+        }
+        if (log != null) {
+            String addr = (address instanceof Inet4Address) ?
+                address.getHostAddress() : "[" + address.getHostAddress() + "]";
+            if (matched) {
+                log.format("%s to %s:%d (socket converted to SDP protocol)\n", action, addr, port);
+            } else {
+                log.format("%s to %s:%d (no match)\n", action, addr, port);
+            }
+        }
+    }
+
+    @Override
+    public void implBeforeTcpBind(FileDescriptor fdObj,
+                              InetAddress address,
+                              int port)
+        throws IOException
+    {
+        if (enabled)
+            convertTcpToSdpIfMatch(fdObj, Action.BIND, address, port);
+    }
+
+    @Override
+    public void implBeforeTcpConnect(FileDescriptor fdObj,
+                                InetAddress address,
+                                int port)
+        throws IOException
+    {
+        if (enabled)
+            convertTcpToSdpIfMatch(fdObj, Action.CONNECT, address, port);
+    }
+}
--- a/src/solaris/classes/sun/net/spi/SdpProvider.java	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,339 +0,0 @@
-/*
- * Copyright (c) 2009, Oracle and/or its affiliates. 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.net.spi;
-
-import sun.net.NetHooks;
-import java.net.InetAddress;
-import java.net.Inet4Address;
-import java.net.UnknownHostException;
-import java.util.*;
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.PrintStream;
-
-import sun.misc.SharedSecrets;
-import sun.misc.JavaIOFileDescriptorAccess;
-
-/**
- * A NetHooks provider that converts sockets from the TCP to SDP protocol prior
- * to binding or connecting.
- */
-
-public class SdpProvider extends NetHooks.Provider {
-    private static final JavaIOFileDescriptorAccess fdAccess =
-        SharedSecrets.getJavaIOFileDescriptorAccess();
-
-    // maximum port
-    private static final int MAX_PORT = 65535;
-
-    // indicates if SDP is enabled and the rules for when the protocol is used
-    private final boolean enabled;
-    private final List<Rule> rules;
-
-    // logging for debug purposes
-    private PrintStream log;
-
-    public SdpProvider() {
-        // if this property is not defined then there is nothing to do.
-        String file = System.getProperty("com.sun.sdp.conf");
-        if (file == null) {
-            this.enabled = false;
-            this.rules = null;
-            return;
-        }
-
-        // load configuration file
-        List<Rule> list = null;
-        if (file != null) {
-            try {
-                list = loadRulesFromFile(file);
-            } catch (IOException e) {
-                fail("Error reading %s: %s", file, e.getMessage());
-            }
-        }
-
-        // check if debugging is enabled
-        PrintStream out = null;
-        String logfile = System.getProperty("com.sun.sdp.debug");
-        if (logfile != null) {
-            out = System.out;
-            if (logfile.length() > 0) {
-                try {
-                    out = new PrintStream(logfile);
-                } catch (IOException ignore) { }
-            }
-        }
-
-        this.enabled = !list.isEmpty();
-        this.rules = list;
-        this.log = out;
-    }
-
-    // supported actions
-    private static enum Action {
-        BIND,
-        CONNECT;
-    }
-
-    // a rule for matching a bind or connect request
-    private static interface Rule {
-        boolean match(Action action, InetAddress address, int port);
-    }
-
-    // rule to match port[-end]
-    private static class PortRangeRule implements Rule {
-        private final Action action;
-        private final int portStart;
-        private final int portEnd;
-        PortRangeRule(Action action, int portStart, int portEnd) {
-            this.action = action;
-            this.portStart = portStart;
-            this.portEnd = portEnd;
-        }
-        Action action() {
-            return action;
-        }
-        @Override
-        public boolean match(Action action, InetAddress address, int port) {
-            return (action == this.action &&
-                    port >= this.portStart &&
-                    port <= this.portEnd);
-        }
-    }
-
-    // rule to match address[/prefix] port[-end]
-    private static class AddressPortRangeRule extends PortRangeRule {
-        private final byte[] addressAsBytes;
-        private final int prefixByteCount;
-        private final byte mask;
-        AddressPortRangeRule(Action action, InetAddress address,
-                             int prefix, int port, int end)
-        {
-            super(action, port, end);
-            this.addressAsBytes = address.getAddress();
-            this.prefixByteCount = prefix >> 3;
-            this.mask = (byte)(0xff << (8 - (prefix % 8)));
-        }
-        @Override
-        public boolean match(Action action, InetAddress address, int port) {
-            if (action != action())
-                return false;
-            byte[] candidate = address.getAddress();
-            // same address type?
-            if (candidate.length != addressAsBytes.length)
-                return false;
-            // check bytes
-            for (int i=0; i<prefixByteCount; i++) {
-                if (candidate[i] != addressAsBytes[i])
-                    return false;
-            }
-            // check remaining bits
-            if ((prefixByteCount < addressAsBytes.length) &&
-                ((candidate[prefixByteCount] & mask) !=
-                 (addressAsBytes[prefixByteCount] & mask)))
-                    return false;
-            return super.match(action, address, port);
-        }
-    }
-
-    // parses port:[-end]
-    private static int[] parsePortRange(String s) {
-        int pos = s.indexOf('-');
-        try {
-            int[] result = new int[2];
-            if (pos < 0) {
-                boolean all = s.equals("*");
-                result[0] = all ? 0 : Integer.parseInt(s);
-                result[1] = all ? MAX_PORT : result[0];
-            } else {
-                String low = s.substring(0, pos);
-                if (low.length() == 0) low = "*";
-                String high = s.substring(pos+1);
-                if (high.length() == 0) high = "*";
-                result[0] = low.equals("*") ? 0 : Integer.parseInt(low);
-                result[1] = high.equals("*") ? MAX_PORT : Integer.parseInt(high);
-            }
-            return result;
-        } catch (NumberFormatException e) {
-            return new int[0];
-        }
-    }
-
-    private static void fail(String msg, Object... args) {
-        Formatter f = new Formatter();
-        f.format(msg, args);
-        throw new RuntimeException(f.out().toString());
-    }
-
-    // loads rules from the given file
-    // Each non-blank/non-comment line must have the format:
-    // ("bind" | "connect") 1*LWSP-char (hostname | ipaddress["/" prefix])
-    //     1*LWSP-char ("*" | port) [ "-" ("*" | port) ]
-    private static List<Rule> loadRulesFromFile(String file)
-        throws IOException
-    {
-        Scanner scanner = new Scanner(new File(file));
-        try {
-            List<Rule> result = new ArrayList<Rule>();
-            while (scanner.hasNextLine()) {
-                String line = scanner.nextLine().trim();
-
-                // skip blank lines and comments
-                if (line.length() == 0 || line.charAt(0) == '#')
-                    continue;
-
-                // must have 3 fields
-                String[] s = line.split("\\s+");
-                if (s.length != 3) {
-                    fail("Malformed line '%s'", line);
-                    continue;
-                }
-
-                // first field is the action ("bind" or "connect")
-                Action action = null;
-                for (Action a: Action.values()) {
-                    if (s[0].equalsIgnoreCase(a.name())) {
-                        action = a;
-                        break;
-                    }
-                }
-                if (action == null) {
-                    fail("Action '%s' not recognized", s[0]);
-                    continue;
-                }
-
-                // * port[-end]
-                int[] ports = parsePortRange(s[2]);
-                if (ports.length == 0) {
-                    fail("Malformed port range '%s'", s[2]);
-                    continue;
-                }
-
-                // match all addresses
-                if (s[1].equals("*")) {
-                    result.add(new PortRangeRule(action, ports[0], ports[1]));
-                    continue;
-                }
-
-                // hostname | ipaddress[/prefix]
-                int pos = s[1].indexOf('/');
-                try {
-                    if (pos < 0) {
-                        // hostname or ipaddress (no prefix)
-                        InetAddress[] addresses = InetAddress.getAllByName(s[1]);
-                        for (InetAddress address: addresses) {
-                            int prefix =
-                                (address instanceof Inet4Address) ? 32 : 128;
-                            result.add(new AddressPortRangeRule(action, address,
-                                prefix, ports[0], ports[1]));
-                        }
-                    } else {
-                        // ipaddress/prefix
-                        InetAddress address = InetAddress
-                            .getByName(s[1].substring(0, pos));
-                        int prefix = -1;
-                        try {
-                            prefix = Integer.parseInt(s[1].substring(pos+1));
-                            if (address instanceof Inet4Address) {
-                                // must be 1-31
-                                if (prefix < 0 || prefix > 32) prefix = -1;
-                            } else {
-                                // must be 1-128
-                                if (prefix < 0 || prefix > 128) prefix = -1;
-                            }
-                        } catch (NumberFormatException e) {
-                        }
-
-                        if (prefix > 0) {
-                            result.add(new AddressPortRangeRule(action,
-                                        address, prefix, ports[0], ports[1]));
-                        } else {
-                            fail("Malformed prefix '%s'", s[1]);
-                            continue;
-                        }
-                    }
-                } catch (UnknownHostException uhe) {
-                    fail("Unknown host or malformed IP address '%s'", s[1]);
-                    continue;
-                }
-            }
-            return result;
-        } finally {
-            scanner.close();
-        }
-    }
-
-    // converts unbound TCP socket to a SDP socket if it matches the rules
-    private void convertTcpToSdpIfMatch(FileDescriptor fdObj,
-                                               Action action,
-                                               InetAddress address,
-                                               int port)
-        throws IOException
-    {
-        boolean matched = false;
-        for (Rule rule: rules) {
-            if (rule.match(action, address, port)) {
-                int fd = fdAccess.get(fdObj);
-                convert(fd);
-                matched = true;
-                break;
-            }
-        }
-        if (log != null) {
-            String addr = (address instanceof Inet4Address) ?
-                address.getHostAddress() : "[" + address.getHostAddress() + "]";
-            if (matched) {
-                log.format("%s to %s:%d (socket converted to SDP protocol)\n", action, addr, port);
-            } else {
-                log.format("%s to %s:%d (no match)\n", action, addr, port);
-            }
-        }
-    }
-
-    @Override
-    public void implBeforeTcpBind(FileDescriptor fdObj,
-                              InetAddress address,
-                              int port)
-        throws IOException
-    {
-        if (enabled)
-            convertTcpToSdpIfMatch(fdObj, Action.BIND, address, port);
-    }
-
-    @Override
-    public void implBeforeTcpConnect(FileDescriptor fdObj,
-                                InetAddress address,
-                                int port)
-        throws IOException
-    {
-        if (enabled)
-            convertTcpToSdpIfMatch(fdObj, Action.CONNECT, address, port);
-    }
-
-    // -- native methods --
-    private static native void convert(int fd) throws IOException;
-}
--- a/src/solaris/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -25,20 +25,14 @@
 
 package sun.net.www.protocol.http.ntlm;
 
+import com.sun.security.ntlm.Client;
+import com.sun.security.ntlm.NTLMException;
 import java.io.IOException;
-import java.io.UnsupportedEncodingException;
 import java.net.InetAddress;
 import java.net.PasswordAuthentication;
 import java.net.UnknownHostException;
 import java.net.URL;
 import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import javax.crypto.Cipher;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.DESKeySpec;
 
 import sun.net.www.HeaderParser;
 import sun.net.www.protocol.http.AuthenticationInfo;
@@ -72,14 +66,8 @@
  */
 
 public class NTLMAuthentication extends AuthenticationInfo {
-    private static final long serialVersionUID = -2403849171106437142L;
+    private static final long serialVersionUID = 170L;
 
-    private byte[] type1;
-    private byte[] type3;
-
-    private SecretKeyFactory fac;
-    private Cipher cipher;
-    private MessageDigest md4;
     private String hostname;
     private static String defaultDomain; /* Domain to use if not specified by user */
 
@@ -94,53 +82,28 @@
     }
 
     private void init0() {
-        type1 = new byte[256];
-        type3 = new byte[256];
-        System.arraycopy (new byte[] {'N','T','L','M','S','S','P',0,1}, 0, type1, 0, 9);
-        type1[12] = (byte) 3;
-        type1[13] = (byte) 0xb2;
-        type1[28] = (byte) 0x20;
-        System.arraycopy (new byte[] {'N','T','L','M','S','S','P',0,3}, 0, type3, 0, 9);
-        type3[12] = (byte) 0x18;
-        type3[14] = (byte) 0x18;
-        type3[20] = (byte) 0x18;
-        type3[22] = (byte) 0x18;
-        type3[32] = (byte) 0x40;
-        type3[60] = (byte) 1;
-        type3[61] = (byte) 0x82;
 
-        try {
-            hostname = java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction<String>() {
-                public String run() {
-                    String localhost;
-                    try {
-                        localhost = InetAddress.getLocalHost().getHostName().toUpperCase();
-                    } catch (UnknownHostException e) {
-                         localhost = "localhost";
-                    }
-                    return localhost;
+        hostname = java.security.AccessController.doPrivileged(
+            new java.security.PrivilegedAction<String>() {
+            public String run() {
+                String localhost;
+                try {
+                    localhost = InetAddress.getLocalHost().getHostName().toUpperCase();
+                } catch (UnknownHostException e) {
+                     localhost = "localhost";
                 }
-            });
-            int x = hostname.indexOf ('.');
-            if (x != -1) {
-                hostname = hostname.substring (0, x);
+                return localhost;
             }
-            fac = SecretKeyFactory.getInstance ("DES");
-            cipher = Cipher.getInstance ("DES/ECB/NoPadding");
-            md4 = sun.security.provider.MD4.getInstance();
-        } catch (NoSuchPaddingException e) {
-            assert false;
-        } catch (NoSuchAlgorithmException e) {
-            assert false;
+        });
+        int x = hostname.indexOf ('.');
+        if (x != -1) {
+            hostname = hostname.substring (0, x);
         }
     };
 
     PasswordAuthentication pw;
-    String username;
-    String ntdomain;
-    String password;
 
+    Client client;
     /**
      * Create a NTLMAuthentication:
      * Username may be specified as domain<BACKSLASH>username in the application Authenticator.
@@ -156,6 +119,9 @@
     }
 
     private void init (PasswordAuthentication pw) {
+        String username;
+        String ntdomain;
+        char[] password;
         this.pw = pw;
         String s = pw.getUserName();
         int i = s.indexOf ('\\');
@@ -166,8 +132,19 @@
             ntdomain = s.substring (0, i).toUpperCase();
             username = s.substring (i+1);
         }
-        password = new String (pw.getPassword());
+        password = pw.getPassword();
         init0();
+        try {
+            client = new Client(System.getProperty("ntlm.version"), hostname,
+                    username, ntdomain, password);
+        } catch (NTLMException ne) {
+            try {
+                client = new Client(null, hostname, username, ntdomain, password);
+            } catch (NTLMException ne2) {
+                // Will never happen
+                throw new AssertionError("Really?");
+            }
+        }
     }
 
    /**
@@ -240,181 +217,26 @@
         }
     }
 
-    private void copybytes (byte[] dest, int destpos, String src, String enc) {
-        try {
-            byte[] x = src.getBytes(enc);
-            System.arraycopy (x, 0, dest, destpos, x.length);
-        } catch (UnsupportedEncodingException e) {
-            assert false;
-        }
-    }
-
     private String buildType1Msg () {
-        int dlen = ntdomain.length();
-        type1[16]= (byte) (dlen % 256);
-        type1[17]= (byte) (dlen / 256);
-        type1[18] = type1[16];
-        type1[19] = type1[17];
-
-        int hlen = hostname.length();
-        type1[24]= (byte) (hlen % 256);
-        type1[25]= (byte) (hlen / 256);
-        type1[26] = type1[24];
-        type1[27] = type1[25];
-
-        copybytes (type1, 32, hostname, "ISO8859_1");
-        copybytes (type1, hlen+32, ntdomain, "ISO8859_1");
-        type1[20] = (byte) ((hlen+32) % 256);
-        type1[21] = (byte) ((hlen+32) / 256);
-
-        byte[] msg = new byte [32 + hlen + dlen];
-        System.arraycopy (type1, 0, msg, 0, 32 + hlen + dlen);
+        byte[] msg = client.type1();
         String result = "NTLM " + (new B64Encoder()).encode (msg);
         return result;
     }
 
-
-    /* Convert a 7 byte array to an 8 byte array (for a des key with parity)
-     * input starts at offset off
-     */
-    private byte[] makeDesKey (byte[] input, int off) {
-        int[] in = new int [input.length];
-        for (int i=0; i<in.length; i++ ) {
-            in[i] = input[i]<0 ? input[i]+256: input[i];
-        }
-        byte[] out = new byte[8];
-        out[0] = (byte)in[off+0];
-        out[1] = (byte)(((in[off+0] << 7) & 0xFF) | (in[off+1] >> 1));
-        out[2] = (byte)(((in[off+1] << 6) & 0xFF) | (in[off+2] >> 2));
-        out[3] = (byte)(((in[off+2] << 5) & 0xFF) | (in[off+3] >> 3));
-        out[4] = (byte)(((in[off+3] << 4) & 0xFF) | (in[off+4] >> 4));
-        out[5] = (byte)(((in[off+4] << 3) & 0xFF) | (in[off+5] >> 5));
-        out[6] = (byte)(((in[off+5] << 2) & 0xFF) | (in[off+6] >> 6));
-        out[7] = (byte)((in[off+6] << 1) & 0xFF);
-        return out;
-    }
-
-    private byte[] calcLMHash () throws GeneralSecurityException {
-        byte[] magic = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25};
-        byte[] pwb = password.toUpperCase ().getBytes();
-        byte[] pwb1 = new byte [14];
-        int len = password.length();
-        if (len > 14)
-            len = 14;
-        System.arraycopy (pwb, 0, pwb1, 0, len); /* Zero padded */
-
-        DESKeySpec dks1 = new DESKeySpec (makeDesKey (pwb1, 0));
-        DESKeySpec dks2 = new DESKeySpec (makeDesKey (pwb1, 7));
-
-        SecretKey key1 = fac.generateSecret (dks1);
-        SecretKey key2 = fac.generateSecret (dks2);
-        cipher.init (Cipher.ENCRYPT_MODE, key1);
-        byte[] out1 = cipher.doFinal (magic, 0, 8);
-        cipher.init (Cipher.ENCRYPT_MODE, key2);
-        byte[] out2 = cipher.doFinal (magic, 0, 8);
-
-        byte[] result = new byte [21];
-        System.arraycopy (out1, 0, result, 0, 8);
-        System.arraycopy (out2, 0, result, 8, 8);
-        return result;
-    }
-
-    private byte[] calcNTHash () throws GeneralSecurityException {
-        byte[] pw = null;
-        try {
-            pw = password.getBytes ("UnicodeLittleUnmarked");
-        } catch (UnsupportedEncodingException e) {
-            assert false;
-        }
-        byte[] out = md4.digest (pw);
-        byte[] result = new byte [21];
-        System.arraycopy (out, 0, result, 0, 16);
-        return result;
-    }
-
-    /* key is a 21 byte array. Split it into 3 7 byte chunks,
-     * Convert each to 8 byte DES keys, encrypt the text arg with
-     * each key and return the three results in a sequential []
-     */
-    private byte[] calcResponse (byte[] key, byte[] text)
-    throws GeneralSecurityException {
-        assert key.length == 21;
-        DESKeySpec dks1 = new DESKeySpec (makeDesKey (key, 0));
-        DESKeySpec dks2 = new DESKeySpec (makeDesKey (key, 7));
-        DESKeySpec dks3 = new DESKeySpec (makeDesKey (key, 14));
-        SecretKey key1 = fac.generateSecret (dks1);
-        SecretKey key2 = fac.generateSecret (dks2);
-        SecretKey key3 = fac.generateSecret (dks3);
-        cipher.init (Cipher.ENCRYPT_MODE, key1);
-        byte[] out1 = cipher.doFinal (text, 0, 8);
-        cipher.init (Cipher.ENCRYPT_MODE, key2);
-        byte[] out2 = cipher.doFinal (text, 0, 8);
-        cipher.init (Cipher.ENCRYPT_MODE, key3);
-        byte[] out3 = cipher.doFinal (text, 0, 8);
-        byte[] result = new byte [24];
-        System.arraycopy (out1, 0, result, 0, 8);
-        System.arraycopy (out2, 0, result, 8, 8);
-        System.arraycopy (out3, 0, result, 16, 8);
-        return result;
-    }
-
     private String buildType3Msg (String challenge) throws GeneralSecurityException,
                                                            IOException  {
         /* First decode the type2 message to get the server nonce */
         /* nonce is located at type2[24] for 8 bytes */
 
         byte[] type2 = (new sun.misc.BASE64Decoder()).decodeBuffer (challenge);
-        byte[] nonce = new byte [8];
-        System.arraycopy (type2, 24, nonce, 0, 8);
-
-        int ulen = username.length()*2;
-        type3[36] = type3[38] = (byte) (ulen % 256);
-        type3[37] = type3[39] = (byte) (ulen / 256);
-        int dlen = ntdomain.length()*2;
-        type3[28] = type3[30] = (byte) (dlen % 256);
-        type3[29] = type3[31] = (byte) (dlen / 256);
-        int hlen = hostname.length()*2;
-        type3[44] = type3[46] = (byte) (hlen % 256);
-        type3[45] = type3[47] = (byte) (hlen / 256);
-
-        int l = 64;
-        copybytes (type3, l, ntdomain, "UnicodeLittleUnmarked");
-        type3[32] = (byte) (l % 256);
-        type3[33] = (byte) (l / 256);
-        l += dlen;
-        copybytes (type3, l, username, "UnicodeLittleUnmarked");
-        type3[40] = (byte) (l % 256);
-        type3[41] = (byte) (l / 256);
-        l += ulen;
-        copybytes (type3, l, hostname, "UnicodeLittleUnmarked");
-        type3[48] = (byte) (l % 256);
-        type3[49] = (byte) (l / 256);
-        l += hlen;
-
-        byte[] lmhash = calcLMHash();
-        byte[] lmresponse = calcResponse (lmhash, nonce);
-        byte[] nthash = calcNTHash();
-        byte[] ntresponse = calcResponse (nthash, nonce);
-        System.arraycopy (lmresponse, 0, type3, l, 24);
-        type3[16] = (byte) (l % 256);
-        type3[17] = (byte) (l / 256);
-        l += 24;
-        System.arraycopy (ntresponse, 0, type3, l, 24);
-        type3[24] = (byte) (l % 256);
-        type3[25] = (byte) (l / 256);
-        l += 24;
-        type3[56] = (byte) (l % 256);
-        type3[57] = (byte) (l / 256);
-
-        byte[] msg = new byte [l];
-        System.arraycopy (type3, 0, msg, 0, l);
+        byte[] nonce = new byte[8];
+        new java.util.Random().nextBytes(nonce);
+        byte[] msg = client.type3(type2, nonce);
         String result = "NTLM " + (new B64Encoder()).encode (msg);
         return result;
     }
-
 }
 
-
 class B64Encoder extends sun.misc.BASE64Encoder {
     /* to force it to to the entire encoding in one line */
     protected int bytesPerLine () {
--- a/src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -65,10 +65,9 @@
      */
     DevPollSelectorImpl(SelectorProvider sp) {
         super(sp);
-        int[] fdes = new int[2];
-        IOUtil.initPipe(fdes, false);
-        fd0 = fdes[0];
-        fd1 = fdes[1];
+        long pipeFds = IOUtil.makePipe(false);
+        fd0 = (int) (pipeFds >>> 32);
+        fd1 = (int) pipeFds;
         pollWrapper = new DevPollArrayWrapper();
         pollWrapper.initInterrupt(fd0, fd1);
         fdToKey = new HashMap<Integer,SelectionKeyImpl>();
@@ -147,7 +146,7 @@
         selectedKeys = null;
 
         // Deregister channels
-        Iterator i = keys.iterator();
+        Iterator<SelectionKey> i = keys.iterator();
         while (i.hasNext()) {
             SelectionKeyImpl ski = (SelectionKeyImpl)i.next();
             deregister(ski);
--- a/src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -62,10 +62,9 @@
      */
     EPollSelectorImpl(SelectorProvider sp) {
         super(sp);
-        int[] fdes = new int[2];
-        IOUtil.initPipe(fdes, false);
-        fd0 = fdes[0];
-        fd1 = fdes[1];
+        long pipeFds = IOUtil.makePipe(false);
+        fd0 = (int) (pipeFds >>> 32);
+        fd1 = (int) pipeFds;
         pollWrapper = new EPollArrayWrapper();
         pollWrapper.initInterrupt(fd0, fd1);
         fdToKey = new HashMap<Integer,SelectionKeyImpl>();
@@ -144,7 +143,7 @@
         selectedKeys = null;
 
         // Deregister channels
-        Iterator i = keys.iterator();
+        Iterator<SelectionKey> i = keys.iterator();
         while (i.hasNext()) {
             SelectionKeyImpl ski = (SelectionKeyImpl)i.next();
             deregister(ski);
--- a/src/solaris/classes/sun/nio/ch/InheritedChannel.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/nio/ch/InheritedChannel.java	Fri Sep 24 16:41:32 2010 -0700
@@ -96,7 +96,7 @@
                                          FileDescriptor fd)
             throws IOException
         {
-            super(sp, fd);
+            super(sp, fd, true);
         }
 
         protected void implCloseSelectableChannel() throws IOException {
--- a/src/solaris/classes/sun/nio/ch/PipeImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/nio/ch/PipeImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -39,13 +39,14 @@
     private final SinkChannel sink;
 
     PipeImpl(SelectorProvider sp) {
-        int[] fdes = new int[2];
-        IOUtil.initPipe(fdes, true);
+        long pipeFds = IOUtil.makePipe(true);
+        int readFd = (int) (pipeFds >>> 32);
+        int writeFd = (int) pipeFds;
         FileDescriptor sourcefd = new FileDescriptor();
-        IOUtil.setfdVal(sourcefd, fdes[0]);
+        IOUtil.setfdVal(sourcefd, readFd);
         source = new SourceChannelImpl(sp, sourcefd);
         FileDescriptor sinkfd = new FileDescriptor();
-        IOUtil.setfdVal(sinkfd, fdes[1]);
+        IOUtil.setfdVal(sinkfd, writeFd);
         sink = new SinkChannelImpl(sp, sinkfd);
     }
 
--- a/src/solaris/classes/sun/nio/ch/PollSelectorImpl.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/nio/ch/PollSelectorImpl.java	Fri Sep 24 16:41:32 2010 -0700
@@ -54,10 +54,9 @@
      */
     PollSelectorImpl(SelectorProvider sp) {
         super(sp, 1, 1);
-        int[] fdes = new int[2];
-        IOUtil.initPipe(fdes, false);
-        fd0 = fdes[0];
-        fd1 = fdes[1];
+        long pipeFds = IOUtil.makePipe(false);
+        fd0 = (int) (pipeFds >>> 32);
+        fd1 = (int) pipeFds;
         pollWrapper = new PollArrayWrapper(INIT_CAP);
         pollWrapper.initInterrupt(fd0, fd1);
         channelArray = new SelectionKeyImpl[INIT_CAP];
--- a/src/solaris/classes/sun/nio/fs/UnixDirectoryStream.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/nio/fs/UnixDirectoryStream.java	Fri Sep 24 16:41:32 2010 -0700
@@ -27,7 +27,6 @@
 
 import java.nio.file.*;
 import java.util.Iterator;
-import java.util.ConcurrentModificationException;
 import java.util.NoSuchElementException;
 import java.util.concurrent.locks.*;
 import java.io.IOException;
@@ -139,9 +138,6 @@
         // next entry to return
         private Path nextEntry;
 
-        // previous entry returned by next method (needed by remove method)
-        private Path prevEntry;
-
         UnixDirectoryIterator(DirectoryStream<Path> stream) {
             atEof = false;
             this.stream = stream;
@@ -168,24 +164,19 @@
                 // prevent close while reading
                 readLock().lock();
                 try {
-                    if (isClosed)
-                        throwAsConcurrentModificationException(new
-                            ClosedDirectoryStreamException());
-                    try {
+                    if (isOpen()) {
                         nameAsBytes = readdir(dp);
-                    } catch (UnixException x) {
-                        try {
-                            x.rethrowAsIOException(dir);
-                        } catch (IOException ioe) {
-                            throwAsConcurrentModificationException(ioe);
-                        }
                     }
+                } catch (UnixException x) {
+                    IOException ioe = x.asIOException(dir);
+                    throw new DirectoryIteratorException(ioe);
                 } finally {
                     readLock().unlock();
                 }
 
                 // EOF
                 if (nameAsBytes == null) {
+                    atEof = true;
                     return null;
                 }
 
@@ -198,7 +189,7 @@
                         if (filter == null || filter.accept(entry))
                             return entry;
                     } catch (IOException ioe) {
-                        throwAsConcurrentModificationException(ioe);
+                        throw new DirectoryIteratorException(ioe);
                     }
                 }
             }
@@ -206,66 +197,28 @@
 
         @Override
         public synchronized boolean hasNext() {
-            if (nextEntry == null && !atEof) {
+            if (nextEntry == null && !atEof)
                 nextEntry = readNextEntry();
-
-                // at EOF?
-                if (nextEntry == null)
-                    atEof = true;
-            }
             return nextEntry != null;
         }
 
         @Override
         public synchronized Path next() {
-            if (nextEntry == null) {
-                if (!atEof) {
-                    nextEntry = readNextEntry();
-                }
-                if (nextEntry == null) {
-                    atEof = true;
-                    throw new NoSuchElementException();
-                }
+            Path result;
+            if (nextEntry == null && !atEof) {
+                result = readNextEntry();
+            } else {
+                result = nextEntry;
+                nextEntry = null;
             }
-            prevEntry = nextEntry;
-            nextEntry = null;
-            return prevEntry;
+            if (result == null)
+                throw new NoSuchElementException();
+            return result;
         }
 
         @Override
         public void remove() {
-            if (isClosed) {
-                throwAsConcurrentModificationException(new
-                    ClosedDirectoryStreamException());
-            }
-            Path entry;
-            synchronized (this) {
-                if (prevEntry == null)
-                    throw new IllegalStateException("No previous entry to remove");
-                entry = prevEntry;
-                prevEntry = null;
-            }
-
-            // use (race-free) unlinkat if available
-            try {
-                if (stream instanceof UnixSecureDirectoryStream) {
-                    ((UnixSecureDirectoryStream)stream)
-                        .implDelete(entry.getName(), false, 0);
-                } else {
-                    entry.delete();
-                }
-            } catch (IOException ioe) {
-                throwAsConcurrentModificationException(ioe);
-            } catch (SecurityException se) {
-                throwAsConcurrentModificationException(se);
-            }
+            throw new UnsupportedOperationException();
         }
     }
-
-    private static void throwAsConcurrentModificationException(Throwable t) {
-        ConcurrentModificationException cme = new ConcurrentModificationException();
-        cme.initCause(t);
-        throw cme;
-    }
-
 }
--- a/src/solaris/classes/sun/nio/fs/UnixSecureDirectoryStream.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/classes/sun/nio/fs/UnixSecureDirectoryStream.java	Fri Sep 24 16:41:32 2010 -0700
@@ -166,7 +166,7 @@
      * Deletes file/directory in this directory. Works in a race-free manner
      * when invoked with flags.
      */
-    void implDelete(Path obj, boolean haveFlags, int flags)
+    private void implDelete(Path obj, boolean haveFlags, int flags)
         throws IOException
     {
         UnixPath file = getName(obj);
--- a/src/solaris/native/java/lang/java_props_md.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/native/java/lang/java_props_md.c	Fri Sep 24 16:41:32 2010 -0700
@@ -115,6 +115,174 @@
 #define P_tmpdir "/var/tmp"
 #endif
 
+static int ParseLocale(int cat, char ** std_language, char ** std_country, char ** std_variant, char ** std_encoding) {
+    char temp[64];
+    char *language = NULL, *country = NULL, *variant = NULL,
+         *encoding = NULL;
+    char *p, encoding_variant[64];
+    char *lc;
+
+    /* Query the locale set for the category */
+    lc = setlocale(cat, NULL);
+
+#ifndef __linux__
+    if (lc == NULL) {
+        return 0;
+    }
+
+    if (cat == LC_CTYPE) {
+        /*
+         * Workaround for Solaris bug 4201684: Xlib doesn't like @euro
+         * locales. Since we don't depend on the libc @euro behavior,
+         * we just remove the qualifier.
+         * On Linux, the bug doesn't occur; on the other hand, @euro
+         * is needed there because it's a shortcut that also determines
+         * the encoding - without it, we wouldn't get ISO-8859-15.
+         * Therefore, this code section is Solaris-specific.
+         */
+        lc = strdup(lc);    /* keep a copy, setlocale trashes original. */
+        strcpy(temp, lc);
+        p = strstr(temp, "@euro");
+        if (p != NULL) {
+            *p = '\0';
+            setlocale(LC_ALL, temp);
+        }
+    }
+#else
+    if (lc == NULL || !strcmp(lc, "C") || !strcmp(lc, "POSIX")) {
+        lc = "en_US";
+    }
+#endif
+
+    /*
+     * locale string format in Solaris is
+     * <language name>_<country name>.<encoding name>@<variant name>
+     * <country name>, <encoding name>, and <variant name> are optional.
+     */
+
+    strcpy(temp, lc);
+
+    /* Parse the language, country, encoding, and variant from the
+     * locale.  Any of the elements may be missing, but they must occur
+     * in the order language_country.encoding@variant, and must be
+     * preceded by their delimiter (except for language).
+     *
+     * If the locale name (without .encoding@variant, if any) matches
+     * any of the names in the locale_aliases list, map it to the
+     * corresponding full locale name.  Most of the entries in the
+     * locale_aliases list are locales that include a language name but
+     * no country name, and this facility is used to map each language
+     * to a default country if that's possible.  It's also used to map
+     * the Solaris locale aliases to their proper Java locale IDs.
+     */
+    if ((p = strchr(temp, '.')) != NULL) {
+        strcpy(encoding_variant, p); /* Copy the leading '.' */
+        *p = '\0';
+    } else if ((p = strchr(temp, '@')) != NULL) {
+         strcpy(encoding_variant, p); /* Copy the leading '@' */
+         *p = '\0';
+    } else {
+        *encoding_variant = '\0';
+    }
+
+    if (mapLookup(locale_aliases, temp, &p)) {
+        strcpy(temp, p);
+    }
+
+    language = temp;
+    if ((country = strchr(temp, '_')) != NULL) {
+        *country++ = '\0';
+    }
+
+    p = encoding_variant;
+    if ((encoding = strchr(p, '.')) != NULL) {
+        p[encoding++ - p] = '\0';
+        p = encoding;
+    }
+    if ((variant = strchr(p, '@')) != NULL) {
+        p[variant++ - p] = '\0';
+    }
+
+    /* Normalize the language name */
+    if (std_language != NULL) {
+        *std_language = "en";
+        if (language != NULL) {
+            mapLookup(language_names, language, std_language);
+        }
+    }
+
+    /* Normalize the country name */
+    if (std_country != NULL && country != NULL) {
+        *std_country = country;
+        mapLookup(country_names, country, std_country);
+    }
+
+    /* Normalize the variant name.  Note that we only use
+     * variants listed in the mapping array; others are ignored. */
+    if (std_variant != NULL && variant != NULL) {
+        mapLookup(variant_names, variant, std_variant);
+    }
+
+    /* Normalize the encoding name.  Note that we IGNORE the string
+     * 'encoding' extracted from the locale name above.  Instead, we use the
+     * more reliable method of calling nl_langinfo(CODESET).  This function
+     * returns an empty string if no encoding is set for the given locale
+     * (e.g., the C or POSIX locales); we use the default ISO 8859-1
+     * converter for such locales.
+     */
+    if (std_encoding != NULL) {
+        /* OK, not so reliable - nl_langinfo() gives wrong answers on
+         * Euro locales, in particular. */
+        if (strcmp(p, "ISO8859-15") == 0)
+            p = "ISO8859-15";
+        else
+            p = nl_langinfo(CODESET);
+
+        /* Convert the bare "646" used on Solaris to a proper IANA name */
+        if (strcmp(p, "646") == 0)
+            p = "ISO646-US";
+
+        /* return same result nl_langinfo would return for en_UK,
+         * in order to use optimizations. */
+        *std_encoding = (*p != '\0') ? p : "ISO8859-1";
+
+#ifdef __linux__
+        /*
+         * Remap the encoding string to a different value for japanese
+         * locales on linux so that customized converters are used instead
+         * of the default converter for "EUC-JP". The customized converters
+         * omit support for the JIS0212 encoding which is not supported by
+         * the variant of "EUC-JP" encoding used on linux
+         */
+        if (strcmp(p, "EUC-JP") == 0) {
+            *std_encoding = "EUC-JP-LINUX";
+        }
+#else
+        if (strcmp(p,"eucJP") == 0) {
+            /* For Solaris use customized vendor defined character
+             * customized EUC-JP converter
+             */
+            *std_encoding = "eucJP-open";
+        } else if (strcmp(p, "Big5") == 0 || strcmp(p, "BIG5") == 0) {
+            /*
+             * Remap the encoding string to Big5_Solaris which augments
+             * the default converter for Solaris Big5 locales to include
+             * seven additional ideographic characters beyond those included
+             * in the Java "Big5" converter.
+             */
+            *std_encoding = "Big5_Solaris";
+        } else if (strcmp(p, "Big5-HKSCS") == 0) {
+            /*
+             * Solaris uses HKSCS2001
+             */
+            *std_encoding = "Big5-HKSCS-2001";
+        }
+#endif
+    }
+
+    return 1;
+}
+
 /* This function gets called very early, before VM_CALLS are setup.
  * Do not use any of the VM_CALLS entries!!!
  */
@@ -185,182 +353,25 @@
     /* Determine the language, country, variant, and encoding from the host,
      * and store these in the user.language, user.country, user.variant and
      * file.encoding system properties. */
-    {
-        char *lc;
-        lc = setlocale(LC_CTYPE, "");
-#ifndef __linux__
-        if (lc == NULL) {
-            /*
-             * 'lc == null' means system doesn't support user's environment
-             * variable's locale.
-             */
-          setlocale(LC_ALL, "C");
-          sprops.language = "en";
-          sprops.encoding = "ISO8859-1";
-          sprops.sun_jnu_encoding = sprops.encoding;
-        } else {
-#else
-        if (lc == NULL || !strcmp(lc, "C") || !strcmp(lc, "POSIX")) {
-            lc = "en_US";
-        }
-        {
-#endif
-
-            /*
-             * locale string format in Solaris is
-             * <language name>_<country name>.<encoding name>@<variant name>
-             * <country name>, <encoding name>, and <variant name> are optional.
-             */
-            char temp[64];
-            char *language = NULL, *country = NULL, *variant = NULL,
-                 *encoding = NULL;
-            char *std_language = NULL, *std_country = NULL, *std_variant = NULL,
-                 *std_encoding = NULL;
-            char *p, encoding_variant[64];
-            int i, found;
-
-#ifndef __linux__
-            /*
-             * Workaround for Solaris bug 4201684: Xlib doesn't like @euro
-             * locales. Since we don't depend on the libc @euro behavior,
-             * we just remove the qualifier.
-             * On Linux, the bug doesn't occur; on the other hand, @euro
-             * is needed there because it's a shortcut that also determines
-             * the encoding - without it, we wouldn't get ISO-8859-15.
-             * Therefore, this code section is Solaris-specific.
-             */
-            lc = strdup(lc);    /* keep a copy, setlocale trashes original. */
-            strcpy(temp, lc);
-            p = strstr(temp, "@euro");
-            if (p != NULL)
-                *p = '\0';
-            setlocale(LC_ALL, temp);
-#endif
-
-            strcpy(temp, lc);
-
-            /* Parse the language, country, encoding, and variant from the
-             * locale.  Any of the elements may be missing, but they must occur
-             * in the order language_country.encoding@variant, and must be
-             * preceded by their delimiter (except for language).
-             *
-             * If the locale name (without .encoding@variant, if any) matches
-             * any of the names in the locale_aliases list, map it to the
-             * corresponding full locale name.  Most of the entries in the
-             * locale_aliases list are locales that include a language name but
-             * no country name, and this facility is used to map each language
-             * to a default country if that's possible.  It's also used to map
-             * the Solaris locale aliases to their proper Java locale IDs.
-             */
-            if ((p = strchr(temp, '.')) != NULL) {
-                strcpy(encoding_variant, p); /* Copy the leading '.' */
-                *p = '\0';
-            } else if ((p = strchr(temp, '@')) != NULL) {
-                 strcpy(encoding_variant, p); /* Copy the leading '@' */
-                 *p = '\0';
-            } else {
-                *encoding_variant = '\0';
-            }
-
-            if (mapLookup(locale_aliases, temp, &p)) {
-                strcpy(temp, p);
-            }
-
-            language = temp;
-            if ((country = strchr(temp, '_')) != NULL) {
-                *country++ = '\0';
-            }
-
-            p = encoding_variant;
-            if ((encoding = strchr(p, '.')) != NULL) {
-                p[encoding++ - p] = '\0';
-                p = encoding;
-            }
-            if ((variant = strchr(p, '@')) != NULL) {
-                p[variant++ - p] = '\0';
-            }
-
-            /* Normalize the language name */
-            std_language = "en";
-            if (language != NULL) {
-                mapLookup(language_names, language, &std_language);
-            }
-            sprops.language = std_language;
-
-            /* Normalize the country name */
-            if (country != NULL) {
-                std_country = country;
-                mapLookup(country_names, country, &std_country);
-                sprops.country = strdup(std_country);
-            }
-
-            /* Normalize the variant name.  Note that we only use
-             * variants listed in the mapping array; others are ignored. */
-            if (variant != NULL) {
-                mapLookup(variant_names, variant, &std_variant);
-                sprops.variant = std_variant;
-            }
-
-            /* Normalize the encoding name.  Note that we IGNORE the string
-             * 'encoding' extracted from the locale name above.  Instead, we use the
-             * more reliable method of calling nl_langinfo(CODESET).  This function
-             * returns an empty string if no encoding is set for the given locale
-             * (e.g., the C or POSIX locales); we use the default ISO 8859-1
-             * converter for such locales.
-             */
-
-            /* OK, not so reliable - nl_langinfo() gives wrong answers on
-             * Euro locales, in particular. */
-            if (strcmp(p, "ISO8859-15") == 0)
-                p = "ISO8859-15";
-            else
-                p = nl_langinfo(CODESET);
-
-            /* Convert the bare "646" used on Solaris to a proper IANA name */
-            if (strcmp(p, "646") == 0)
-                p = "ISO646-US";
-
-            /* return same result nl_langinfo would return for en_UK,
-             * in order to use optimizations. */
-            std_encoding = (*p != '\0') ? p : "ISO8859-1";
-
-
-#ifdef __linux__
-            /*
-             * Remap the encoding string to a different value for japanese
-             * locales on linux so that customized converters are used instead
-             * of the default converter for "EUC-JP". The customized converters
-             * omit support for the JIS0212 encoding which is not supported by
-             * the variant of "EUC-JP" encoding used on linux
-             */
-            if (strcmp(p, "EUC-JP") == 0) {
-                std_encoding = "EUC-JP-LINUX";
-            }
-#else
-            if (strcmp(p,"eucJP") == 0) {
-                /* For Solaris use customized vendor defined character
-                 * customized EUC-JP converter
-                 */
-                std_encoding = "eucJP-open";
-            } else if (strcmp(p, "Big5") == 0 || strcmp(p, "BIG5") == 0) {
-                /*
-                 * Remap the encoding string to Big5_Solaris which augments
-                 * the default converter for Solaris Big5 locales to include
-                 * seven additional ideographic characters beyond those included
-                 * in the Java "Big5" converter.
-                 */
-                std_encoding = "Big5_Solaris";
-            } else if (strcmp(p, "Big5-HKSCS") == 0) {
-                /*
-                 * Solaris uses HKSCS2001
-                 */
-                std_encoding = "Big5-HKSCS-2001";
-            }
-#endif
-            sprops.encoding = std_encoding;
-            sprops.sun_jnu_encoding = sprops.encoding;
-        }
+    setlocale(LC_ALL, "");
+    if (ParseLocale(LC_CTYPE,
+                    &(sprops.format_language),
+                    &(sprops.format_country),
+                    &(sprops.format_variant),
+                    &(sprops.encoding))) {
+        ParseLocale(LC_MESSAGES,
+                    &(sprops.language),
+                    &(sprops.country),
+                    &(sprops.variant),
+                    NULL);
+    } else {
+        sprops.language = "en";
+        sprops.encoding = "ISO8859-1";
     }
+    sprops.display_language = sprops.language;
+    sprops.display_country = sprops.country;
+    sprops.display_variant = sprops.variant;
+    sprops.sun_jnu_encoding = sprops.encoding;
 
 #ifdef __linux__
 #if __BYTE_ORDER == __LITTLE_ENDIAN
--- a/src/solaris/native/sun/awt/gtk2_interface.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/native/sun/awt/gtk2_interface.c	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -371,6 +371,16 @@
     return convertionBuffer;
 }
 
+static void throw_exception(JNIEnv *env, const char* name, const char* message)
+{
+    jclass class = (*env)->FindClass(env, name);
+
+    if (class != NULL)
+        (*env)->ThrowNew(env, class, message);
+
+    (*env)->DeleteLocalRef(env, class);
+}
+
 /* This is a workaround for the bug:
  * http://sourceware.org/bugzilla/show_bug.cgi?id=1814
  * (dlsym/dlopen clears dlerror state)
@@ -859,14 +869,26 @@
  * comparing results. This can be optimized by using subclassed pixmap and
  * doing the second drawing only if necessary.
 */
-void gtk2_init_painting(gint width, gint height)
+void gtk2_init_painting(JNIEnv *env, gint width, gint height)
 {
     GdkGC *gc;
+    GdkPixbuf *white, *black;
 
     init_containers();
 
     if (gtk2_pixbuf_width < width || gtk2_pixbuf_height < height)
     {
+        white = (*fp_gdk_pixbuf_new)(GDK_COLORSPACE_RGB, TRUE, 8, width, height);
+        black = (*fp_gdk_pixbuf_new)(GDK_COLORSPACE_RGB, TRUE, 8, width, height);
+
+        if (white == NULL || black == NULL)
+        {
+            snprintf(convertionBuffer, CONV_BUFFER_SIZE, "Couldn't create pixbuf of size %dx%d", width, height);
+            throw_exception(env, "java/lang/RuntimeException", convertionBuffer);
+            fp_gdk_threads_leave();
+            return;
+        }
+
         if (gtk2_white_pixmap != NULL) {
             /* free old stuff */
             (*fp_g_object_unref)(gtk2_white_pixmap);
@@ -875,14 +897,12 @@
             (*fp_g_object_unref)(gtk2_black_pixbuf);
         }
 
-        gtk2_white_pixmap = (*fp_gdk_pixmap_new)
-                                (gtk2_window->window, width, height, -1);
-        gtk2_black_pixmap = (*fp_gdk_pixmap_new)
-                                (gtk2_window->window, width, height, -1);
-        gtk2_white_pixbuf = (*fp_gdk_pixbuf_new)(GDK_COLORSPACE_RGB, TRUE, 8,
-                                                 width, height);
-        gtk2_black_pixbuf = (*fp_gdk_pixbuf_new)(GDK_COLORSPACE_RGB, TRUE, 8,
-                                                 width, height);
+        gtk2_white_pixmap = (*fp_gdk_pixmap_new)(gtk2_window->window, width, height, -1);
+        gtk2_black_pixmap = (*fp_gdk_pixmap_new)(gtk2_window->window, width, height, -1);
+
+        gtk2_white_pixbuf = white;
+        gtk2_black_pixbuf = black;
+
         gtk2_pixbuf_width = width;
         gtk2_pixbuf_height = height;
     }
--- a/src/solaris/native/sun/awt/gtk2_interface.h	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/native/sun/awt/gtk2_interface.h	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -717,7 +717,7 @@
 void gtk_paint_background(WidgetType widget_type, GtkStateType state_type,
         gint x, gint y, gint width, gint height);
 
-void gtk2_init_painting(gint w, gint h);
+void gtk2_init_painting(JNIEnv *env, gint w, gint h);
 gint gtk2_copy_image(gint *dest, gint width, gint height);
 
 gint gtk2_get_xthickness(JNIEnv *env, WidgetType widget_type);
--- a/src/solaris/native/sun/awt/swing_GTKEngine.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/native/sun/awt/swing_GTKEngine.c	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. 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
@@ -293,7 +293,7 @@
         JNIEnv *env, jobject this, jint w, jint h)
 {
     fp_gdk_threads_enter();
-    gtk2_init_painting(w, h);
+    gtk2_init_painting(env, w, h);
     fp_gdk_threads_leave();
 }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/solaris/native/sun/net/sdp/SdpSupport.c	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2009, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <errno.h>
+
+#if defined(__solaris__)
+  #if !defined(PROTO_SDP)
+    #define PROTO_SDP       257
+  #endif
+#elif defined(__linux__)
+  #if !defined(AF_INET_SDP)
+    #define AF_INET_SDP     27
+  #endif
+#endif
+
+#include "jni.h"
+#include "jni_util.h"
+#include "net_util.h"
+
+#define RESTARTABLE(_cmd, _result) do { \
+  do { \
+    _result = _cmd; \
+  } while((_result == -1) && (errno == EINTR)); \
+} while(0)
+
+
+/**
+ * Creates a SDP socket.
+ */
+static int create(JNIEnv* env)
+{
+    int s;
+
+#if defined(__solaris__)
+  #ifdef AF_INET6
+    int domain = ipv6_available() ? AF_INET6 : AF_INET;
+  #else
+    int domain = AF_INET;
+  #endif
+    s = socket(domain, SOCK_STREAM, PROTO_SDP);
+#elif defined(__linux__)
+    /**
+     * IPv6 not supported by SDP on Linux
+     */
+    if (ipv6_available()) {
+        JNU_ThrowIOException(env, "IPv6 not supported");
+        return;
+    }
+    s = socket(AF_INET_SDP, SOCK_STREAM, 0);
+#else
+    /* not supported on other platforms at this time */
+    s = -1;
+    errno = EPROTONOSUPPORT;
+#endif
+
+    if (s < 0)
+        JNU_ThrowIOExceptionWithLastError(env, "socket");
+    return s;
+}
+
+/**
+ * Creates a SDP socket, returning file descriptor referencing the socket.
+ */
+JNIEXPORT jint JNICALL
+Java_sun_net_sdp_SdpSupport_create0(JNIEnv *env, jclass cls)
+{
+    return create(env);
+}
+
+/**
+ * Converts an existing file descriptor, that references an unbound TCP socket,
+ * to SDP.
+ */
+JNIEXPORT void JNICALL
+Java_sun_net_sdp_SdpSupport_convert0(JNIEnv *env, jclass cls, int fd)
+{
+    int s = create(env);
+    if (s >= 0) {
+        socklen_t len;
+        int arg, res;
+        struct linger linger;
+
+        /* copy socket options that are relevant to SDP */
+        len = sizeof(arg);
+        if (getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&arg, &len) == 0)
+            setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&arg, len);
+        len = sizeof(arg);
+        if (getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*)&arg, &len) == 0)
+            setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (char*)&arg, len);
+        len = sizeof(linger);
+        if (getsockopt(fd, SOL_SOCKET, SO_LINGER, (void*)&linger, &len) == 0)
+            setsockopt(s, SOL_SOCKET, SO_LINGER, (char*)&linger, len);
+
+        RESTARTABLE(dup2(s, fd), res);
+        if (res < 0)
+            JNU_ThrowIOExceptionWithLastError(env, "dup2");
+        RESTARTABLE(close(s), res);
+    }
+}
--- a/src/solaris/native/sun/net/spi/SdpProvider.c	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2009, Oracle and/or its affiliates. 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#if defined(__solaris__) && !defined(PROTO_SDP)
-#define PROTO_SDP       257
-#endif
-
-#include "jni.h"
-#include "jni_util.h"
-#include "net_util.h"
-
-#define RESTARTABLE(_cmd, _result) do { \
-  do { \
-    _result = _cmd; \
-  } while((_result == -1) && (errno == EINTR)); \
-} while(0)
-
-JNIEXPORT void JNICALL
-Java_sun_net_spi_SdpProvider_convert(JNIEnv *env, jclass cls, jint fd)
-{
-#ifdef PROTO_SDP
-#ifdef AF_INET6
-    int domain = ipv6_available() ? AF_INET6 : AF_INET;
-#else
-    int domain = AF_INET;
-#endif
-    int s = socket(domain, SOCK_STREAM, PROTO_SDP);
-    if (s < 0) {
-        JNU_ThrowIOExceptionWithLastError(env, "socket");
-    } else {
-        int arg, len, res;
-        struct linger linger;
-
-        /* copy socket options that are relevant to SDP */
-        len = sizeof(arg);
-        if (getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&arg, &len) == 0)
-            setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&arg, len);
-        len = sizeof(arg);
-        if (getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*)&arg, &len) == 0)
-            setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (char*)&arg, len);
-        len = sizeof(linger);
-        if (getsockopt(fd, SOL_SOCKET, SO_LINGER, (void*)&linger, &len) == 0)
-            setsockopt(s, SOL_SOCKET, SO_LINGER, (char*)&linger, len);
-
-        RESTARTABLE(dup2(s, fd), res);
-        if (res < 0)
-            JNU_ThrowIOExceptionWithLastError(env, "dup2");
-        RESTARTABLE(close(s), res);
-    }
-#else
-    JNU_ThrowInternalError(env, "should not reach here");
-#endif
-}
--- a/src/solaris/native/sun/nio/ch/IOUtil.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/solaris/native/sun/nio/ch/IOUtil.c	Fri Sep 24 16:41:32 2010 -0700
@@ -67,12 +67,9 @@
 configureBlocking(int fd, jboolean blocking)
 {
     int flags = fcntl(fd, F_GETFL);
+    int newflags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
 
-    if ((blocking == JNI_FALSE) && !(flags & O_NONBLOCK))
-        return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
-    else if ((blocking == JNI_TRUE) && (flags & O_NONBLOCK))
-        return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
-    return 0;
+    return (flags == newflags) ? 0 : fcntl(fd, F_SETFL, newflags);
 }
 
 JNIEXPORT void JNICALL
@@ -83,27 +80,25 @@
         JNU_ThrowIOExceptionWithLastError(env, "Configure blocking failed");
 }
 
-JNIEXPORT void JNICALL
-Java_sun_nio_ch_IOUtil_initPipe(JNIEnv *env, jobject this,
-                                    jintArray intArray, jboolean block)
+JNIEXPORT jlong JNICALL
+Java_sun_nio_ch_IOUtil_makePipe(JNIEnv *env, jobject this, jboolean blocking)
 {
     int fd[2];
-    jint *ptr = 0;
 
     if (pipe(fd) < 0) {
         JNU_ThrowIOExceptionWithLastError(env, "Pipe failed");
-        return;
+        return 0;
     }
-    if (block == JNI_FALSE) {
+    if (blocking == JNI_FALSE) {
         if ((configureBlocking(fd[0], JNI_FALSE) < 0)
             || (configureBlocking(fd[1], JNI_FALSE) < 0)) {
             JNU_ThrowIOExceptionWithLastError(env, "Configure blocking failed");
+            close(fd[0]);
+            close(fd[1]);
+            return 0;
         }
     }
-    ptr = (*env)->GetPrimitiveArrayCritical(env, intArray, 0);
-    ptr[0] = fd[0];
-    ptr[1] = fd[1];
-    (*env)->ReleasePrimitiveArrayCritical(env, intArray, ptr, 0);
+    return ((jlong) fd[0] << 32) | (jlong) fd[1];
 }
 
 JNIEXPORT jboolean JNICALL
@@ -131,21 +126,22 @@
 {
     if (n > 0) /* Number of bytes written */
         return n;
-    if (n < 0) {
-        if (errno == EAGAIN)
-            return IOS_UNAVAILABLE;
-        if (errno == EINTR)
-            return IOS_INTERRUPTED;
-    }
-    if (n == 0) {
+    else if (n == 0) {
         if (reading) {
             return IOS_EOF; /* EOF is -1 in javaland */
         } else {
             return 0;
         }
     }
-    JNU_ThrowIOExceptionWithLastError(env, "Read/write failed");
-    return IOS_THROWN;
+    else if (errno == EAGAIN)
+        return IOS_UNAVAILABLE;
+    else if (errno == EINTR)
+        return IOS_INTERRUPTED;
+    else {
+        const char *msg = reading ? "Read failed" : "Write failed";
+        JNU_ThrowIOExceptionWithLastError(env, msg);
+        return IOS_THROWN;
+    }
 }
 
 /* Declared in nio_util.h for use elsewhere in NIO */
@@ -155,21 +151,22 @@
 {
     if (n > 0) /* Number of bytes written */
         return n;
-    if (n < 0) {
-        if (errno == EAGAIN)
-            return IOS_UNAVAILABLE;
-        if (errno == EINTR)
-            return IOS_INTERRUPTED;
-    }
-    if (n == 0) {
+    else if (n == 0) {
         if (reading) {
             return IOS_EOF; /* EOF is -1 in javaland */
         } else {
             return 0;
         }
     }
-    JNU_ThrowIOExceptionWithLastError(env, "Read/write failed");
-    return IOS_THROWN;
+    else if (errno == EAGAIN)
+        return IOS_UNAVAILABLE;
+    else if (errno == EINTR)
+        return IOS_INTERRUPTED;
+    else {
+        const char *msg = reading ? "Read failed" : "Write failed";
+        JNU_ThrowIOExceptionWithLastError(env, msg);
+        return IOS_THROWN;
+    }
 }
 
 jint
--- a/src/windows/bin/java_md.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/bin/java_md.c	Fri Sep 24 16:41:32 2010 -0700
@@ -105,15 +105,15 @@
         exit(1);
     }
 
-    /* Do this before we read jvm.cfg */
-    EnsureJreInstallation(jrepath);
-
     /* Find out where the JRE is that we will be using. */
     if (!GetJREPath(jrepath, so_jrepath)) {
         JLI_ReportErrorMessage(JRE_ERROR1);
         exit(2);
     }
 
+    /* Do this before we read jvm.cfg and after jrepath is initialized */
+    EnsureJreInstallation(jrepath);
+
     /* Find the specified JVM type */
     if (ReadKnownVMs(jrepath, (char*)GetArch(), JNI_FALSE) < 1) {
         JLI_ReportErrorMessage(CFG_ERROR7);
@@ -162,6 +162,10 @@
 #endif
 #ifdef CRT_DLL
         if (GetJREPath(crtpath, MAXPATHLEN)) {
+            if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") + JLI_StrLen(CRT_DLL) >= MAXPATHLEN) {
+                JLI_ReportErrorMessage(JRE_ERROR11);
+                return JNI_FALSE;
+            }
             (void)JLI_StrCat(crtpath, "\\bin\\" CRT_DLL);   /* Add crt dll */
             JLI_TraceLauncher("CRT path is %s\n", crtpath);
             if (_access(crtpath, 0) == 0) {
@@ -213,6 +217,7 @@
     }
     /* Does our bundle directory exist ? */
     JLI_Snprintf(tmpbuf, sizeof(tmpbuf), "%s\\lib\\bundles", jrepath);
+    JLI_TraceLauncher("EnsureJreInstallation: %s\n", tmpbuf);
     if (stat(tmpbuf, &s) != 0) {
         return;
     }
@@ -851,8 +856,7 @@
     /*
      * If this isn't the selected version, exec the selected version.
      */
-    (void)JLI_StrCat(JLI_StrCat(JLI_StrCpy(path, jre), "\\bin\\"), progname);
-    (void)JLI_StrCat(path, ".exe");
+    JLI_Snprintf(path, sizeof(path), "%s\\bin\\%s.exe", jre, progname);
 
     /*
      * Although Windows has an execv() entrypoint, it doesn't actually
--- a/src/windows/classes/sun/nio/fs/WindowsDirectoryStream.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/classes/sun/nio/fs/WindowsDirectoryStream.java	Fri Sep 24 16:41:32 2010 -0700
@@ -28,7 +28,6 @@
 import java.nio.file.*;
 import java.nio.file.attribute.BasicFileAttributes;
 import java.util.Iterator;
-import java.util.ConcurrentModificationException;
 import java.util.NoSuchElementException;
 import java.io.IOException;
 
@@ -121,17 +120,10 @@
         }
     }
 
-    private static void throwAsConcurrentModificationException(Throwable t) {
-        ConcurrentModificationException cme = new ConcurrentModificationException();
-        cme.initCause(t);
-        throw cme;
-    }
-
     private class WindowsDirectoryIterator implements Iterator<Path> {
         private boolean atEof;
         private String first;
         private Path nextEntry;
-        private Path prevEntry;
 
         WindowsDirectoryIterator(String first) {
             atEof = false;
@@ -156,7 +148,7 @@
                 if (filter.accept(entry))
                     return entry;
             } catch (IOException ioe) {
-                throwAsConcurrentModificationException(ioe);
+                throw new DirectoryIteratorException(ioe);
             }
             return null;
         }
@@ -177,21 +169,19 @@
 
                 // synchronize on closeLock to prevent close while reading
                 synchronized (closeLock) {
-                    if (!isOpen)
-                        throwAsConcurrentModificationException(new
-                            ClosedDirectoryStreamException());
                     try {
-                        name = FindNextFile(handle, findDataBuffer.address());
-                        if (name == null) {
-                            // NO_MORE_FILES
-                            return null;
+                        if (isOpen) {
+                            name = FindNextFile(handle, findDataBuffer.address());
                         }
                     } catch (WindowsException x) {
-                        try {
-                            x.rethrowAsIOException(dir);
-                        } catch (IOException ioe) {
-                            throwAsConcurrentModificationException(ioe);
-                        }
+                        IOException ioe = x.asIOException(dir);
+                        throw new DirectoryIteratorException(ioe);
+                    }
+
+                    // NO_MORE_FILES or stream closed
+                    if (name == null) {
+                        atEof = true;
+                        return null;
                     }
 
                     // grab the attributes from the WIN32_FIND_DATA structure
@@ -210,49 +200,28 @@
 
         @Override
         public synchronized boolean hasNext() {
-            if (nextEntry == null && !atEof) {
+            if (nextEntry == null && !atEof)
                 nextEntry = readNextEntry();
-                atEof = (nextEntry == null);
-            }
             return nextEntry != null;
         }
 
         @Override
         public synchronized Path next() {
-            if (nextEntry == null) {
-                if (!atEof) {
-                    nextEntry = readNextEntry();
-                }
-                if (nextEntry == null) {
-                    atEof = true;
-                    throw new NoSuchElementException();
-                }
+            Path result = null;
+            if (nextEntry == null && !atEof) {
+                result = readNextEntry();
+            } else {
+                result = nextEntry;
+                nextEntry = null;
             }
-            prevEntry = nextEntry;
-            nextEntry = null;
-            return prevEntry;
+            if (result == null)
+                throw new NoSuchElementException();
+            return result;
         }
 
         @Override
         public void remove() {
-            if (!isOpen) {
-                throwAsConcurrentModificationException(new
-                    ClosedDirectoryStreamException());
-            }
-            Path entry;
-            synchronized (this) {
-                if (prevEntry == null)
-                    throw new IllegalStateException("no last element");
-                entry = prevEntry;
-                prevEntry = null;
-            }
-            try {
-                entry.delete();
-            } catch (IOException ioe) {
-                throwAsConcurrentModificationException(ioe);
-            } catch (SecurityException se) {
-                throwAsConcurrentModificationException(se);
-            }
+            throw new UnsupportedOperationException();
         }
     }
 }
--- a/src/windows/native/java/lang/java_props_md.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/native/java/lang/java_props_md.c	Fri Sep 24 16:41:32 2010 -0700
@@ -43,413 +43,48 @@
 #endif
 
 typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
+static void SetupI18nProps(LCID lcid, char** language, char** country,
+               char** variant, char** encoding);
 
 #define SHELL_KEY "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"
 
-/* Encodings for Windows language groups. According to
-   www.microsoft.com/globaldev/faqs/locales.asp,
-   some locales do not have codepages, and are
-   supported in Windows 2000/XP solely through Unicode.
-   In this case, we use utf-8 encoding */
+static char *
+getEncodingInternal(LCID lcid)
+{
+    char * ret = malloc(16);
+    int codepage;
 
-static char *encoding_names[] = {
-    "Cp1250",    /*  0:Latin 2  */
-    "Cp1251",    /*  1:Cyrillic */
-    "Cp1252",    /*  2:Latin 1  */
-    "Cp1253",    /*  3:Greek    */
-    "Cp1254",    /*  4:Latin 5  */
-    "Cp1255",    /*  5:Hebrew   */
-    "Cp1256",    /*  6:Arabic   */
-    "Cp1257",    /*  7:Baltic   */
-    "Cp1258",    /*  8:Viet Nam */
-    "MS874",     /*  9:Thai     */
-    "MS932",     /* 10:Japanese */
-    "GBK",       /* 11:PRC GBK  */
-    "MS949",     /* 12:Korean Extended Wansung */
-    "MS950",     /* 13:Chinese (Taiwan, Hongkong, Macau) */
-    "utf-8",     /* 14:Unicode  */
-    "MS1361",    /* 15:Korean Johab */
-};
-
-/*
- * List mapping from LanguageID to Java locale IDs.
- * The entries in this list should not be construed to suggest we actually have
- * full locale-data and other support for all of these locales; these are
- * merely all of the Windows locales for which we could construct an accurate
- * locale ID.  The data is based on the web page "Windows XP/Server 2003 -
- * List of Locale IDs, Input Locale, and Language Collection"
- * (http://www.microsoft.com/globaldev/reference/winxp/xp-lcid.mspx)
- *
- * Some of the language IDs below are not yet used by Windows, but were
- * defined by Microsoft for other products, such as Office XP. They may
- * become Windows language IDs in the future.
- *
- */
-typedef struct LANGIDtoLocale {
-    WORD    langID;
-    WORD    encoding;
-    char*   javaID;
-} LANGIDtoLocale;
+    if (GetLocaleInfo(lcid,
+                      LOCALE_IDEFAULTANSICODEPAGE,
+                      ret+2, 14) == 0) {
+        codepage = 1252;
+    } else {
+        codepage = atoi(ret+2);
+    }
 
-static LANGIDtoLocale langIDMap[] = {
-    /* fallback locales to use when the country code doesn't match anything we have */
-    0x01,    6, "ar",
-    0x02,    1, "bg",
-    0x03,    2, "ca",
-    0x04,   11, "zh",
-    0x05,    0, "cs",
-    0x06,    2, "da",
-    0x07,    2, "de",
-    0x08,    3, "el",
-    0x09,    2, "en",
-    0x0a,    2, "es",
-    0x0b,    2, "fi",
-    0x0c,    2, "fr",
-    0x0d,    5, "iw",
-    0x0e,    0, "hu",
-    0x0f,    2, "is",
-    0x10,    2, "it",
-    0x11,   10, "ja",
-    0x12,   12, "ko",
-    0x13,    2, "nl",
-    0x14,    2, "no",
-    0x15,    0, "pl",
-    0x16,    2, "pt",
-    0x17,    2, "rm",
-    0x18,    0, "ro",
-    0x19,    1, "ru",
-    0x1a,    0, "sr",
-    0x1b,    0, "sk",
-    0x1c,    0, "sq",
-    0x1d,    2, "sv",
-    0x1e,    9, "th",
-    0x1f,    4, "tr",
-    0x20,    2, "ur",
-    0x21,    2, "in",
-    0x22,    1, "uk",
-    0x23,    1, "be",
-    0x24,    0, "sl",
-    0x25,    7, "et",
-    0x26,    7, "lv",
-    0x27,    7, "lt",
-    0x28,    1, "tg",
-    0x29,    6, "fa",
-    0x2a,    8, "vi",
-    0x2b,   14, "hy",
-    0x2c,    4, "az",
-    0x2d,    2, "eu",
-/*  0x2e,    2, "??",  no ISO-639 abbreviation for Sorbian */
-    0x2f,    1, "mk",
-    0x31,    2, "ts",
-    0x32,    2, "tn",
-    0x34,    2, "xh",
-    0x35,    2, "zu",
-    0x36,    2, "af",
-    0x37,   14, "ka",
-    0x38,    2, "fo",
-    0x39,   14, "hi",
-    0x3a,   14, "mt",
-    0x3b,    2, "se",
-    0x3c,    2, "gd",
-    0x3d,    2, "yi",
-    0x3e,    2, "ms",
-    0x3f,    1, "kk",
-    0x40,    1, "ky",
-    0x41,    2, "sw",
-    0x42,    0, "tk",
-    0x43,    1, "uz",
-    0x44,    1, "tt",
-    0x45,   14, "bn",
-    0x46,   14, "pa",
-    0x47,   14, "gu",
-    0x48,   14, "or",
-    0x49,   14, "ta",
-    0x4a,   14, "te",
-    0x4b,   14, "kn",
-    0x4c,   14, "ml",
-    0x4d,   14, "as",
-    0x4e,   14, "mr",
-    0x4f,   14, "sa",
-    0x50,    1, "mn",
-    0x51,   14, "bo",
-    0x52,    1, "cy",
-    0x53,   14, "km",
-    0x54,   14, "lo",
-    0x56,    2, "gl",
-    0x5b,   14, "si",
-    0x5d,   14, "iu",
-    0x5e,   14, "am",
-/*  0x5f,    2, "??",  no ISO-639 abbreviation for Tamazight */
-    0x68,    2, "ha",
-    0x6a,    2, "yo",
-    0x6b,    2, "qu",
-    0x6d,    1, "ba",
-    0x6f,    2, "kl",
-    0x70,    2, "ig",
-/*  0x78,   14, "??",  no ISO-639 abbreviation for Yi */
-    0x7e,    2, "br",
-    0x80,    6, "ug",
-    0x81,   14, "mi",
-    0x82,    2, "oc",
-    0x83,    2, "co",
-/*  0x84,    2, "??",  no ISO-639 abbreviation for Alsatian */
-/*  0x85,    1, "??",  no ISO-639 abbreviation for Yakut */
-/*  0x86,    2, "??",  no ISO-639 abbreviation for K'iche */
-    0x87,    2, "rw",
-    0x88,    2, "wo",
-/*  0x8c,    6, "??",  no ISO-639 abbreviation for Dari */
-    /* mappings for real Windows LCID values */
-    0x0401,  6, "ar_SA",
-    0x0402,  1, "bg_BG",
-    0x0403,  2, "ca_ES",
-    0x0404, 13, "zh_TW",
-    0x0405,  0, "cs_CZ",
-    0x0406,  2, "da_DK",
-    0x0407,  2, "de_DE",
-    0x0408,  3, "el_GR",
-    0x0409,  2, "en_US",
-    0x040a,  2, "es_ES",  /* (traditional sort) */
-    0x040b,  2, "fi_FI",
-    0x040c,  2, "fr_FR",
-    0x040d,  5, "iw_IL",
-    0x040e,  0, "hu_HU",
-    0x040f,  2, "is_IS",
-    0x0410,  2, "it_IT",
-    0x0411, 10, "ja_JP",
-    0x0412, 12, "ko_KR",
-    0x0413,  2, "nl_NL",
-    0x0414,  2, "no_NO",
-    0x0415,  0, "pl_PL",
-    0x0416,  2, "pt_BR",
-    0x0417,  2, "rm_CH",
-    0x0418,  0, "ro_RO",
-    0x0419,  1, "ru_RU",
-    0x041a,  0, "hr_HR",
-    0x041b,  0, "sk_SK",
-    0x041c,  0, "sq_AL",
-    0x041d,  2, "sv_SE",
-    0x041e,  9, "th_TH",
-    0x041f,  4, "tr_TR",
-    0x0420,  6, "ur_PK",
-    0x0421,  2, "in_ID",
-    0x0422,  1, "uk_UA",
-    0x0423,  1, "be_BY",
-    0x0424,  0, "sl_SI",
-    0x0425,  7, "et_EE",
-    0x0426,  7, "lv_LV",
-    0x0427,  7, "lt_LT",
-    0x0428,  1, "tg_TJ",
-    0x0429,  6, "fa_IR",
-    0x042a,  8, "vi_VN",
-    0x042b, 14, "hy_AM",  /* Armenian  */
-    0x042c,  4, "az_AZ",  /* Azeri_Latin */
-    0x042d,  2, "eu_ES",
-/*  0x042e,  2, "??",      no ISO-639 abbreviation for Upper Sorbian */
-    0x042f,  1, "mk_MK",
-/*  0x0430,  2, "??",      no ISO-639 abbreviation for Sutu */
-    0x0431,  2, "ts",     /* (country?) */
-    0x0432,  2, "tn_ZA",
-/*  0x0433,  2, "??",      no ISO-639 abbreviation for Venda */
-    0x0434,  2, "xh_ZA",
-    0x0435,  2, "zu_ZA",
-    0x0436,  2, "af_ZA",
-    0x0437, 14, "ka_GE",  /* Georgian   */
-    0x0438,  2, "fo_FO",
-    0x0439, 14, "hi_IN",
-    0x043a, 14, "mt_MT",
-    0x043b,  2, "se_NO",  /* Sami, Northern - Norway */
-    0x043c,  2, "gd_GB",
-    0x043d,  2, "yi",     /* (country?) */
-    0x043e,  2, "ms_MY",
-    0x043f,  1, "kk_KZ",  /* Kazakh */
-    0x0440,  1, "ky_KG",  /* Kyrgyz     */
-    0x0441,  2, "sw_KE",
-    0x0442,  0, "tk_TM",
-    0x0443,  4, "uz_UZ",  /* Uzbek_Latin */
-    0x0444,  1, "tt_RU",  /* Tatar */
-    0x0445, 14, "bn_IN",  /* Bengali   */
-    0x0446, 14, "pa_IN",  /* Punjabi   */
-    0x0447, 14, "gu_IN",  /* Gujarati  */
-    0x0448, 14, "or_IN",  /* Oriya     */
-    0x0449, 14, "ta_IN",  /* Tamil     */
-    0x044a, 14, "te_IN",  /* Telugu    */
-    0x044b, 14, "kn_IN",  /* Kannada   */
-    0x044c, 14, "ml_IN",  /* Malayalam */
-    0x044d, 14, "as_IN",  /* Assamese  */
-    0x044e, 14, "mr_IN",  /* Marathi   */
-    0x044f, 14, "sa_IN",  /* Sanskrit  */
-    0x0450,  1, "mn_MN",  /* Mongolian */
-    0x0451, 14, "bo_CN",  /* Tibetan   */
-    0x0452,  2, "cy_GB",  /* Welsh     */
-    0x0453, 14, "km_KH",  /* Khmer     */
-    0x0454, 14, "lo_LA",  /* Lao       */
-    0x0456,  2, "gl_ES",  /* Galician  */
-/*  0x0457, 14, "??_IN",  /* Konkani, no ISO-639 abbreviation*/
-/*  0x045a, 14, "??_SY",  /* Syriac, no ISO-639 abbreviation*/
-    0x045b, 14, "si_LK",  /* Sinhala   */
-    0x045d, 14, "iu_CA",  /* Inuktitut */
-    0x045e, 14, "am_ET",  /* Amharic   */
-    0x0461, 14, "ne_NP",  /* Nepali */
-    0x0462,  2, "fy_NL",  /* Frisian */
-    0x0463,  6, "ps_AF",  /* Pushto */
-/*  0x0464,  2, "??_PH",  /* Filipino, no ISO-639 abbreviation*/
-    0x0465, 14, "dv_MV",  /* Divehi    */
-    0x0468,  2, "ha_NG",  /* Hausa     */
-    0x046a,  2, "yo_NG",  /* Yoruba    */
-    0x046b,  2, "qu_BO",  /* Quechua - Bolivia */
-/*  0x046c,  2, "??_ZA",  /* Northern Sotho, no ISO-639 abbreviation */
-    0x046d,  1, "ba_RU",  /* Bashkir   */
-    0x046e,  2, "lb_LU",  /* Luxembourgish */
-    0x046f,  2, "kl_GL",  /* Greenlandic */
-    0x0470,  2, "ig_NG",  /* Igbo      */
-/*  0x0478, 14, "??_CN",  /* Yi (PRC), no ISO-639 abbreviation */
-/*  0x047a,  2, "??_CL",  /* Mapudungun (Araucanian), no ISO-639 abbreviation */
-/*  0x047c,  2, "??_CA",  /* Mohawk, no ISO-639 abbreviation */
-    0x047e,  2, "br_FR",  /* Breton    */
-    0x0480,  6, "ug_CN",  /* Uighur    */
-    0x0481, 14, "mi_NZ",  /* Maori - New Zealand */
-    0x0482,  2, "oc_FR",  /* Occitan   */
-    0x0483,  2, "co_FR",  /* Corsican  */
-/*  0x0484,  2, "??_FR",  /* Alsatian, no ISO-639 abbreviation */
-/*  0x0485,  1, "??_RU",  /* Yakut, no ISO-639 abbreviation */
-/*  0x0486,  2, "??_GT",  /* K'iche, no ISO-639 abbreviation */
-    0x0487,  2, "rw_RW",  /* Kinyarwanda */
-    0x0488,  2, "wo_SN",  /* Wolof */
-/*  0x048c,  6, "??_AF",  /* Dari, no ISO-639 abbreviation */
-    0x0801,  6, "ar_IQ",
-    0x0804, 11, "zh_CN",
-    0x0807,  2, "de_CH",
-    0x0809,  2, "en_GB",
-    0x080a,  2, "es_MX",
-    0x080c,  2, "fr_BE",
-    0x0810,  2, "it_CH",
-    0x0812, 15, "ko_KR",  /* Korean(Johab)*/
-    0x0813,  2, "nl_BE",
-    0x0814,  2, "no_NO_NY",
-    0x0816,  2, "pt_PT",
-    0x0818,  0, "ro_MD",
-    0x0819,  1, "ru_MD",
-    0x081a,  0, "sr_CS",
-    0x081d,  2, "sv_FI",
-    0x082c,  1, "az_AZ",  /* Azeri_Cyrillic */
-/*  0x082e,  2, "??",      no ISO-639 abbreviation for Lower Sorbian */
-    0x083b,  2, "se_SE",  /* Sami, Northern - Sweden */
-    0x083c,  2, "ga_IE",
-    0x083e,  2, "ms_BN",
-    0x0843,  1, "uz_UZ",  /* Uzbek_Cyrillic */
-    0x0845, 14, "bn_BD",  /* Bengali   */
-    0x0850, 14, "mn_CN",  /* Traditional Mongolian */
-    0x085d,  2, "iu_CA",  /* Inuktitut */
-/*  0x085f,  2, "??_DZ",      no ISO-639 abbreviation for Tamazight */
-    0x086b,  2, "qu_EC",  /* Quechua - Ecuador */
-    0x0c01,  6, "ar_EG",
-    0x0c04, 13, "zh_HK",
-    0x0c07,  2, "de_AT",
-    0x0c09,  2, "en_AU",
-    0x0c0a,  2, "es_ES",  /* (modern sort) */
-    0x0c0c,  2, "fr_CA",
-    0x0c1a,  1, "sr_CS",
-    0x0c3b,  2, "se_FI",  /* Sami, Northern - Finland */
-    0x0c6b,  2, "qu_PE",  /* Quechua - Peru */
-    0x1001,  6, "ar_LY",
-    0x1004, 11, "zh_SG",
-    0x1007,  2, "de_LU",
-    0x1009,  2, "en_CA",
-    0x100a,  2, "es_GT",
-    0x100c,  2, "fr_CH",
-    0x101a,  0, "hr_BA",
-/*  0x103b,  2, "??_NO",  /* Sami, Lule - Norway */
-    0x1401,  6, "ar_DZ",
-    0x1404, 13, "zh_MO",
-    0x1407,  2, "de_LI",
-    0x1409,  2, "en_NZ",
-    0x140a,  2, "es_CR",
-    0x140c,  2, "fr_LU",
-    0x141a,  0, "bs_BA",
-/*  0x143b,  2, "??_SE",  /* Sami, Lule - Sweden */
-    0x1801,  6, "ar_MA",
-    0x1809,  2, "en_IE",
-    0x180a,  2, "es_PA",
-    0x180c,  2, "fr_MC",
-    0x181a,  0, "sr_BA",
-/*  0x183b,  2, "??_NO",  /* Sami, Southern - Norway */
-    0x1c01,  6, "ar_TN",
-    0x1c09,  2, "en_ZA",
-    0x1c0a,  2, "es_DO",
-    0x1c1a,  1, "sr_BA",
-/*  0x1c3b,  2, "??_SE",  /* Sami, Southern - Sweden */
-    0x2001,  6, "ar_OM",
-    0x2009,  2, "en_JM",
-    0x200a,  2, "es_VE",
-    0x201a,  0, "bs_BA",  /* Bosnian (Cyrillic) */
-/*  0x203b,  2, "??_FI",  /* Sami, Skolt - Finland */
-    0x2401,  6, "ar_YE",
-    0x2409,  2, "en",     /* ("Caribbean", which could be any of many countries) */
-    0x240a,  2, "es_CO",
-/*  0x243b,  2, "??_FI",  /* Sami, Inari - Finland */
-    0x2801,  6, "ar_SY",
-    0x2809,  2, "en_BZ",
-    0x280a,  2, "es_PE",
-    0x2c01,  6, "ar_JO",
-    0x2c09,  2, "en_TT",
-    0x2c0a,  2, "es_AR",
-    0x3001,  6, "ar_LB",
-    0x3009,  2, "en_ZW",
-    0x300a,  2, "es_EC",
-    0x3401,  6, "ar_KW",
-    0x3409,  2, "en_PH",
-    0x340a,  2, "es_CL",
-    0x3801,  6, "ar_AE",
-    0x380a,  2, "es_UY",
-    0x3c01,  6, "ar_BH",
-    0x3c0a,  2, "es_PY",
-    0x4001,  6, "ar_QA",
-    0x4009,  2, "en_IN",
-    0x400a,  2, "es_BO",
-    0x4409,  2, "en_MY",
-    0x440a,  2, "es_SV",
-    0x4809,  2, "en_SG",
-    0x480a,  2, "es_HN",
-    0x4c0a,  2, "es_NI",
-    0x500a,  2, "es_PR",
-    0x540a,  2, "es_US"
-};
-
-/*
- * binary-search our list of LANGID values.  If we don't find the
- * one we're looking for, mask out the country code and try again
- * with just the primary language ID
- */
-static int
-getLocaleEntryIndex(LANGID langID)
-{
-    int index = -1;
-    int tries = 0;
-    do {
-        int lo, hi, mid;
-        lo = 0;
-        hi = sizeof(langIDMap) / sizeof(LANGIDtoLocale);
-        while (index == -1 && lo < hi) {
-            mid = (lo + hi) / 2;
-            if (langIDMap[mid].langID == langID) {
-                index = mid;
-            } else if (langIDMap[mid].langID > langID) {
-                hi = mid;
-            } else {
-                lo = mid + 1;
-            }
-        }
-        langID = PRIMARYLANGID(langID);
-        ++tries;
-    } while (index == -1 && tries < 2);
-
-    return index;
-}
-
-static char *
-getEncodingInternal(int index)
-{
-    char * ret = encoding_names[langIDMap[index].encoding];
+    switch (codepage) {
+    case 0:
+        strcpy(ret, "UTF-8");
+        break;
+    case 874:     /*  9:Thai     */
+    case 932:     /* 10:Japanese */
+    case 949:     /* 12:Korean Extended Wansung */
+    case 950:     /* 13:Chinese (Taiwan, Hongkong, Macau) */
+    case 1361:    /* 15:Korean Johab */
+        ret[0] = 'M';
+        ret[1] = 'S';
+        break;
+    case 936:
+        strcpy(ret, "GBK");
+        break;
+    case 54936:
+        strcpy(ret, "GB18030");
+        break;
+    default:
+        ret[0] = 'C';
+        ret[1] = 'p';
+        break;
+    }
 
     //Traditional Chinese Windows should use MS950_HKSCS_XP as the
     //default encoding, if HKSCS patch has been installed.
@@ -460,7 +95,7 @@
         WCHAR  unicodeChar;
         MultiByteToWideChar(CP_ACP, 0, mbChar, 2, &unicodeChar, 1);
         if (unicodeChar == 0x92db) {
-            ret = "MS950_HKSCS_XP";
+            strcpy(ret, "MS950_HKSCS_XP");
         }
     } else {
         //SimpChinese Windows should use GB18030 as the default
@@ -476,7 +111,7 @@
                 strcat(systemPath, "\\FONTS\\SimSun18030.ttc");
                 if ((f = fopen(systemPath, "r")) != NULL) {
                     fclose(f);
-                    ret = "GB18030";
+                    strcpy(ret, "GB18030");
                 }
             }
         }
@@ -489,25 +124,35 @@
 DllExport const char *
 getEncodingFromLangID(LANGID langID)
 {
-    int index = getLocaleEntryIndex(langID);
-
-    if (index != (-1)) {
-        return getEncodingInternal(index);
-    } else {
-        return "Cp1252";
-    }
+    return getEncodingInternal(MAKELCID(langID, SORT_DEFAULT));
 }
 
 DllExport const char *
 getJavaIDFromLangID(LANGID langID)
 {
-    int index = getLocaleEntryIndex(langID);
+    char * lang;
+    char * ctry;
+    char * vrnt;
+    char * enc;
+    char * ret = malloc(16);
 
-    if (index != (-1)) {
-        return langIDMap[index].javaID;
+    SetupI18nProps(MAKELCID(langID, SORT_DEFAULT), &lang, &ctry, &vrnt, &enc);
+    if (ctry[0] != '\0') {
+        if (vrnt[0] != '\0') {
+            sprintf(ret, "%s_%s_%s", lang, ctry, vrnt);
+        } else {
+            sprintf(ret, "%s_%s", lang, ctry);
+        }
     } else {
-        return NULL;
+        strcpy(ret, lang);
     }
+
+    free(lang);
+    free(ctry);
+    free(vrnt);
+    free(enc);
+
+    return ret;
 }
 
 /*
@@ -644,6 +289,58 @@
     return NULL;
 }
 
+#define PROPSIZE 3      // two-letter + null terminator
+static void
+SetupI18nProps(LCID lcid, char** language, char** country,
+               char** variant, char** encoding) {
+    /* country */
+    *country = malloc(PROPSIZE);
+    if (GetLocaleInfo(lcid,
+                      LOCALE_SISO3166CTRYNAME, *country, PROPSIZE) == 0) {
+        (*country)[0] = '\0';
+    }
+
+    /* language */
+    *language = malloc(PROPSIZE);
+    if (lcid == 0x46c) {
+        /* Windows returns non-existent language code "ns" for Northern Sotho.
+         * Defaults to en_US
+         */
+        strcpy(*language, "en");
+        strcpy(*country, "US");
+    } else if (GetLocaleInfo(lcid,
+                      LOCALE_SISO639LANGNAME, *language, PROPSIZE) == 0) {
+        if (lcid == 0x465) {
+            /* for some reason, Windows returns "div" for this Divehi LCID, even though
+             * there is a two letter language code "dv".  Tweak it here.
+             */
+            strcpy(*language, "dv");
+            strcpy(*country, "MV");
+        } else {
+            /* defaults to en_US */
+            strcpy(*language, "en");
+            strcpy(*country, "US");
+        }
+    }
+
+    /* variant */
+    *variant = malloc(PROPSIZE);
+    (*variant)[0] = '\0';
+
+    /* handling for Norwegian */
+    if (strcmp(*language, "nb") == 0) {
+        strcpy(*language, "no");
+        strcpy(*country , "NO");
+    } else if (strcmp(*language, "nn") == 0) {
+        strcpy(*language, "no");
+        strcpy(*country , "NO");
+        strcpy(*variant, "NY");
+    }
+
+    /* encoding */
+    *encoding = getEncodingInternal(lcid);
+}
+
 java_props_t *
 GetJavaProperties(JNIEnv* env)
 {
@@ -876,62 +573,31 @@
          * query the system for the current system default locale
          * (which is a Windows LCID value),
          */
-        LANGID langID = LANGIDFROMLCID(GetUserDefaultLCID());
-        LANGID sysLangID = LANGIDFROMLCID(GetSystemDefaultLCID());
+        LCID userDefaultLCID = GetUserDefaultLCID();
+        LCID systemDefaultLCID = GetSystemDefaultLCID();
+        LCID userDefaultUILang = GetUserDefaultUILanguage();
 
         {
-            int index = getLocaleEntryIndex(langID);
-
-            /*
-             * if we didn't find the LCID that the system returned to us,
-             * we don't have a Java locale ID that corresponds to it.
-             * Fall back on en_US.
-             */
-            if (index == -1) {
-                sprops.language = "en";
-                sprops.country = "US";
-                sprops.encoding = "Cp1252";
-            } else {
-
-                /* otherwise, look up the corresponding Java locale ID from
-                 * the list of Java locale IDs and set up the system properties
-                 * accordingly.
-                 */
-
-                char* lang;
-                char* ctry;
-                char* variant;
-
-                lang = strdup(langIDMap[index].javaID);
-                ctry = lang;
+            char * display_encoding;
 
-                while (*ctry != '_' && *ctry != 0)
-                    ++ctry;
-
-                if (*ctry == '_') {
-                    *ctry++ = 0;
-                }
-
-                variant = ctry;
-                while (*variant != '_' && *variant != 0)
-                    ++variant;
+            SetupI18nProps(userDefaultUILang,
+                           &sprops.language,
+                           &sprops.country,
+                           &sprops.variant,
+                           &display_encoding);
+            SetupI18nProps(userDefaultLCID,
+                           &sprops.format_language,
+                           &sprops.format_country,
+                           &sprops.format_variant,
+                           &sprops.encoding);
+            SetupI18nProps(userDefaultUILang,
+                           &sprops.display_language,
+                           &sprops.display_country,
+                           &sprops.display_variant,
+                           &display_encoding);
 
-                if (*variant == '_') {
-                    *variant++ = 0;
-                }
-
-                sprops.language = lang;
-                sprops.country = ctry;
-                sprops.variant = variant;
-                sprops.encoding = getEncodingInternal(index);
-            }
-            index = getLocaleEntryIndex(sysLangID);
-            if (index == -1) {
-                sprops.sun_jnu_encoding = "Cp1252";
-            } else {
-                sprops.sun_jnu_encoding = getEncodingInternal(index);
-            }
-            if (langID == 0x0c04 && ver.dwMajorVersion == 6) {
+            sprops.sun_jnu_encoding = getEncodingInternal(systemDefaultLCID);
+            if (LANGIDFROMLCID(userDefaultLCID) == 0x0c04 && ver.dwMajorVersion == 6) {
                 // MS claims "Vista has built-in support for HKSCS-2004.
                 // All of the HKSCS-2004 characters have Unicode 4.1.
                 // PUA code point assignments". But what it really means
--- a/src/windows/native/sun/windows/awt_DataTransferer.cpp	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/native/sun/windows/awt_DataTransferer.cpp	Fri Sep 24 16:41:32 2010 -0700
@@ -201,6 +201,7 @@
         throw std::bad_alloc();
     }
     env->SetByteArrayRegion(retval, 0, length, (jbyte *)encoding);
+    free((void *)encoding);
     return retval;
 }
 
--- a/src/windows/native/sun/windows/awt_InputMethod.cpp	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/native/sun/windows/awt_InputMethod.cpp	Fri Sep 24 16:41:32 2010 -0700
@@ -296,7 +296,9 @@
         // so we can reset this flag.
         g_bUserHasChangedInputLang = FALSE;
 
-        return CreateLocaleObject(env, javaLocaleName);
+        jobject ret = CreateLocaleObject(env, javaLocaleName);
+        free((void *)javaLocaleName);
+        return ret;
     } else {
         return NULL;
     }
@@ -323,6 +325,7 @@
     const char * requested = env->GetStringUTFChars(localeString, &isCopy);
     if ((current != NULL) && (strcmp(current, requested) == 0)) {
         env->ReleaseStringUTFChars(localeString, requested);
+        free((void *)current);
         return JNI_TRUE;
     }
 
@@ -352,6 +355,7 @@
 
     env->ReleaseStringUTFChars(localeString, requested);
     free(hKLList);
+    free((void *)current);
     return retValue;
 
     CATCH_BAD_ALLOC_RET(JNI_FALSE);
@@ -480,6 +484,7 @@
         env->SetObjectArrayElement(locales,
                                    current,
                                    CreateLocaleObject(env, javaLocaleNames[current]));
+        free((void *)javaLocaleNames[current]);
     }
     DASSERT(!safe_ExceptionOccurred(env));
 
--- a/src/windows/native/sun/windows/awt_MenuItem.cpp	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/native/sun/windows/awt_MenuItem.cpp	Fri Sep 24 16:41:32 2010 -0700
@@ -794,6 +794,11 @@
     jobject jitem = GetTarget(env);
     jstring label  =
         (jstring)(env)->GetObjectField(jitem, AwtMenuItem::labelID);
+    if (label == NULL) {
+        env->DeleteLocalRef(label);
+        env->DeleteLocalRef(jitem);
+        return FALSE; //separator must has '-' as label.
+    }
     LPCWSTR labelW = JNU_GetStringPlatformChars(env, label, NULL);
     BOOL isSeparator = (labelW && (wcscmp(labelW, L"-") == 0));
     JNU_ReleaseStringPlatformChars(env, label, labelW);
--- a/src/windows/native/sun/windows/awt_TextComponent.h	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/native/sun/windows/awt_TextComponent.h	Fri Sep 24 16:41:32 2010 -0700
@@ -113,8 +113,6 @@
     // Used to prevent untrusted code from synthesizing a WM_PASTE message
     // by posting a <CTRL>-V KeyEvent
     BOOL    m_synthetic;
-    virtual void EditSetSel(CHARRANGE &cr) = 0;
-    virtual void EditGetSel(CHARRANGE &cr) = 0;
     virtual LONG EditGetCharFromPos(POINT& pt) = 0;
 
 private:
--- a/src/windows/native/sun/windows/awt_TextField.cpp	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/native/sun/windows/awt_TextField.cpp	Fri Sep 24 16:41:32 2010 -0700
@@ -41,7 +41,9 @@
  * AwtTextField methods
  */
 
-AwtTextField::AwtTextField() {
+AwtTextField::AwtTextField()
+    : m_initialRescrollFlag( true )
+{
 }
 
 /* Create a new AwtTextField object and window.   */
@@ -116,10 +118,6 @@
     SendMessage(EM_SETSEL, cr.cpMin, cr.cpMax);
 }
 
-void AwtTextField::EditGetSel(CHARRANGE &cr) {
-    SendMessage(EM_SETSEL, reinterpret_cast<WPARAM>(&cr.cpMin), reinterpret_cast<LPARAM>(&cr.cpMax));
-}
-
 LONG AwtTextField::EditGetCharFromPos(POINT& pt) {
     return static_cast<LONG>(SendMessage(EM_CHARFROMPOS, 0, MAKELPARAM(pt.x, pt.y)));
 }
@@ -153,11 +151,9 @@
      * The workaround also allows us to implement synthetic focus mechanism.
      */
     if (IsFocusingMouseMessage(msg)) {
-        CHARRANGE cr;
 
         LONG lCurPos = EditGetCharFromPos(msg->pt);
 
-        EditGetSel(cr);
         /*
          * NOTE: Plain EDIT control always clears selection on mouse
          * button press. We are clearing the current selection only if
@@ -174,6 +170,7 @@
             SetStartSelectionPos(lCurPos);
             SetEndSelectionPos(lCurPos);
         }
+        CHARRANGE cr;
         cr.cpMin = GetStartSelectionPos();
         cr.cpMax = GetEndSelectionPos();
         EditSetSel(cr);
@@ -310,6 +307,47 @@
     delete secs;
 }
 
+void AwtTextField::Reshape(int x, int y, int w, int h)
+{
+    AwtTextComponent::Reshape( x, y, w, h );
+
+    // Another option would be to call this
+    // after WM_SIZE notification is handled
+    initialRescroll();
+}
+
+
+// Windows' Edit control features:
+// (i) if text selection is set while control's width or height is 0,
+//   text is scrolled oddly.
+// (ii) if control's size is changed, text seems never be automatically
+//   rescrolled.
+//
+// This method is designed for the following scenario: AWT spawns Edit
+// control with 0x0 dimensions, then sets text selection, then resizes the
+// control (couple of times). This might cause text appear undesirably scrolled.
+// So we reset/set selection again to rescroll text. (see also CR 6480547)
+void AwtTextField::initialRescroll()
+{
+    if( ! m_initialRescrollFlag ) {
+        return;
+    }
+
+    ::RECT r;
+    BOOL ok = ::GetClientRect( GetHWnd(), &r );
+    if( ! ok || r.right==0 || r.bottom==0 ) {
+        return;
+    }
+
+    m_initialRescrollFlag = false;
+
+    DWORD start, end;
+    SendMessage( EM_GETSEL, (WPARAM)&start, (LPARAM)&end );
+    SendMessage( EM_SETSEL, (WPARAM)0, (LPARAM)0 );
+    SendMessage( EM_SETSEL, (WPARAM)start, (LPARAM)end );
+}
+
+
 /************************************************************************
  * WTextFieldPeer native methods
  */
--- a/src/windows/native/sun/windows/awt_TextField.h	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/native/sun/windows/awt_TextField.h	Fri Sep 24 16:41:32 2010 -0700
@@ -55,9 +55,14 @@
     static void _SetEchoChar(void *param);
 
   protected:
+    LONG EditGetCharFromPos(POINT& pt);
+    virtual void Reshape(int x, int y, int w, int h);
+
+private:
     void EditSetSel(CHARRANGE &cr);
-    void EditGetSel(CHARRANGE &cr);
-    LONG EditGetCharFromPos(POINT& pt);
+    void initialRescroll();
+
+    bool m_initialRescrollFlag;
 };
 
 #endif /* AWT_TEXTFIELD_H */
--- a/src/windows/native/sun/windows/awt_Window.h	Thu Sep 23 17:33:40 2010 -0700
+++ b/src/windows/native/sun/windows/awt_Window.h	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2010, Oracle and/or its affiliates. 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
@@ -193,12 +193,17 @@
 
     // Execute on Toolkit only.
     INLINE static LRESULT SynthesizeWmActivate(BOOL doActivate, HWND targetHWnd, HWND oppositeHWnd) {
-        if (::IsWindowVisible(targetHWnd)) {
-            return ::SendMessage(targetHWnd, WM_ACTIVATE,
-                                 MAKEWPARAM(doActivate ? WA_ACTIVE : WA_INACTIVE, FALSE),
-                                 (LPARAM) oppositeHWnd);
+        if (doActivate &&
+            (!::IsWindowVisible(targetHWnd) || ::IsIconic(::GetAncestor(targetHWnd, GA_ROOT))))
+        {
+            // The activation is rejected if either:
+            // - The toplevel is not visible
+            // - The toplevel (or its embedder) is minimised
+            return 1;
         }
-        return 1; // if not processed
+        return ::SendMessage(targetHWnd, WM_ACTIVATE,
+                             MAKEWPARAM(doActivate ? WA_ACTIVE : WA_INACTIVE, FALSE),
+                             (LPARAM) oppositeHWnd);
     }
 
     void moveToDefaultLocation(); /* moves Window to X,Y specified by Window Manger */
--- a/test/ProblemList.txt	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/ProblemList.txt	Fri Sep 24 16:41:32 2010 -0700
@@ -201,9 +201,6 @@
 # Windows X64, RuntimeException: MyThread expected to have RUNNABLE but got WAITING
 java/lang/Thread/ThreadStateTest.java				generic-all
 
-# Timeout on windows 64bit 
-java/lang/ClassLoader/deadlock/TestCrossDelegate.sh		generic-all
-
 ############################################################################
 
 # jdk_management
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/oracle/net/Sanity.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.oracle.net.Sdp;
+
+import java.net.*;
+import java.io.*;
+import java.nio.channels.*;
+import java.util.*;
+
+/**
+ * Exercise com.oracle.net.Sdp with each IP address plumbed to InfiniBand
+ * interfaces listed in a given file.
+ */
+
+public class Sanity {
+    public static void main(String[] args) throws Exception {
+        // The file is a list of interfaces to test.
+        Scanner s = new Scanner(new File(args[0]));
+        try {
+            while (s.hasNextLine()) {
+                String link = s.nextLine();
+                NetworkInterface ni = NetworkInterface.getByName(link);
+                if (ni != null) {
+                    Enumeration<InetAddress> addrs = ni.getInetAddresses();
+                    while (addrs.hasMoreElements()) {
+                        InetAddress addr = addrs.nextElement();
+                        System.out.format("Testing %s: %s\n", link, addr.getHostAddress());
+                        test(addr);
+                    }
+                }
+            }
+        } finally {
+            s.close();
+        }
+    }
+
+    static void test(InetAddress addr) throws Exception {
+        // Test SocketChannel and ServerSocketChannel
+        ServerSocketChannel ssc = Sdp.openServerSocketChannel();
+        try {
+            ssc.socket().bind(new InetSocketAddress(addr, 0));
+            int port = ssc.socket().getLocalPort();
+
+            // SocketChannel.connect (implicit bind)
+            SocketChannel client = Sdp.openSocketChannel();
+            try {
+                client.connect(new InetSocketAddress(addr, port));
+                SocketChannel peer = ssc.accept();
+                try {
+                    testConnection(Channels.newOutputStream(client),
+                                   Channels.newInputStream(peer));
+                } finally {
+                    peer.close();
+                }
+            } finally {
+                client.close();
+            }
+
+            // SocketChannel.connect (explicit bind)
+            client = Sdp.openSocketChannel();
+            try {
+                client.socket().bind(new InetSocketAddress(addr, 0));
+                client.connect(new InetSocketAddress(addr, port));
+                ssc.accept().close();
+            } finally {
+                client.close();
+            }
+        } finally {
+            ssc.close();
+        }
+
+        // Test Socket and ServerSocket
+        ServerSocket ss = Sdp.openServerSocket();
+        try {
+            ss.bind(new InetSocketAddress(addr, 0));
+            int port = ss.getLocalPort();
+
+            // Socket.connect (implicit bind)
+            Socket s = Sdp.openSocket();
+            try {
+                s.connect(new InetSocketAddress(addr, port));
+                Socket peer = ss.accept();
+                try {
+                    testConnection(s.getOutputStream(), peer.getInputStream());
+                } finally {
+                    peer.close();
+                }
+            } finally {
+                s.close();
+            }
+
+            // Socket.connect (explicit bind)
+            s = Sdp.openSocket();
+            try {
+                s.bind(new InetSocketAddress(addr, 0));
+                s.connect(new InetSocketAddress(addr, port));
+                ss.accept().close();
+            } finally {
+                s.close();
+            }
+        } finally {
+            ss.close();
+        }
+    }
+
+    static void testConnection(OutputStream out, InputStream in)
+        throws IOException
+    {
+        byte[] msg = "hello".getBytes();
+        out.write(msg);
+
+        byte[] ba = new byte[100];
+        int nread = 0;
+        while (nread < msg.length) {
+            int n = in.read(ba);
+            if (n < 0)
+                throw new IOException("EOF not expected!");
+            nread += n;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/oracle/net/sanity.sh	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,66 @@
+#
+# Copyright (c) 2010, Oracle and/or its affiliates. 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.
+#
+# 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+# @test
+# @bug 6965072
+# @summary Unit test for SDP support
+# @build  Sanity
+# @run shell sanity.sh
+
+IB_LINKS=ib.links
+
+OS=`uname -s`
+case "$OS" in
+    SunOS )
+        /usr/sbin/dladm show-part -o LINK -p > ${IB_LINKS}
+        if [ $? != 0 ]; then
+            echo "Unable to get InfiniBand parition link information"
+            exit 0
+        fi
+        ;;
+    Linux )
+        if [ ! -f /proc/net/sdp ]; then
+            echo "InfiniBand SDP module not installed"
+            exit 0
+        fi
+        egrep "^[ \t]+ib" /proc/net/dev|cut -d':' -f1|tr -d '\t ' > ${IB_LINKS}
+        ;; 
+    * )
+        echo "This test only runs on Solaris or Linux"
+        exit 0
+        ;;
+esac
+
+if [ -z "$TESTJAVA" ]; then
+    JAVA=java
+    TESTCLASSES=.
+    TESTSRC=.
+else
+    JAVA="${TESTJAVA}/bin/java"
+fi
+
+CLASSPATH=${TESTCLASSES}:${TESTSRC}
+export CLASSPATH
+
+# Run sanity test (IPv4-only for now)
+$JAVA -Djava.net.preferIPv4Stack=true Sanity ${IB_LINKS}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/security/sasl/ntlm/NTLMTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,416 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 6911951
+ * @summary NTLM should be a supported Java SASL mechanism
+ */
+import java.io.IOException;
+import javax.security.sasl.*;
+import javax.security.auth.callback.*;
+import java.util.*;
+
+import com.sun.security.ntlm.NTLMException;
+
+public class NTLMTest {
+
+    private static final String MECH = "NTLM";
+    private static final String REALM = "REALM";
+    private static final String PROTOCOL = "jmx";
+    private static final byte[] EMPTY = new byte[0];
+
+    private static final String USER1 = "dummy";
+    private static final char[] PASS1 = "bogus".toCharArray();
+    private static final String USER2 = "foo";
+    private static final char[] PASS2 = "bar".toCharArray();
+
+    private static final Map<String,char[]> maps =
+            new HashMap<String,char[]>();
+    static {
+        maps.put(USER1, PASS1);
+        maps.put(USER2, PASS2);
+    }
+
+    static char[] getPass(String d, String u) {
+        if (!d.equals(REALM)) return null;
+        return maps.get(u);
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        checkAuthOnly();
+        checkClientNameOverride();
+        checkServerDomainOverride();
+        checkClientDomainOverride();
+        checkVersions();
+        checkClientHostname();
+    }
+
+    static void checkVersions() throws Exception {
+        // Server accepts all version
+        checkVersion(null, null);
+        checkVersion("LM/NTLM", null);
+        checkVersion("LM", null);
+        checkVersion("NTLM", null);
+        checkVersion("NTLM2", null);
+        checkVersion("LMv2/NTLMv2", null);
+        checkVersion("LMv2", null);
+        checkVersion("NTLMv2", null);
+
+        // Client's default version is LMv2
+        checkVersion(null, "LMv2");
+
+        // Also works if they specified identical versions
+        checkVersion("LM/NTLM", "LM");
+        checkVersion("LM", "LM");
+        checkVersion("NTLM", "LM");
+        checkVersion("NTLM2", "NTLM2");
+        checkVersion("LMv2/NTLMv2", "LMv2");
+        checkVersion("LMv2", "LMv2");
+        checkVersion("NTLMv2", "LMv2");
+
+        // But should not work if different
+        try {
+            checkVersion("LM/NTLM", "LMv2");
+            throw new Exception("Should not succeed");
+        } catch (SaslException se) {
+            NTLMException ne = (NTLMException)se.getCause();
+            if (ne.errorCode() != NTLMException.AUTH_FAILED) {
+                throw new Exception("Failed false");
+            }
+        }
+        try {
+            checkVersion("LMv2/NTLMv2", "LM");
+            throw new Exception("Should not succeed");
+        } catch (SaslException se) {
+            NTLMException ne = (NTLMException)se.getCause();
+            if (ne.errorCode() != NTLMException.AUTH_FAILED) {
+                throw new Exception("Failed false");
+            }
+        }
+
+    }
+
+    /**
+     * A test on version matching
+     * @param vc ntlm version specified for client
+     * @param vs ntlm version specified for server
+     * @throws Exception
+     */
+    private static void checkVersion(String vc, String vs) throws Exception {
+        Map<String,Object> pc = new HashMap<>();
+        pc.put("com.sun.security.sasl.ntlm.version", vc);
+        Map<String,Object> ps = new HashMap<>();
+        ps.put("com.sun.security.sasl.ntlm.version", vs);
+        SaslClient clnt = Sasl.createSaslClient(
+                new String[]{MECH}, USER1, PROTOCOL, null, pc,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                NameCallback ncb = (NameCallback)cb;
+                                ncb.setName(ncb.getDefaultName());
+                            } else if (cb instanceof PasswordCallback) {
+                                ((PasswordCallback)cb).setPassword(PASS1);
+                            }
+                        }
+                    }
+                });
+
+        SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, REALM, ps,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        String domain = null, name = null;
+                        PasswordCallback pcb = null;
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                name = ((NameCallback)cb).getDefaultName();
+                            } else if (cb instanceof RealmCallback) {
+                                domain = ((RealmCallback)cb).getDefaultText();
+                            } else if (cb instanceof PasswordCallback) {
+                                pcb = (PasswordCallback)cb;
+                            }
+                        }
+                        if (pcb != null) {
+                            pcb.setPassword(getPass(domain, name));
+                        }
+                    }
+                });
+
+        handshake(clnt, srv);
+    }
+
+    private static void checkClientHostname() throws Exception {
+        Map<String,Object> pc = new HashMap<>();
+        pc.put("com.sun.security.sasl.ntlm.hostname", "this.is.com");
+        SaslClient clnt = Sasl.createSaslClient(
+                new String[]{MECH}, USER1, PROTOCOL, null, pc,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                NameCallback ncb = (NameCallback)cb;
+                                ncb.setName(ncb.getDefaultName());
+                            } else if (cb instanceof PasswordCallback) {
+                                ((PasswordCallback)cb).setPassword(PASS1);
+                            }
+                        }
+                    }
+                });
+
+        SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, REALM, null,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        String domain = null, name = null;
+                        PasswordCallback pcb = null;
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                name = ((NameCallback)cb).getDefaultName();
+                            } else if (cb instanceof RealmCallback) {
+                                domain = ((RealmCallback)cb).getDefaultText();
+                            } else if (cb instanceof PasswordCallback) {
+                                pcb = (PasswordCallback)cb;
+                            }
+                        }
+                        if (pcb != null) {
+                            pcb.setPassword(getPass(domain, name));
+                        }
+                    }
+                });
+
+        handshake(clnt, srv);
+        if (!"this.is.com".equals(
+                srv.getNegotiatedProperty("com.sun.security.sasl.ntlm.hostname"))) {
+            throw new Exception("Hostname not trasmitted to server");
+        }
+    }
+
+    /**
+     * Client realm override, but finally overridden by server response
+     */
+    private static void checkClientDomainOverride() throws Exception {
+        SaslClient clnt = Sasl.createSaslClient(
+                new String[]{MECH}, USER1, PROTOCOL, "ANOTHERREALM", null,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                NameCallback ncb = (NameCallback)cb;
+                                ncb.setName(ncb.getDefaultName());
+                            } else if(cb instanceof RealmCallback) {
+                                RealmCallback dcb = (RealmCallback)cb;
+                                dcb.setText("THIRDDOMAIN");
+                            } else if (cb instanceof PasswordCallback) {
+                                ((PasswordCallback)cb).setPassword(PASS1);
+                            }
+                        }
+                    }
+                });
+
+        SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, REALM, null,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        String domain = null, name = null;
+                        PasswordCallback pcb = null;
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                name = ((NameCallback)cb).getDefaultName();
+                            } else if (cb instanceof RealmCallback) {
+                                domain = ((RealmCallback)cb).getDefaultText();
+                            } else if (cb instanceof PasswordCallback) {
+                                pcb = (PasswordCallback)cb;
+                            }
+                        }
+                        if (pcb != null) {
+                            pcb.setPassword(getPass(domain, name));
+                        }
+                    }
+                });
+
+        handshake(clnt, srv);
+    }
+
+    /**
+     * Client side user name provided in callback.
+     * @throws Exception
+     */
+    private static void checkClientNameOverride() throws Exception {
+        SaslClient clnt = Sasl.createSaslClient(
+                new String[]{MECH}, null, PROTOCOL, null, null,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                NameCallback ncb = (NameCallback)cb;
+                                ncb.setName(USER1);
+                            } else if (cb instanceof PasswordCallback) {
+                                ((PasswordCallback)cb).setPassword(PASS1);
+                            }
+                        }
+                    }
+                });
+
+        SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, REALM, null,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        String domain = null, name = null;
+                        PasswordCallback pcb = null;
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                name = ((NameCallback)cb).getDefaultName();
+                            } else if (cb instanceof RealmCallback) {
+                                domain = ((RealmCallback)cb).getDefaultText();
+                            } else if (cb instanceof PasswordCallback) {
+                                pcb = (PasswordCallback)cb;
+                            }
+                        }
+                        if (pcb != null) {
+                            pcb.setPassword(getPass(domain, name));
+                        }
+                    }
+                });
+
+        handshake(clnt, srv);
+    }
+
+    /**
+     * server side domain provided in props.
+     * @throws Exception
+     */
+    private static void checkServerDomainOverride() throws Exception {
+        SaslClient clnt = Sasl.createSaslClient(
+                new String[]{MECH}, USER1, PROTOCOL, null, null,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                NameCallback ncb = (NameCallback)cb;
+                                ncb.setName(ncb.getDefaultName());
+                            } else if (cb instanceof PasswordCallback) {
+                                ((PasswordCallback)cb).setPassword(PASS1);
+                            }
+                        }
+                    }
+                });
+
+        Map<String,Object> ps = new HashMap<>();
+        ps.put("com.sun.security.sasl.ntlm.domain", REALM);
+        SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, null, ps,
+                new CallbackHandler() {
+                    public void handle(Callback[] callbacks)
+                            throws IOException, UnsupportedCallbackException {
+                        String domain = null, name = null;
+                        PasswordCallback pcb = null;
+                        for (Callback cb: callbacks) {
+                            if (cb instanceof NameCallback) {
+                                name = ((NameCallback)cb).getDefaultName();
+                            } else if (cb instanceof RealmCallback) {
+                                domain = ((RealmCallback)cb).getDefaultText();
+                            } else if (cb instanceof PasswordCallback) {
+                                pcb = (PasswordCallback)cb;
+                            }
+                        }
+                        if (pcb != null) {
+                            pcb.setPassword(getPass(domain, name));
+                        }
+                    }
+                });
+
+        handshake(clnt, srv);
+    }
+
+    private static void checkAuthOnly() throws Exception {
+        Map<String,Object> props = new HashMap<>();
+        props.put(Sasl.QOP, "auth-conf");
+        try {
+            Sasl.createSaslClient(
+                    new String[]{MECH}, USER2, PROTOCOL, REALM, props, null);
+            throw new Exception("NTLM should not support auth-conf");
+        } catch (SaslException se) {
+            // Normal
+        }
+    }
+
+    private static void handshake(SaslClient clnt, SaslServer srv)
+            throws Exception {
+        if (clnt == null) {
+            throw new IllegalStateException(
+                    "Unable to find client impl for " + MECH);
+        }
+        if (srv == null) {
+            throw new IllegalStateException(
+                    "Unable to find server impl for " + MECH);
+        }
+
+        byte[] response = (clnt.hasInitialResponse()
+                ? clnt.evaluateChallenge(EMPTY) : EMPTY);
+        System.out.println("Initial:");
+        new sun.misc.HexDumpEncoder().encodeBuffer(response, System.out);
+        byte[] challenge;
+
+        while (!clnt.isComplete() || !srv.isComplete()) {
+            challenge = srv.evaluateResponse(response);
+            response = null;
+            if (challenge != null) {
+                System.out.println("Challenge:");
+                new sun.misc.HexDumpEncoder().encodeBuffer(challenge, System.out);
+                response = clnt.evaluateChallenge(challenge);
+            }
+            if (response != null) {
+                System.out.println("Response:");
+                new sun.misc.HexDumpEncoder().encodeBuffer(response, System.out);
+            }
+        }
+
+        if (clnt.isComplete() && srv.isComplete()) {
+            System.out.println("SUCCESS");
+            if (!srv.getAuthorizationID().equals(USER1)) {
+                throw new Exception("Not correct user");
+            }
+        } else {
+            throw new IllegalStateException(
+                    "FAILURE: mismatched state:"
+                    + " client complete? " + clnt.isComplete()
+                    + " server complete? " + srv.isComplete());
+        }
+
+        if (!clnt.getNegotiatedProperty(Sasl.QOP).equals("auth") ||
+                !srv.getNegotiatedProperty(Sasl.QOP).equals("auth") ||
+                !clnt.getNegotiatedProperty(
+                    "com.sun.security.sasl.ntlm.domain").equals(REALM)) {
+            throw new Exception("Negotiated property error");
+        }
+        clnt.dispose();
+        srv.dispose();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/EventQueue/SecondaryLoopTest/SecondaryLoopTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+  @test
+  @bug 6949936
+  @author Artem Ananiev: area=eventqueue
+  @run main/timeout=30 SecondaryLoopTest
+*/
+
+import java.awt.*;
+
+/**
+ * Unit test for java.awt.SecondaryLoop implementation
+ */
+public class SecondaryLoopTest {
+
+    private static volatile boolean loopStarted;
+    private static volatile boolean doubleEntered;
+    private static volatile boolean loopActive;
+    private static volatile boolean eventDispatched;
+
+    public static void main(String[] args) throws Exception {
+        test(true, true);
+        test(true, false);
+        test(false, true);
+        test(false, false);
+    }
+
+    private static void test(final boolean enterEDT, final boolean exitEDT) throws Exception {
+        System.out.println("Running test(" + enterEDT + ", " + exitEDT + ")");
+        System.err.flush();
+        loopStarted = true;
+        Runnable enterRun = new Runnable() {
+            @Override
+            public void run() {
+                Toolkit tk = Toolkit.getDefaultToolkit();
+                EventQueue eq = tk.getSystemEventQueue();
+                final SecondaryLoop loop = eq.createSecondaryLoop();
+                doubleEntered = false;
+                eventDispatched = false;
+                Runnable eventRun = new Runnable() {
+                    @Override
+                    public void run() {
+                        // Let the loop enter
+                        sleep(1000);
+                        if (loop.enter()) {
+                            doubleEntered = true;
+                        }
+                        eventDispatched = true;
+                    }
+                };
+                EventQueue.invokeLater(eventRun);
+                Runnable exitRun = new Runnable() {
+                    @Override
+                    public void run() {
+                        // Let the loop enter and eventRun finish
+                        sleep(2000);
+                        if (doubleEntered) {
+                            // Hopefully, we get here if the loop is entered twice
+                            loop.exit();
+                        }
+                        loop.exit();
+                    }
+                };
+                if (exitEDT) {
+                    EventQueue.invokeLater(exitRun);
+                } else {
+                    new Thread(exitRun).start();
+                }
+                if (!loop.enter()) {
+                    loopStarted = false;
+                }
+                loopActive = eventDispatched;
+            }
+        };
+        if (enterEDT) {
+            EventQueue.invokeAndWait(enterRun);
+        } else {
+            enterRun.run();
+        }
+        // Print all the flags before we fail with exception
+        System.out.println("    loopStarted = " + loopStarted);
+        System.out.println("    doubleEntered = " + doubleEntered);
+        System.out.println("    loopActive = " + loopActive);
+        System.out.flush();
+        if (!loopStarted) {
+            throw new RuntimeException("Test FAILED: the secondary loop is not started");
+        }
+        if (doubleEntered) {
+            throw new RuntimeException("Test FAILED: the secondary loop is started twice");
+        }
+        if (!loopActive) {
+            throw new RuntimeException("Test FAILED: the secondary loop exited immediately");
+        }
+    }
+
+    private static void sleep(long t) {
+        try {
+            Thread.sleep(t);
+        } catch (InterruptedException e) {
+            e.printStackTrace(System.err);
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Menu/NullMenuLabelTest/NullMenuLabelTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,26 @@
+/*      @test 1.5 98/07/23
+        @bug 4064202 4253466
+        @summary Test for Win32 NPE when MenuItem with null label added.
+        @author fred.ecks
+        @run main/othervm NullMenuLabelTest
+*/
+
+import java.awt.*;
+
+public class NullMenuLabelTest {
+
+    public static void main(String[] args) {
+        Frame frame = new Frame("Test Frame");
+        frame.pack();
+        frame.setVisible(true);
+        MenuBar menuBar = new MenuBar();
+        frame.setMenuBar(menuBar);
+        Menu menu = new Menu(null);
+        menuBar.add(menu);
+        menu.add(new MenuItem(null));
+        // If we got this far, the test succeeded
+        frame.setVisible(false);
+        frame.dispose();
+    }
+
+} // class NullMenuLabelTest
--- a/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/awt/TextField/ScrollSelectionTest/ScrollSelectionTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -53,13 +53,14 @@
       frame.add(tf);
       tf.select(0, 20);
 
-      String[] instructions =
-       {
+      String[] instructions = {
           "INSTRUCTIONS:",
           "This is a test for a win32 specific problem",
-          "If you see all the letters from 'a' to 'z' and",
-          "letters from 'a' to 't' are selected then test passes"
-       };
+         "If you see all the letters from 'a' to 'z' and",
+          "letters from 'a' to 't' are selected then test passes.",
+          "You may have to activate the frame to see the selection"
+          + " highlighted (e.g. by clicking on frame's title)."
+      };
       Sysout.createDialogWithInstructions( instructions );
 
     }// init()
--- a/test/java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_3.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_3.java	Fri Sep 24 16:41:32 2010 -0700
@@ -114,6 +114,7 @@
         checkEvents(frameAdapter, 1, 1);
         checkEvents(buttonAdapter, 0, 0);
         w.setVisible(false);
+        Util.waitForIdle(r);
     }
 
     public static void main(String []s)
--- a/test/java/lang/ClassLoader/deadlock/TestCrossDelegate.sh	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/lang/ClassLoader/deadlock/TestCrossDelegate.sh	Fri Sep 24 16:41:32 2010 -0700
@@ -25,7 +25,7 @@
 # @summary (cl) ClassLoader.loadClass locks all instances in chain 
 #          when delegating
 # 
-# @run shell/timeout=10 TestCrossDelegate.sh
+# @run shell/timeout=300 TestCrossDelegate.sh
 
 # if running by hand on windows, change TESTSRC and TESTCLASSES to "."
 if [ "${TESTSRC}" = "" ] ; then
@@ -41,10 +41,6 @@
     echo "FAILED!!!"
     exit 1
 fi
-echo TESTSRC=${TESTSRC}
-echo TESTCLASSES=${TESTCLASSES}
-echo TESTJAVA=${TESTJAVA}
-echo ""
 
 # set platform-specific variables
 OS=`uname -s`
@@ -55,11 +51,20 @@
   Linux )
     FS="/"
     ;;
-  Windows* | CYGWIN* )
+  Windows*)
     FS="\\"
     ;;
+  CYGWIN* )
+    FS="\\"
+    TESTCLASSES=`/usr/bin/cygpath -a -s -m ${TESTCLASSES}`
+    ;;
 esac
 
+echo TESTSRC=${TESTSRC}
+echo TESTCLASSES=${TESTCLASSES}
+echo TESTJAVA=${TESTJAVA}
+echo ""
+
 # compile test
 ${TESTJAVA}${FS}bin${FS}javac \
         -d ${TESTCLASSES} \
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/ProcessBuilder/SecurityManagerClinit.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2010 Google 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 6980747
+ * @summary Check that Process-related classes have the proper
+ *     doPrivileged blocks, and can be initialized with an adversarial
+ *     security manager.
+ * @run main/othervm SecurityManagerClinit
+ * @author Martin Buchholz
+ */
+
+import java.io.*;
+import java.security.*;
+
+public class SecurityManagerClinit {
+    private static class Policy extends java.security.Policy {
+        private Permissions perms;
+
+        public Policy(Permission... permissions) {
+            perms = new Permissions();
+            for (Permission permission : permissions)
+                perms.add(permission);
+        }
+
+        public boolean implies(ProtectionDomain pd, Permission p) {
+            return perms.implies(p);
+        }
+    }
+
+    public static void main(String[] args) throws Throwable {
+        String javaExe =
+            System.getProperty("java.home") +
+            File.separator + "bin" + File.separator + "java";
+
+        // A funky contrived security setup, just for bug repro purposes.
+        java.security.Security.setProperty("package.access", "java.util");
+
+        final Policy policy =
+            new Policy
+            (new FilePermission("<<ALL FILES>>", "execute"),
+             new RuntimePermission("setSecurityManager"));
+        Policy.setPolicy(policy);
+
+        System.setSecurityManager(new SecurityManager());
+
+        try {
+            String[] cmd = { javaExe, "-version" };
+            Process p = Runtime.getRuntime().exec(cmd);
+            p.getOutputStream().close();
+            p.getInputStream().close();
+            p.getErrorStream().close();
+            p.waitFor();
+        } finally {
+            System.setSecurityManager(null);
+        }
+    }
+}
--- a/test/java/nio/channels/FileChannel/Transfer.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/nio/channels/FileChannel/Transfer.java	Fri Sep 24 16:41:32 2010 -0700
@@ -23,6 +23,7 @@
 
 /* @test
  * @bug 4434723 4482726 4559072 4638365 4795550 5081340 5103988 6253145
+ *   6984545
  * @summary Test FileChannel.transferFrom and transferTo
  * @library ..
  */
@@ -55,6 +56,7 @@
         xferTest06(); // for bug 5081340
         xferTest07(); // for bug 5103988
         xferTest08(); // for bug 6253145
+        xferTest09(); // for bug 6984545
     }
 
     private static void testFileChannel() throws Exception {
@@ -505,6 +507,27 @@
         }
     }
 
+    // Test that transferFrom with FileChannel source that is not readable
+    // throws NonReadableChannelException
+    static void xferTest09() throws Exception {
+        File source = File.createTempFile("source", null);
+        source.deleteOnExit();
+
+        File target = File.createTempFile("target", null);
+        target.deleteOnExit();
+
+        FileChannel fc1 = new FileOutputStream(source).getChannel();
+        FileChannel fc2 = new RandomAccessFile(target, "rw").getChannel();
+        try {
+            fc2.transferFrom(fc1, 0L, 0);
+            throw new RuntimeException("NonReadableChannelException expected");
+        } catch (NonReadableChannelException expected) {
+        } finally {
+            fc1.close();
+            fc2.close();
+        }
+    }
+
     /**
      * Creates file blah of specified size in bytes.
      */
--- a/test/java/nio/channels/Selector/ConnectWrite.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/nio/channels/Selector/ConnectWrite.java	Fri Sep 24 16:41:32 2010 -0700
@@ -38,7 +38,6 @@
 
     public static void main(String[] args) throws Exception {
         test1(13);
-        test1(9);
     }
 
     public static void test1(int port) throws Exception {
--- a/test/java/nio/file/DirectoryStream/Basic.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/nio/file/DirectoryStream/Basic.java	Fri Sep 24 16:41:32 2010 -0700
@@ -104,20 +104,20 @@
             stream.close();
         }
 
-        // check that IOExceptions throws by filters are propagated
+        // check that an IOException thrown by a filter is propagated
         filter = new DirectoryStream.Filter<Path>() {
             public boolean accept(Path file) throws IOException {
-                throw new IOException();
+                throw new java.util.zip.ZipException();
             }
         };
         stream = dir.newDirectoryStream(filter);
         try {
             stream.iterator().hasNext();
-            throw new RuntimeException("ConcurrentModificationException expected");
-        } catch (ConcurrentModificationException x) {
-            Throwable t = x.getCause();
-            if (!(t instanceof IOException))
-                throw new RuntimeException("Cause is not IOException as expected");
+            throw new RuntimeException("DirectoryIteratorException expected");
+        } catch (DirectoryIteratorException x) {
+            IOException cause = x.getCause();
+            if (!(cause instanceof java.util.zip.ZipException))
+                throw new RuntimeException("Expected IOException not propagated");
         } finally {
             stream.close();
         }
@@ -142,58 +142,49 @@
         } catch (NotDirectoryException x) {
         }
 
-        // test iterator remove method
-        stream = dir.newDirectoryStream();
+        // test UnsupportedOperationException
+        stream =  dir.newDirectoryStream();
         Iterator<Path> i = stream.iterator();
-        while (i.hasNext()) {
-            Path entry = i.next();
-            if (!entry.getName().equals(foo))
-                throw new RuntimeException("entry not expected");
+        i.next();
+        try {
             i.remove();
+            throw new RuntimeException("UnsupportedOperationException expected");
+        } catch (UnsupportedOperationException uoe) {
         }
-        stream.close();
 
         // test IllegalStateException
-        dir.resolve(foo).createFile();
         stream =  dir.newDirectoryStream();
-        i = stream.iterator();
-        i.next();
+        stream.iterator();
         try {
+            // attempt to obtain second iterator
             stream.iterator();
             throw new RuntimeException("IllegalStateException not thrown as expected");
         } catch (IllegalStateException x) {
         }
         stream.close();
+
+        stream =  dir.newDirectoryStream();
+        stream.close();
         try {
+            // attempt to obtain iterator after stream is closed
             stream.iterator();
             throw new RuntimeException("IllegalStateException not thrown as expected");
         } catch (IllegalStateException x) {
         }
-        try {
-            i.hasNext();
-            throw new RuntimeException("ConcurrentModificationException not thrown as expected");
-        } catch (ConcurrentModificationException x) {
-            Throwable t = x.getCause();
-            if (!(t instanceof ClosedDirectoryStreamException))
-                throw new RuntimeException("Cause is not ClosedDirectoryStreamException as expected");
-        }
-        try {
+
+        // test that iterator reads to end of stream when closed
+        stream =  dir.newDirectoryStream();
+        i = stream.iterator();
+        stream.close();
+        while (i.hasNext())
             i.next();
-            throw new RuntimeException("ConcurrentModificationException not thrown as expected");
-        } catch (ConcurrentModificationException x) {
-            Throwable t = x.getCause();
-            if (!(t instanceof ClosedDirectoryStreamException))
-                throw new RuntimeException("Cause is not ClosedDirectoryStreamException as expected");
-        }
+
+        stream =  dir.newDirectoryStream();
+        i = stream.iterator();
+        stream.close();
         try {
-            i.remove();
-            throw new RuntimeException("ConcurrentModificationException not thrown as expected");
-        } catch (ConcurrentModificationException x) {
-            Throwable t = x.getCause();
-            if (!(t instanceof ClosedDirectoryStreamException))
-                throw new RuntimeException("Cause is not ClosedDirectoryStreamException as expected");
-        }
-
+            for (;;) i.next();
+        } catch (NoSuchElementException expected) { }
     }
 
     public static void main(String[] args) throws IOException {
--- a/test/java/nio/file/DirectoryStream/SecureDS.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/nio/file/DirectoryStream/SecureDS.java	Fri Sep 24 16:41:32 2010 -0700
@@ -166,22 +166,6 @@
         stream.deleteDirectory(dirEntry);
         stream.deleteFile(fileEntry);
 
-        // Test: remove
-        // (requires resetting environment to get new iterator)
-        stream.close();
-        dir2.moveTo(dir1);
-        dir1.resolve(fileEntry).createFile();
-        stream = (SecureDirectoryStream<Path>)dir1.newDirectoryStream();
-        dir1.moveTo(dir2);
-        Iterator<Path> iter = stream.iterator();
-        int removed = 0;
-        while (iter.hasNext()) {
-            iter.next();
-            iter.remove();
-            removed++;
-        }
-        assertTrue(removed == 1);
-
         // clean-up
         stream.close();
         dir2.delete();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/nio/file/etc/Exceptions.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 4313887 6881498
+ * @summary Miscellenous tests on exceptions in java.nio.file
+ */
+
+import java.nio.file.*;
+import java.io.*;
+import java.util.Objects;
+import java.lang.reflect.*;
+
+public class Exceptions {
+
+    public static void main(String[] args) throws Exception {
+        testFileSystemException();
+        testDirectoryIteratorException();
+    }
+
+    static void testFileSystemException() throws Exception {
+        String thisFile = "source";
+        String otherFile = "target";
+        String reason = "Access denied";
+
+        // getFile/getOtherFile
+        testFileSystemException(thisFile, otherFile, reason);
+        testFileSystemException(null, otherFile, reason);
+        testFileSystemException(thisFile, null, reason);
+        testFileSystemException(thisFile, otherFile, null);
+
+        // serialization
+        FileSystemException exc;
+        exc = new FileSystemException(thisFile, otherFile, reason);
+        exc = (FileSystemException)deserialize(serialize(exc));
+        if (!exc.getFile().equals(thisFile) || !exc.getOtherFile().equals(otherFile))
+            throw new RuntimeException("Exception not reconstituted completely");
+    }
+
+    static void testFileSystemException(String thisFile,
+                                        String otherFile,
+                                        String reason)
+    {
+        FileSystemException exc = new FileSystemException(thisFile, otherFile, reason);
+        if (!Objects.equals(thisFile, exc.getFile()))
+            throw new RuntimeException("getFile returned unexpected result");
+        if (!Objects.equals(otherFile, exc.getOtherFile()))
+            throw new RuntimeException("getOtherFile returned unexpected result");
+        if (!Objects.equals(reason, exc.getReason()))
+            throw new RuntimeException("getReason returned unexpected result");
+    }
+
+    static void testDirectoryIteratorException() throws Exception {
+        // NullPointerException
+        try {
+            new DirectoryIteratorException(null);
+            throw new RuntimeException("NullPointerException expected");
+        } catch (NullPointerException expected) { }
+
+        // serialization
+        DirectoryIteratorException exc;
+        exc = new DirectoryIteratorException(new IOException());
+        exc = (DirectoryIteratorException)deserialize(serialize(exc));
+        IOException ioe = exc.getCause();
+        if (ioe == null)
+            throw new RuntimeException("Cause should not be null");
+
+        // when deserializing then the cause should be an IOException
+        hackCause(exc, null);
+        try {
+            deserialize(serialize(exc));
+            throw new RuntimeException("InvalidObjectException expected");
+        } catch (InvalidObjectException expected) { }
+
+        hackCause(exc, new RuntimeException());
+        try {
+            deserialize(serialize(exc));
+            throw new RuntimeException("InvalidObjectException expected");
+        } catch (InvalidObjectException expected) { }
+    }
+
+
+    // Use reflection to set a Throwable's cause.
+    static void hackCause(Throwable t, Throwable cause)
+        throws NoSuchFieldException, IllegalAccessException
+    {
+        Field f = Throwable.class.getDeclaredField("cause");
+        f.setAccessible(true);
+        f.set(t, cause);
+    }
+
+    // Serialize the given object to a byte[]
+    static byte[] serialize(Object o) throws IOException {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(baos);
+        oos.writeObject(o);
+        oos.close();
+        return baos.toByteArray();
+    }
+
+    // Read an object from its serialized form
+    static Object deserialize(byte[] bytes)
+        throws IOException, ClassNotFoundException
+    {
+        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
+        ObjectInputStream ois = new ObjectInputStream(in);
+        Object result = ois.readObject();
+        ois.close();
+        return result;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/text/Format/DateFormat/ISO8601ZoneTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4919632
+ * @summary Unit test for ISO8601 time zone format support
+ */
+
+import java.text.*;
+import java.util.*;
+
+public class ISO8601ZoneTest {
+    static final Date TIMESTAMP = new Date(1283758039020L);
+
+    static final String[][] formatData = {
+        // time zone name, expected output at TIMESTAMP
+        { "America/Los_Angeles", "2010-09-06T00:27:19.020-07", },
+        { "America/Los_Angeles", "2010-09-06T00:27:19.020-0700", },
+        { "America/Los_Angeles", "2010-09-06T00:27:19.020-07:00", },
+        { "Australia/Sydney", "2010-09-06T17:27:19.020+10", },
+        { "Australia/Sydney", "2010-09-06T17:27:19.020+1000", },
+        { "Australia/Sydney", "2010-09-06T17:27:19.020+10:00", },
+        { "GMT-07:00", "2010-09-06T00:27:19.020-07", },
+        { "GMT-07:00", "2010-09-06T00:27:19.020-0700", },
+        { "GMT-07:00", "2010-09-06T00:27:19.020-07:00", },
+        { "UTC", "2010-09-06T07:27:19.020Z", },
+        { "UTC", "2010-09-06T07:27:19.020Z", },
+        { "UTC", "2010-09-06T07:27:19.020Z", },
+    };
+
+    static final String[] zones = {
+        "America/Los_Angeles", "Australia/Sydney", "GMT-07:00",
+        "UTC", "GMT+05:30", "GMT-01:23",
+    };
+
+    static final String[] isoZoneFormats = {
+        "yyyy-MM-dd'T'HH:mm:ss.SSSX",
+        "yyyy-MM-dd'T'HH:mm:ss.SSSXX",
+        "yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
+    };
+
+    static final String[][] badData = {
+        { "X", "1" },
+        { "X", "+1" },
+        { "X", "-2" },
+        { "X", "-24" },
+        { "X", "+24" },
+
+        { "XX", "9" },
+        { "XX", "23" },
+        { "XX", "234" },
+        { "XX", "3456" },
+        { "XX", "23456" },
+        { "XX", "+1" },
+        { "XX", "-12" },
+        { "XX", "+123" },
+        { "XX", "-12:34" },
+        { "XX", "+12:34" },
+        { "XX", "-2423" },
+        { "XX", "+2423" },
+        { "XX", "-1260" },
+        { "XX", "+1260" },
+
+        { "XXX", "9" },
+        { "XXX", "23" },
+        { "XXX", "234" },
+        { "XXX", "3456" },
+        { "XXX", "23456" },
+        { "XXX", "2:34" },
+        { "XXX", "12:4" },
+        { "XXX", "12:34" },
+        { "XXX", "-1" },
+        { "XXX", "+1" },
+        { "XXX", "-12" },
+        { "XXX", "+12" },
+        { "XXX", "-123" },
+        { "XXX", "+123" },
+        { "XXX", "-1234" },
+        { "XXX", "+1234" },
+        { "XXX", "+24:23" },
+        { "XXX", "+12:60" },
+        { "XXX", "+1:23" },
+        { "XXX", "+12:3" },
+    };
+
+    static String[] badFormats = {
+        "XXXX", "XXXXX", "XXXXXX",
+    };
+
+    public static void main(String[] args) throws Exception {
+        TimeZone tz = TimeZone.getDefault();
+
+        try {
+            for (int i = 0; i < formatData.length; i++) {
+                TimeZone.setDefault(TimeZone.getTimeZone(formatData[i][0]));
+                formatTest(isoZoneFormats[i % isoZoneFormats.length],
+                           formatData[i][1]);
+            }
+
+            for (String zone : zones) {
+                TimeZone.setDefault(TimeZone.getTimeZone(zone));
+                for (String fmt : isoZoneFormats) {
+                    roundtripTest(fmt);
+                    SimpleDateFormat f = new SimpleDateFormat(fmt);
+                }
+
+            }
+
+            for (String[] d : badData) {
+                badDataParsing(d[0], d[1]);
+            }
+
+            for (String fmt : badFormats) {
+                badFormat(fmt);
+            }
+        } finally {
+            TimeZone.setDefault(tz);
+        }
+
+    }
+
+    static void formatTest(String fmt, String expected) throws Exception {
+        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
+        String s = sdf.format(TIMESTAMP);
+        if (!expected.equals(s)) {
+            throw new RuntimeException("formatTest: got " + s
+                                       + ", expected " + expected);
+        }
+
+        Date d = sdf.parse(s);
+        if (d.getTime() != TIMESTAMP.getTime()) {
+            throw new RuntimeException("formatTest: parse(" + s
+                                       + "), got " + d.getTime()
+                                       + ", expected " + TIMESTAMP.getTime());
+        }
+
+        ParsePosition pos = new ParsePosition(0);
+        d = sdf.parse(s + "123", pos);
+        if (d.getTime() != TIMESTAMP.getTime()) {
+            throw new RuntimeException("formatTest: parse(" + s
+                                       + "), got " + d.getTime()
+                                       + ", expected " + TIMESTAMP.getTime());
+        }
+        if (pos.getIndex() != s.length()) {
+            throw new RuntimeException("formatTest: wrong resulting parse position: "
+                                       + pos.getIndex() + ", expected " + s.length());
+        }
+    }
+
+    static void roundtripTest(String fmt) throws Exception {
+        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
+        Date date = new Date();
+
+        int fractionalHour = sdf.getTimeZone().getOffset(date.getTime());
+        fractionalHour %= 3600000; // fraction of hour
+
+        String s = sdf.format(date);
+        Date pd = sdf.parse(s);
+        long diffsInMillis = pd.getTime() - date.getTime();
+        if (diffsInMillis != 0) {
+            if (diffsInMillis != fractionalHour) {
+                throw new RuntimeException("fmt= " + fmt
+                                           + ", diff="+diffsInMillis
+                                           + ", fraction=" + fractionalHour);
+            }
+        }
+    }
+
+
+    static void badDataParsing(String fmt, String text) {
+        try {
+            SimpleDateFormat sdf = new SimpleDateFormat(fmt);
+            sdf.parse(text);
+            throw new RuntimeException("didn't throw an exception: fmt=" + fmt
+                                       + ", text=" + text);
+        } catch (ParseException e) {
+            // OK
+        }
+    }
+
+    static void badFormat(String fmt) {
+        try {
+            SimpleDateFormat sdf = new SimpleDateFormat(fmt);
+            throw new RuntimeException("Constructor didn't throw an exception: fmt=" + fmt);
+        } catch (IllegalArgumentException e) {
+            // OK
+        }
+        try {
+            SimpleDateFormat sdf = new SimpleDateFormat();
+            sdf.applyPattern(fmt);
+            throw new RuntimeException("applyPattern didn't throw an exception: fmt=" + fmt);
+        } catch (IllegalArgumentException e) {
+            // OK
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/text/Format/DateFormat/WeekDateTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4267450
+ * @summary Unit test for week date support
+ */
+
+import java.text.*;
+import java.util.*;
+import static java.util.GregorianCalendar.*;
+
+public class WeekDateTest {
+    static SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");
+    static SimpleDateFormat ywdFormat = new SimpleDateFormat("YYYY-'W'ww-u");
+    static {
+        ymdFormat.setCalendar(newCalendar());
+        ywdFormat.setCalendar(newCalendar());
+    }
+
+    // Round-trip Data
+    static final String[][] roundTripData = {
+        { "2005-01-01", "2004-W53-6" },
+        { "2005-01-02", "2004-W53-7" },
+        { "2005-12-31", "2005-W52-6" },
+        { "2007-01-01", "2007-W01-1" },
+        { "2007-12-30", "2007-W52-7" },
+        { "2007-12-31", "2008-W01-1" },
+        { "2008-01-01", "2008-W01-2" },
+        { "2008-12-29", "2009-W01-1" },
+        { "2008-12-31", "2009-W01-3" },
+        { "2009-01-01", "2009-W01-4" },
+        { "2009-12-31", "2009-W53-4" },
+        { "2010-01-03", "2009-W53-7" },
+        { "2009-12-31", "2009-W53-4" },
+        { "2010-01-01", "2009-W53-5" },
+        { "2010-01-02", "2009-W53-6" },
+        { "2010-01-03", "2009-W53-7" },
+        { "2008-12-28", "2008-W52-7" },
+        { "2008-12-29", "2009-W01-1" },
+        { "2008-12-30", "2009-W01-2" },
+        { "2008-12-31", "2009-W01-3" },
+        { "2009-01-01", "2009-W01-4" },
+        { "2009-01-01", "2009-W01-4" },
+    };
+
+    // Data for leniency test
+    static final String[][] leniencyData = {
+        { "2008-12-28", "2009-W01-0" },
+        { "2010-01-04", "2009-W53-8" },
+        { "2008-12-29", "2008-W53-1" },
+    };
+
+    static final String[] invalidData = {
+        "2010-W00-1",
+        "2010-W55-1",
+        "2010-W03-0",
+        "2010-W04-8",
+        "2010-W04-19"
+    };
+
+    public static void main(String[] args) throws Exception {
+        formatTest(roundTripData);
+        parseTest(roundTripData);
+        parseTest(leniencyData);
+        nonLenientTest(invalidData);
+        noWeekDateSupport();
+    }
+
+    private static void formatTest(String[][] data) throws Exception {
+        for (String[] dates : data) {
+            String regularDate = dates[0];
+            String weekDate = dates[1];
+            Date date = null;
+            date = ymdFormat.parse(regularDate);
+            String s = ywdFormat.format(date);
+            if (!s.equals(weekDate)) {
+                throw new RuntimeException("format: got="+s+", expecetd="+weekDate);
+            }
+        }
+    }
+
+    private static void parseTest(String[][] data) throws Exception {
+        for (String[] dates : data) {
+            String regularDate = dates[0];
+            String weekDate = dates[1];
+            Date date1 = null, date2 = null;
+            date1 = ymdFormat.parse(regularDate);
+            date2 = ywdFormat.parse(weekDate);
+            if (!date1.equals(date2)) {
+                System.err.println(regularDate + ": date1 = " + date1);
+                System.err.println(weekDate + ": date2 = " + date2);
+                throw new RuntimeException("parse: date1 != date2");
+            }
+        }
+    }
+
+
+    // Non-lenient mode test
+    private static void nonLenientTest(String[] data) {
+        ywdFormat.setLenient(false);
+        for (String date : data) {
+            try {
+                Date d = ywdFormat.parse(date);
+                throw new RuntimeException("No ParseException thrown with " + date);
+            } catch (ParseException e) {
+                // OK
+            }
+        }
+        ywdFormat.setLenient(true);
+    }
+
+
+    private static void noWeekDateSupport() throws Exception {
+        // Tests with Japanese Imperial Calendar that doesn't support week dates.
+        Calendar jcal = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
+                                             new Locale("ja", "JP", "JP"));
+
+        jcal.setFirstDayOfWeek(MONDAY);
+        jcal.setMinimalDaysInFirstWeek(4);
+        SimpleDateFormat sdf = new SimpleDateFormat("Y-'W'ww-u");
+        sdf.setCalendar(jcal);
+        Date d = sdf.parse("21-W01-3"); // 2008-12-31 == H20-12-31
+        GregorianCalendar gcal = newCalendar();
+        gcal.setTime(d);
+        if (gcal.get(YEAR) != 2008
+            || gcal.get(MONTH) != DECEMBER
+            || gcal.get(DAY_OF_MONTH) != 31) {
+            String s = String.format("noWeekDateSupport: got %04d-%02d-%02d, expected 2008-12-31%n",
+                                     gcal.get(YEAR),
+                                     gcal.get(MONTH)+1,
+                                     gcal.get(DAY_OF_MONTH));
+            throw new RuntimeException(s);
+        }
+    }
+
+    private static GregorianCalendar newCalendar() {
+        // Use GMT to avoid any surprises related DST transitions.
+        GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
+        // Setup the ISO 8601 compatible parameters
+        cal.setFirstDayOfWeek(MONDAY);
+        cal.setMinimalDaysInFirstWeek(4);
+        return cal;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Calendar/WeekDateTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 4267450
+ * @summary Unit test for week date support
+ */
+
+import java.text.*;
+import java.util.*;
+import static java.util.GregorianCalendar.*;
+
+public class WeekDateTest {
+
+    // Week dates are in the ISO numbering for day-of-week.
+    static int[][][] data = {
+        // Calendar year-date, Week year-date
+        {{ 2005, 01, 01}, { 2004, 53, 6}},
+        {{ 2005, 01, 02}, { 2004, 53, 7}},
+        {{ 2005, 12, 31}, { 2005, 52, 6}},
+        {{ 2007, 01, 01}, { 2007, 01, 1}},
+        {{ 2007, 12, 30}, { 2007, 52, 7}},
+        {{ 2007, 12, 31}, { 2008, 01, 1}},
+        {{ 2008, 01, 01}, { 2008, 01, 2}},
+        {{ 2008, 12, 29}, { 2009, 01, 1}},
+        {{ 2008, 12, 31}, { 2009, 01, 3}},
+        {{ 2009, 01, 01}, { 2009, 01, 4}},
+        {{ 2009, 12, 31}, { 2009, 53, 4}},
+        {{ 2010, 01, 03}, { 2009, 53, 7}},
+        {{ 2009, 12, 31}, { 2009, 53, 4}},
+        {{ 2010, 01, 01}, { 2009, 53, 5}},
+        {{ 2010, 01, 02}, { 2009, 53, 6}},
+        {{ 2010, 01, 03}, { 2009, 53, 7}},
+        {{ 2008, 12, 28}, { 2008, 52, 7}},
+        {{ 2008, 12, 29}, { 2009, 01, 1}},
+        {{ 2008, 12, 30}, { 2009, 01, 2}},
+        {{ 2008, 12, 31}, { 2009, 01, 3}},
+        {{ 2009, 01, 01}, { 2009, 01, 4}}
+    };
+
+    // Data for leniency test
+    static final int[][][] leniencyData = {
+        {{ 2008, 12, 28}, { 2009,  0, 7}},
+        {{ 2008, 12, 21}, { 2009, -1, 7}},
+        {{ 2009,  1,  4}, { 2008, 53, 7}},
+    };
+
+    static final int[][] invalidData = {
+        { 2010, -1,  1},
+        { 2010, 00,  1},
+        { 2010, 55,  1},
+        { 2010, 03,  0},
+        { 2010, 04,  8},
+        { 2010, 04, 19},
+        { 2010, 05, -1},
+    };
+
+    public static void main(String[] args) {
+        GregorianCalendar cal = newCalendar();
+        for (int[][] dates : data) {
+            int[] expected = dates[0];
+            int[] weekDate = dates[1];
+            // Convert ISO 8601 day-of-week to Calendar.DAY_OF_WEEK.
+            int dayOfWeek = getCalendarDayOfWeek(weekDate[2]);
+
+            cal.clear();
+            cal.setWeekDate(weekDate[0], weekDate[1], dayOfWeek);
+            if (cal.get(YEAR) != expected[0]
+                || cal.get(MONTH)+1 != expected[1]
+                || cal.get(DAY_OF_MONTH) != expected[2]) {
+                String s = String.format("got=%4d-%02d-%02d, expected=%4d-%02d-%02d",
+                               cal.get(YEAR), cal.get(MONTH)+1, cal.get(DAY_OF_MONTH),
+                               expected[0], expected[1], expected[2]);
+                throw new RuntimeException(s);
+            }
+            if (cal.getWeekYear() != weekDate[0]
+                || cal.get(WEEK_OF_YEAR) != weekDate[1]
+                || cal.get(DAY_OF_WEEK) != dayOfWeek) {
+                String s = String.format(
+                    "got=%4d-W%02d-%d, expected=%4d-W%02d-%d (not ISO day-of-week)",
+                    cal.getWeekYear(), cal.get(WEEK_OF_YEAR), cal.get(DAY_OF_WEEK),
+                    weekDate[0], weekDate[1], dayOfWeek);
+                throw new RuntimeException(s);
+            }
+        }
+
+        // Test getWeeksInWeekYear().
+        // If we avoid the first week of January and the last week of
+        // December, getWeeksInWeekYear() and
+        // getActualMaximum(WEEK_OF_YEAR) values should be the same.
+        for (int year = 2000; year <= 2100; year++) {
+            cal.clear();
+            cal.set(year, JUNE, 1);
+            int n = cal.getWeeksInWeekYear();
+            if (n != cal.getActualMaximum(WEEK_OF_YEAR)) {
+                String s = String.format("getWeeksInWeekYear() = %d, "
+                                         + "getActualMaximum(WEEK_OF_YEAR) = %d%n",
+                                         n, cal.getActualMaximum(WEEK_OF_YEAR));
+                throw new RuntimeException(s);
+            }
+
+            cal.setWeekDate(cal.getWeekYear(), 1, MONDAY);
+            if (cal.getWeeksInWeekYear() != n) {
+                String s = String.format("first day: got %d, expected %d%n",
+                                         cal.getWeeksInWeekYear(), n);
+                throw new RuntimeException(s);
+            }
+
+            cal.setWeekDate(cal.getWeekYear(), n, SUNDAY);
+            if (cal.getWeeksInWeekYear() != n) {
+                String s = String.format("last day: got %d, expected %d%n",
+                                         cal.getWeeksInWeekYear(), n);
+                throw new RuntimeException(s);
+            }
+        }
+
+        // Test lenient mode with out of range values.
+        for (int[][] dates : leniencyData) {
+            int[] expected = dates[0];
+            int[] weekDate = dates[1];
+            // Convert ISO 8601 day-of-week to Calendar.DAY_OF_WEEK.
+            int dayOfWeek = getCalendarDayOfWeek(weekDate[2]);
+
+            cal.clear();
+            cal.setWeekDate(weekDate[0], weekDate[1], dayOfWeek);
+            if (cal.get(YEAR) != expected[0]
+                || cal.get(MONTH)+1 != expected[1]
+                || cal.get(DAY_OF_MONTH) != expected[2]) {
+                String s = String.format("got=%4d-%02d-%02d, expected=%4d-%02d-%02d",
+                               cal.get(YEAR), cal.get(MONTH)+1, cal.get(DAY_OF_MONTH),
+                               expected[0], expected[1], expected[2]);
+                throw new RuntimeException(s);
+            }
+        }
+
+        // Test non-lenient mode
+        cal.setLenient(false);
+        for (int[] date : invalidData) {
+            cal.clear();
+            try {
+                // Use the raw dayOfWeek value as invalid data
+                cal.setWeekDate(date[0], date[1], date[2]);
+                String s = String.format("didn't throw an IllegalArgumentException with"
+                                         + " %d, %d, %d",date[0], date[1], date[2]);
+                throw new RuntimeException(s);
+            } catch (IllegalArgumentException e) {
+                // OK
+            }
+        }
+    }
+
+    private static GregorianCalendar newCalendar() {
+        // Use GMT to avoid any surprises related DST transitions.
+        GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
+        if (!cal.isWeekDateSupported()) {
+            throw new RuntimeException("Week dates not supported");
+        }
+        // Setup the ISO 8601 compatible parameters
+        cal.setFirstDayOfWeek(MONDAY);
+        cal.setMinimalDaysInFirstWeek(4);
+        return cal;
+    }
+
+    private static int getCalendarDayOfWeek(int isoDayOfWeek) {
+        return (isoDayOfWeek == 7) ? SUNDAY : isoDayOfWeek + 1;
+    }
+}
--- a/test/java/util/Formatter/Constructors.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/util/Formatter/Constructors.java	Fri Sep 24 16:41:32 2010 -0700
@@ -58,7 +58,7 @@
     }
 
     static void locale(Formatter f) {
-        locale(f, Locale.getDefault());
+        locale(f, Locale.getDefault(Locale.Category.FORMAT));
     }
 
     static void locale(Formatter f, Locale l) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/LocaleCategory.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+import java.util.Locale;
+
+public class LocaleCategory {
+    private static Locale base = null;
+    private static Locale disp = null;
+    private static Locale fmt = null;
+    private static String enc = null;
+
+    public static void main(String[] args) {
+        base = new Locale(System.getProperty("user.language", ""),
+                          System.getProperty("user.country", ""),
+                          System.getProperty("user.variant", ""));
+        disp = new Locale(System.getProperty("user.language.display", ""),
+                          System.getProperty("user.country.display", ""),
+                          System.getProperty("user.variant.display", ""));
+        fmt  = new Locale(System.getProperty("user.language.format", ""),
+                          System.getProperty("user.country.format", ""),
+                          System.getProperty("user.variant.format", ""));
+        checkDefault();
+        testGetSetDefault();
+    }
+
+    static void checkDefault() {
+        if (!base.equals(Locale.getDefault()) ||
+            !disp.equals(Locale.getDefault(Locale.Category.DISPLAY)) ||
+            !fmt.equals(Locale.getDefault(Locale.Category.FORMAT))) {
+            throw new RuntimeException("Some of the return values from getDefault() do not agree with the locale derived from \"user.xxxx\" system properties");
+        }
+    }
+
+    static void testGetSetDefault() {
+        try {
+            Locale.setDefault(null, null);
+            throw new RuntimeException("setDefault(null, null) should throw a NullPointerException");
+        } catch (NullPointerException npe) {}
+
+        Locale.setDefault(Locale.CHINA);
+        if (!Locale.CHINA.equals(Locale.getDefault(Locale.Category.DISPLAY)) ||
+            !Locale.CHINA.equals(Locale.getDefault(Locale.Category.FORMAT))) {
+            throw new RuntimeException("setDefault() should set all default locales for all categories");
+        }
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/LocaleCategory.sh	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,79 @@
+#!/bin/sh
+#
+# @test
+# @bug 4700857
+# @summary tests for Locale.getDefault(Locale.Category) and 
+#    Locale.setDefault(Locale.Category, Locale)
+# @build LocaleCategory
+# @run shell/timeout=600 LocaleCategory.sh
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTCLASSES=${TESTCLASSES}"
+echo "CLASSPATH=${CLASSPATH}"
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  SunOS | Linux )
+    PS=":"
+    FS="/"
+    ;;
+  Windows* )
+    PS=";"
+    FS="\\"
+    ;;
+  * )
+    echo "Unrecognized system!"
+    exit 1;
+    ;;
+esac
+
+# test user.xxx.display user.xxx.format properties
+
+# run
+RUNCMD="${TESTJAVA}${FS}bin${FS}java -classpath ${TESTCLASSES} -Duser.language.display=ja -Duser.language.format=zh LocaleCategory"
+
+echo ${RUNCMD}
+${RUNCMD}
+result=$?
+
+if [ $result -eq 0 ]
+then
+  echo "Execution successful"
+else
+  echo "Execution of the test case failed."
+fi
+
+# test user.xxx properties overriding user.xxx.display/format
+
+# run
+RUNCMD="${TESTJAVA}${FS}bin${FS}java -classpath ${TESTCLASSES} -Duser.language=en -Duser.language.display=ja -Duser.language.format=zh LocaleCategory"
+
+echo ${RUNCMD}
+${RUNCMD}
+result=$?
+
+if [ $result -eq 0 ]
+then
+  echo "Execution successful"
+else
+  echo "Execution of the test case failed."
+fi
+
+exit $result
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/LocaleEnhanceTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,1293 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.IllformedLocaleException;
+import java.util.List;
+import java.util.Locale;
+import java.util.Locale.Builder;
+import java.util.Set;
+
+/**
+ * @test
+ * @bug 6875847
+ * @summary test API changes to Locale
+ */
+public class LocaleEnhanceTest extends LocaleTestFmwk {
+
+    public static void main(String[] args) throws Exception {
+        List<String> argList = new ArrayList<String>();
+        argList.addAll(Arrays.asList(args));
+        argList.add("-nothrow");
+        new LocaleEnhanceTest().run(argList.toArray(new String[argList.size()]));
+    }
+
+    public LocaleEnhanceTest() {
+    }
+
+    ///
+    /// Generic sanity tests
+    ///
+
+    /** A canonical language code. */
+    private static final String l = "en";
+
+    /** A canonical script code.. */
+    private static final String s = "Latn";
+
+    /** A canonical region code. */
+    private static final String c = "US";
+
+    /** A canonical variant code. */
+    private static final String v = "NewYork";
+
+    /**
+     * Ensure that Builder builds locales that have the expected
+     * tag and java6 ID.  Note the odd cases for the ID.
+     */
+    public void testCreateLocaleCanonicalValid() {
+        String[] valids = {
+            "en-Latn-US-NewYork", "en_US_NewYork_#Latn",
+            "en-Latn-US", "en_US_#Latn",
+            "en-Latn-NewYork", "en__NewYork_#Latn", // double underscore
+            "en-Latn", "en_#Latn",
+            "en-US-NewYork", "en_US_NewYork",
+            "en-US", "en_US",
+            "en-NewYork", "en__NewYork", // double underscore
+            "en", "en",
+            "und-Latn-US-NewYork", "_US_NewYork_#Latn",
+            "und-Latn-US", "_US_#Latn",
+            "und-Latn-NewYork", "", // variant only not supported
+            "und-Latn", "",
+            "und-US-NewYork", "_US_NewYork",
+            "und-US", "_US",
+            "und-NewYork", "", // variant only not supported
+            "und", ""
+        };
+
+        Builder builder = new Builder();
+
+        for (int i = 0; i < valids.length; i += 2) {
+            String tag = valids[i];
+            String id = valids[i+1];
+
+            String idl = (i & 16) == 0 ? l : "";
+            String ids = (i & 8) == 0 ? s : "";
+            String idc = (i & 4) == 0 ? c : "";
+            String idv = (i & 2) == 0 ? v : "";
+
+            String msg = String.valueOf(i/2) + ": '" + tag + "' ";
+
+            try {
+                Locale l = builder
+                    .setLanguage(idl)
+                    .setScript(ids)
+                    .setRegion(idc)
+                    .setVariant(idv)
+                    .build();
+                assertEquals(msg + "language", idl, l.getLanguage());
+                assertEquals(msg + "script", ids, l.getScript());
+                assertEquals(msg + "country", idc, l.getCountry());
+                assertEquals(msg + "variant", idv, l.getVariant());
+                assertEquals(msg + "tag", tag, l.toLanguageTag());
+                assertEquals(msg + "id", id, l.toString());
+            }
+            catch (IllegalArgumentException e) {
+                errln(msg + e.getMessage());
+            }
+        }
+    }
+
+    /**
+     * Test that locale construction works with 'multiple variants'.
+     * <p>
+     * The string "Newer__Yorker" is treated as three subtags,
+     * "Newer", "", and "Yorker", and concatenated into one
+     * subtag by omitting empty subtags and joining the remainer
+     * with underscores.  So the resulting variant tag is "Newer_Yorker".
+     * Note that 'New' and 'York' are invalid BCP47 variant subtags
+     * because they are too short.
+     */
+    public void testCreateLocaleMultipleVariants() {
+
+        String[] valids = {
+            "en-Latn-US-Newer-Yorker",  "en_US_Newer_Yorker_#Latn",
+            "en-Latn-Newer-Yorker",     "en__Newer_Yorker_#Latn",
+            "en-US-Newer-Yorker",       "en_US_Newer_Yorker",
+            "en-Newer-Yorker",          "en__Newer_Yorker",
+            "und-Latn-US-Newer-Yorker", "_US_Newer_Yorker_#Latn",
+            "und-Latn-Newer-Yorker",    "",
+            "und-US-Newer-Yorker",      "_US_Newer_Yorker",
+            "und-Newer-Yorker",         "",
+        };
+
+        Builder builder = new Builder(); // lenient variant
+
+        final String idv = "Newer_Yorker";
+        for (int i = 0; i < valids.length; i += 2) {
+            String tag = valids[i];
+            String id = valids[i+1];
+
+            String idl = (i & 8) == 0 ? l : "";
+            String ids = (i & 4) == 0 ? s : "";
+            String idc = (i & 2) == 0 ? c : "";
+
+            String msg = String.valueOf(i/2) + ": " + tag + " ";
+            try {
+                Locale l = builder
+                    .setLanguage(idl)
+                    .setScript(ids)
+                    .setRegion(idc)
+                    .setVariant(idv)
+                    .build();
+
+                assertEquals(msg + " language", idl, l.getLanguage());
+                assertEquals(msg + " script", ids, l.getScript());
+                assertEquals(msg + " country", idc, l.getCountry());
+                assertEquals(msg + " variant", idv, l.getVariant());
+
+                assertEquals(msg + "tag", tag, l.toLanguageTag());
+                assertEquals(msg + "id", id, l.toString());
+            }
+            catch (IllegalArgumentException e) {
+                errln(msg + e.getMessage());
+            }
+        }
+    }
+
+    /**
+     * Ensure that all these invalid formats are not recognized by
+     * forLanguageTag.
+     */
+    public void testCreateLocaleCanonicalInvalidSeparator() {
+        String[] invalids = {
+            // trailing separator
+            "en_Latn_US_NewYork_",
+            "en_Latn_US_",
+            "en_Latn_",
+            "en_",
+            "_",
+
+            // double separator
+            "en_Latn_US__NewYork",
+            "_Latn_US__NewYork",
+            "en_US__NewYork",
+            "_US__NewYork",
+
+            // are these OK?
+            // "en_Latn__US_NewYork", // variant is 'US_NewYork'
+            // "_Latn__US_NewYork", // variant is 'US_NewYork'
+            // "en__Latn_US_NewYork", // variant is 'Latn_US_NewYork'
+            // "en__US_NewYork", // variant is 'US_NewYork'
+
+            // double separator without language or script
+            "__US",
+            "__NewYork",
+
+            // triple separator anywhere except within variant
+            "en___NewYork",
+            "en_Latn___NewYork",
+            "_Latn___NewYork",
+            "___NewYork",
+        };
+
+        for (int i = 0; i < invalids.length; ++i) {
+            String id = invalids[i];
+            Locale l = Locale.forLanguageTag(id);
+            assertEquals(id, "und", l.toLanguageTag());
+        }
+    }
+
+    /**
+     * Ensure that all current locale ids parse.  Use DateFormat as a proxy
+     * for all current locale ids.
+     */
+    public void testCurrentLocales() {
+        Locale[] locales = java.text.DateFormat.getAvailableLocales();
+        Builder builder = new Builder();
+
+        for (Locale target : locales) {
+            String tag = target.toLanguageTag();
+
+            // the tag recreates the original locale,
+            // except no_NO_NY
+            Locale tagResult = Locale.forLanguageTag(tag);
+            if (!target.getVariant().equals("NY")) {
+                assertEquals("tagResult", target, tagResult);
+            }
+
+            // the builder also recreates the original locale,
+            // except ja_JP_JP, th_TH_TH and no_NO_NY
+            Locale builderResult = builder.setLocale(target).build();
+            if (target.getVariant().length() != 2) {
+                assertEquals("builderResult", target, builderResult);
+            }
+        }
+    }
+
+    /**
+     * Ensure that all icu locale ids parse.
+     */
+    public void testIcuLocales() throws Exception {
+        BufferedReader br = new BufferedReader(
+            new InputStreamReader(
+                LocaleEnhanceTest.class.getResourceAsStream("icuLocales.txt"),
+                "UTF-8"));
+        String id = null;
+        while (null != (id = br.readLine())) {
+            Locale result = Locale.forLanguageTag(id);
+            assertEquals("ulocale", id, result.toLanguageTag());
+        }
+    }
+
+    ///
+    /// Compatibility tests
+    ///
+
+    public void testConstructor() {
+        // all the old weirdness still holds, no new weirdness
+        String[][] tests = {
+            // language to lower case, region to upper, variant unchanged
+            // short
+            { "X", "y", "z", "x", "Y" },
+            // long
+            { "xXxXxXxXxXxX", "yYyYyYyYyYyYyYyY", "zZzZzZzZzZzZzZzZ",
+              "xxxxxxxxxxxx", "YYYYYYYYYYYYYYYY" },
+            // mapped language ids
+            { "he", "IW", "", "iw" },
+            { "iw", "IW", "", "iw" },
+            { "yi", "DE", "", "ji" },
+            { "ji", "DE", "", "ji" },
+            { "id", "ID", "", "in" },
+            { "in", "ID", "", "in" },
+            // special variants
+            { "ja", "JP", "JP" },
+            { "th", "TH", "TH" },
+            { "no", "NO", "NY" },
+            { "no", "NO", "NY" },
+            // no canonicalization of 3-letter language codes
+            { "eng", "US", "" }
+        };
+        for (int i = 0; i < tests.length; ++ i) {
+            String[] test = tests[i];
+            String id = String.valueOf(i);
+            Locale locale = new Locale(test[0], test[1], test[2]);
+            assertEquals(id + " lang", test.length > 3 ? test[3] : test[0], locale.getLanguage());
+            assertEquals(id + " region", test.length > 4 ? test[4] : test[1], locale.getCountry());
+            assertEquals(id + " variant", test.length > 5 ? test[5] : test[2], locale.getVariant());
+        }
+    }
+
+    ///
+    /// Locale API tests.
+    ///
+
+    public void testGetScript() {
+        // forLanguageTag normalizes case
+        Locale locale = Locale.forLanguageTag("und-latn");
+        assertEquals("forLanguageTag", "Latn", locale.getScript());
+
+        // Builder normalizes case
+        locale = new Builder().setScript("LATN").build();
+        assertEquals("builder", "Latn", locale.getScript());
+
+        // empty string is returned, not null, if there is no script
+        locale = Locale.forLanguageTag("und");
+        assertEquals("script is empty string", "", locale.getScript());
+    }
+
+    public void testGetExtension() {
+        // forLanguageTag does NOT normalize to hyphen
+        Locale locale = Locale.forLanguageTag("und-a-some_ex-tension");
+        assertEquals("some_ex-tension", null, locale.getExtension('a'));
+
+        // regular extension
+        locale = new Builder().setExtension('a', "some-ex-tension").build();
+        assertEquals("builder", "some-ex-tension", locale.getExtension('a'));
+
+        // returns null if extension is not present
+        assertEquals("empty b", null, locale.getExtension('b'));
+
+        // throws exception if extension tag is illegal
+        new ExpectIAE() { public void call() { Locale.forLanguageTag("").getExtension('\uD800'); }};
+
+        // 'x' is not an extension, it's a private use tag, but it's accessed through this API
+        locale = Locale.forLanguageTag("x-y-z-blork");
+        assertEquals("x", "y-z-blork", locale.getExtension('x'));
+    }
+
+    public void testGetExtensionKeys() {
+        Locale locale = Locale.forLanguageTag("und-a-xx-yy-b-zz-ww");
+        Set<Character> result = locale.getExtensionKeys();
+        assertEquals("result size", 2, result.size());
+        assertTrue("'a','b'", result.contains('a') && result.contains('b'));
+
+        // result is not mutable
+        try {
+            result.add('x');
+            errln("expected exception on add to extension key set");
+        }
+        catch (UnsupportedOperationException e) {
+            // ok
+        }
+
+        // returns empty set if no extensions
+        locale = Locale.forLanguageTag("und");
+        assertTrue("empty result", locale.getExtensionKeys().isEmpty());
+    }
+
+    public void testGetUnicodeLocaleAttributes() {
+        Locale locale = Locale.forLanguageTag("en-US-u-abc-def");
+        Set<String> attributes = locale.getUnicodeLocaleAttributes();
+        assertEquals("number of attributes", 2, attributes.size());
+        assertTrue("attribute abc", attributes.contains("abc"));
+        assertTrue("attribute def", attributes.contains("def"));
+
+        locale = Locale.forLanguageTag("en-US-u-ca-gregory");
+        attributes = locale.getUnicodeLocaleAttributes();
+        assertTrue("empty attributes", attributes.isEmpty());
+    }
+
+    public void testGetUnicodeLocaleType() {
+        Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai");
+        assertEquals("collation", "japanese", locale.getUnicodeLocaleType("co"));
+        assertEquals("numbers", "thai", locale.getUnicodeLocaleType("nu"));
+
+        // Unicode locale extension key is case insensitive
+        assertEquals("key case", "japanese", locale.getUnicodeLocaleType("Co"));
+
+        // if keyword is not present, returns null
+        assertEquals("locale keyword not present", null, locale.getUnicodeLocaleType("xx"));
+
+        // if no locale extension is set, returns null
+        locale = Locale.forLanguageTag("und");
+        assertEquals("locale extension not present", null, locale.getUnicodeLocaleType("co"));
+
+        // typeless keyword
+        locale = Locale.forLanguageTag("und-u-kn");
+        assertEquals("typeless keyword", "", locale.getUnicodeLocaleType("kn"));
+
+        // invalid keys throw exception
+        new ExpectIAE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType("q"); }};
+        new ExpectIAE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType("abcdefghi"); }};
+
+        // null argument throws exception
+        new ExpectNPE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType(null); }};
+    }
+
+    public void testGetUnicodeLocaleKeys() {
+        Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai");
+        Set<String> result = locale.getUnicodeLocaleKeys();
+        assertEquals("two keys", 2, result.size());
+        assertTrue("co and nu", result.contains("co") && result.contains("nu"));
+
+        // result is not modifiable
+        try {
+            result.add("frobozz");
+            errln("expected exception when add to locale key set");
+        }
+        catch (UnsupportedOperationException e) {
+            // ok
+        }
+    }
+
+    public void testPrivateUseExtension() {
+        Locale locale = Locale.forLanguageTag("x-y-x-blork-");
+        assertEquals("blork", "y-x-blork", locale.getExtension(Locale.PRIVATE_USE_EXTENSION));
+
+        locale = Locale.forLanguageTag("und");
+        assertEquals("no privateuse", null, locale.getExtension(Locale.PRIVATE_USE_EXTENSION));
+    }
+
+    public void testToLanguageTag() {
+        // lots of normalization to test here
+        // test locales created using the constructor
+        String[][] tests = {
+            // empty locale canonicalizes to 'und'
+            { "", "", "", "und" },
+            // variant alone is not a valid Locale, but has a valid language tag
+            { "", "", "NewYork", "und-NewYork" },
+            // standard valid locales
+            { "", "Us", "", "und-US" },
+            { "", "US", "NewYork", "und-US-NewYork" },
+            { "EN", "", "", "en" },
+            { "EN", "", "NewYork", "en-NewYork" },
+            { "EN", "US", "", "en-US" },
+            { "EN", "US", "NewYork", "en-US-NewYork" },
+            // underscore in variant will be emitted as multiple variant subtags
+            { "en", "US", "Newer_Yorker", "en-US-Newer-Yorker" },
+            // invalid variant subtags are appended as private use
+            { "en", "US", "new_yorker", "en-US-x-lvariant-new-yorker" },
+            // the first invalid variant subtags and following variant subtags are appended as private use
+            { "en", "US", "Windows_XP_Home", "en-US-Windows-x-lvariant-XP-Home" },
+            // too long variant and following variant subtags disappear
+            { "en", "US", "WindowsVista_SP2", "en-US" },
+            // invalid region subtag disappears
+            { "en", "USA", "", "en" },
+            // invalid language tag disappears
+            { "e", "US", "", "und-US" },
+            // three-letter language tags are not canonicalized
+            { "Eng", "", "", "eng" },
+            // legacy languages canonicalize to modern equivalents
+            { "he", "IW", "", "he-IW" },
+            { "iw", "IW", "", "he-IW" },
+            { "yi", "DE", "", "yi-DE" },
+            { "ji", "DE", "", "yi-DE" },
+            { "id", "ID", "", "id-ID" },
+            { "in", "ID", "", "id-ID" },
+            // special values are converted on output
+            { "ja", "JP", "JP", "ja-JP-u-ca-japanese-x-lvariant-JP" },
+            { "th", "TH", "TH", "th-TH-u-nu-thai-x-lvariant-TH" },
+            { "no", "NO", "NY", "nn-NO" }
+        };
+        for (int i = 0; i < tests.length; ++i) {
+            String[] test = tests[i];
+            Locale locale = new Locale(test[0], test[1], test[2]);
+            assertEquals("case " + i, test[3], locale.toLanguageTag());
+        }
+    }
+
+    public void testForLanguageTag() {
+        // forLanguageTag implements the 'Language-Tag' production of
+        // BCP47, so it handles private use and grandfathered tags,
+        // unlike locale builder.  Tags listed below (except for the
+        // sample private use tags) come from 4646bis Feb 29, 2009.
+
+        String[][] tests = {
+            // private use tags only
+            { "x-abc", "und-x-abc" },
+            { "x-a-b-c", "und-x-a-b-c" },
+            { "x-a-12345678", "und-x-a-12345678" },
+
+            // grandfathered tags with preferred mappings
+            { "i-ami", "ami" },
+            { "i-bnn", "bnn" },
+            { "i-hak", "hak" },
+            { "i-klingon", "tlh" },
+            { "i-lux", "lb" }, // two-letter tag
+            { "i-navajo", "nv" }, // two-letter tag
+            { "i-pwn", "pwn" },
+            { "i-tao", "tao" },
+            { "i-tay", "tay" },
+            { "i-tsu", "tsu" },
+            { "art-lojban", "jbo" },
+            { "no-bok", "nb" },
+            { "no-nyn", "nn" },
+            { "sgn-BE-FR", "sfb" },
+            { "sgn-BE-NL", "vgt" },
+            { "sgn-CH-DE", "sgg" },
+            { "zh-guoyu", "cmn" },
+            { "zh-hakka", "hak" },
+            { "zh-min-nan", "nan" },
+            { "zh-xiang", "hsn" },
+
+            // grandfathered irregular tags, no preferred mappings, drop illegal fields
+            // from end.  If no subtag is mappable, fallback to 'und'
+            { "i-default", "en-x-i-default" },
+            { "i-enochian", "und-x-i-enochian" },
+            { "i-mingo", "see-x-i-mingo" },
+            { "en-GB-oed", "en-GB-x-oed" },
+            { "zh-min", "nan-x-zh-min" },
+            { "cel-gaulish", "xtg-x-cel-gaulish" },
+        };
+        for (int i = 0; i < tests.length; ++i) {
+            String[] test = tests[i];
+            Locale locale = Locale.forLanguageTag(test[0]);
+            assertEquals("grandfathered case " + i, test[1], locale.toLanguageTag());
+        }
+
+        // forLanguageTag ignores everything past the first place it encounters
+        // a syntax error
+        tests = new String[][] {
+            { "valid",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def-x-y-12345678-z",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def-x-y-12345678-z" },
+            { "segment of private use tag too long",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def-x-y-123456789-z",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def-x-y" },
+            { "segment of private use tag is empty",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def-x-y--12345678-z",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def-x-y" },
+            { "first segment of private use tag is empty",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def-x--y-12345678-z",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def" },
+            { "illegal extension tag",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def-\uD800-y-12345678-z",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-def" },
+            { "locale subtag with no value",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-x-y-12345678-z",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-bb-x-y-12345678-z" },
+            { "locale key subtag invalid",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc-123456789-def-x-y-12345678-z",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-aa-abc" },
+            // locale key subtag invalid in earlier position, all following subtags
+            // dropped (and so the locale extension dropped as well)
+            { "locale key subtag invalid in earlier position",
+              "en-US-Newer-Yorker-a-bb-cc-dd-u-123456789-abc-bb-def-x-y-12345678-z",
+              "en-US-Newer-Yorker-a-bb-cc-dd" },
+        };
+        for (int i = 0; i < tests.length; ++i) {
+            String[] test = tests[i];
+            String msg = "syntax error case " + i + " " + test[0];
+            try {
+                Locale locale = Locale.forLanguageTag(test[1]);
+                assertEquals(msg, test[2], locale.toLanguageTag());
+            }
+            catch (IllegalArgumentException e) {
+                errln(msg + " caught exception: " + e);
+            }
+        }
+
+        // duplicated extension are just ignored
+        Locale locale = Locale.forLanguageTag("und-d-aa-00-bb-01-D-AA-10-cc-11-c-1234");
+        assertEquals("extension", "aa-00-bb-01", locale.getExtension('d'));
+        assertEquals("extension c", "1234", locale.getExtension('c'));
+
+        // redundant Unicode locale keys in an extension are ignored
+        locale = Locale.forLanguageTag("und-u-aa-000-bb-001-bB-002-cc-003-c-1234");
+        assertEquals("Unicode keywords", "aa-000-bb-001-cc-003", locale.getExtension(Locale.UNICODE_LOCALE_EXTENSION));
+        assertEquals("Duplicated Unicode locake key followed by an extension", "1234", locale.getExtension('c'));
+    }
+
+    public void testGetDisplayScript() {
+        Locale latnLocale = Locale.forLanguageTag("und-latn");
+        Locale hansLocale = Locale.forLanguageTag("und-hans");
+
+        Locale oldLocale = Locale.getDefault();
+
+        Locale.setDefault(Locale.US);
+        assertEquals("latn US", "Latin", latnLocale.getDisplayScript());
+        assertEquals("hans US", "Simplified Han", hansLocale.getDisplayScript());
+
+        // note, no localization data yet other than US
+        // this should break when we have localization data for DE
+        Locale.setDefault(Locale.GERMANY);
+        assertEquals("latn DE", "Latin", latnLocale.getDisplayScript());
+        assertEquals("hans DE", "Simplified Han", hansLocale.getDisplayScript());
+
+        Locale.setDefault(oldLocale);
+    }
+
+    public void testGetDisplayScriptWithLocale() {
+        Locale latnLocale = Locale.forLanguageTag("und-latn");
+        Locale hansLocale = Locale.forLanguageTag("und-hans");
+
+        assertEquals("latn US", "Latin", latnLocale.getDisplayScript(Locale.US));
+        assertEquals("hans US", "Simplified Han", hansLocale.getDisplayScript(Locale.US));
+
+        // note, no localization data yet other than US
+        // this should break when we have localization data for DE
+        assertEquals("latn DE", "Latin", latnLocale.getDisplayScript(Locale.GERMANY));
+        assertEquals("hans DE", "Simplified Han", hansLocale.getDisplayScript(Locale.GERMANY));
+    }
+
+    ///
+    /// Builder tests
+    ///
+
+    public void testBuilderSetLocale() {
+        Builder builder = new Builder();
+        Builder lenientBuilder = new Builder();
+
+        String languageTag = "en-Latn-US-NewYork-a-bb-ccc-u-co-japanese-x-y-z";
+        String target = "en-Latn-US-NewYork-a-bb-ccc-u-co-japanese-x-y-z";
+
+        Locale locale = Locale.forLanguageTag(languageTag);
+        Locale result = lenientBuilder
+            .setLocale(locale)
+            .build();
+        assertEquals("long tag", target, result.toLanguageTag());
+        assertEquals("long tag", locale, result);
+
+        // null is illegal
+        new BuilderNPE("locale") {
+            public void call() { b.setLocale(null); }
+        };
+
+        // builder canonicalizes the three legacy locales:
+        // ja_JP_JP, th_TH_TH, no_NY_NO.
+        locale = builder.setLocale(new Locale("ja", "JP", "JP")).build();
+        assertEquals("ja_JP_JP languagetag", "ja-JP-u-ca-japanese", locale.toLanguageTag());
+        assertEquals("ja_JP_JP variant", "", locale.getVariant());
+
+        locale = builder.setLocale(new Locale("th", "TH", "TH")).build();
+        assertEquals("th_TH_TH languagetag", "th-TH-u-nu-thai", locale.toLanguageTag());
+        assertEquals("th_TH_TH variant", "", locale.getVariant());
+
+        locale = builder.setLocale(new Locale("no", "NO", "NY")).build();
+        assertEquals("no_NO_NY languagetag", "nn-NO", locale.toLanguageTag());
+        assertEquals("no_NO_NY language", "nn", locale.getLanguage());
+        assertEquals("no_NO_NY variant", "", locale.getVariant());
+
+        // non-canonical, non-legacy locales are invalid
+        new BuilderILE("123_4567_89") {
+            public void call() {
+                b.setLocale(new Locale("123", "4567", "89"));
+            }
+        };
+    }
+
+    public void testBuilderSetLanguageTag() {
+        String source = "eN-LaTn-Us-NewYork-A-Xx-B-Yy-X-1-2-3";
+        String target = "en-Latn-US-NewYork-a-xx-b-yy-x-1-2-3";
+        Builder builder = new Builder();
+        String result = builder
+            .setLanguageTag(source)
+            .build()
+            .toLanguageTag();
+        assertEquals("language", target, result);
+
+        // redundant extensions cause a failure
+        new BuilderILE() { public void call() { b.setLanguageTag("und-a-xx-yy-b-ww-A-00-11-c-vv"); }};
+
+        // redundant Unicode locale extension keys within an Unicode locale extension cause a failure
+        new BuilderILE() { public void call() { b.setLanguageTag("und-u-nu-thai-NU-chinese-xx-1234"); }};
+    }
+
+    public void testBuilderSetLanguage() {
+        // language is normalized to lower case
+        String source = "eN";
+        String target = "en";
+        String defaulted = "";
+        Builder builder = new Builder();
+        String result = builder
+            .setLanguage(source)
+            .build()
+            .getLanguage();
+        assertEquals("en", target, result);
+
+        // setting with empty resets
+        result = builder
+            .setLanguage(target)
+            .setLanguage("")
+            .build()
+            .getLanguage();
+        assertEquals("empty", defaulted, result);
+
+        // setting with null resets too
+        result = builder
+                .setLanguage(target)
+                .setLanguage(null)
+                .build()
+                .getLanguage();
+        assertEquals("null", defaulted, result);
+
+        // language codes must be 2-8 alpha
+        // for forwards compatibility, 4-alpha and 5-8 alpha (registered)
+        // languages are accepted syntax
+        new BuilderILE("q", "abcdefghi", "13") { public void call() { b.setLanguage(arg); }};
+
+        // language code validation is NOT performed, any 2-8-alpha passes
+        assertNotNull("2alpha", builder.setLanguage("zz").build());
+        assertNotNull("8alpha", builder.setLanguage("abcdefgh").build());
+
+        // three-letter language codes are NOT canonicalized to two-letter
+        result = builder
+            .setLanguage("eng")
+            .build()
+            .getLanguage();
+        assertEquals("eng", "eng", result);
+    }
+
+    public void testBuilderSetScript() {
+        // script is normalized to title case
+        String source = "lAtN";
+        String target = "Latn";
+        String defaulted = "";
+        Builder builder = new Builder();
+        String result = builder
+            .setScript(source)
+            .build()
+            .getScript();
+        assertEquals("script", target, result);
+
+        // setting with empty resets
+        result = builder
+            .setScript(target)
+            .setScript("")
+            .build()
+            .getScript();
+        assertEquals("empty", defaulted, result);
+
+        // settting with null also resets
+        result = builder
+                .setScript(target)
+                .setScript(null)
+                .build()
+                .getScript();
+        assertEquals("null", defaulted, result);
+
+        // ill-formed script codes throw IAE
+        // must be 4alpha
+        new BuilderILE("abc", "abcde", "l3tn") { public void call() { b.setScript(arg); }};
+
+        // script code validation is NOT performed, any 4-alpha passes
+        assertEquals("4alpha", "Wxyz", builder.setScript("wxyz").build().getScript());
+    }
+
+    public void testBuilderSetRegion() {
+        // region is normalized to upper case
+        String source = "uS";
+        String target = "US";
+        String defaulted = "";
+        Builder builder = new Builder();
+        String result = builder
+            .setRegion(source)
+            .build()
+            .getCountry();
+        assertEquals("us", target, result);
+
+        // setting with empty resets
+        result = builder
+            .setRegion(target)
+            .setRegion("")
+            .build()
+            .getCountry();
+        assertEquals("empty", defaulted, result);
+
+        // setting with null also resets
+        result = builder
+                .setRegion(target)
+                .setRegion(null)
+                .build()
+                .getCountry();
+        assertEquals("null", defaulted, result);
+
+        // ill-formed region codes throw IAE
+        // 2 alpha or 3 numeric
+        new BuilderILE("q", "abc", "12", "1234", "a3", "12a") { public void call() { b.setRegion(arg); }};
+
+        // region code validation is NOT performed, any 2-alpha or 3-digit passes
+        assertEquals("2alpha", "ZZ", builder.setRegion("ZZ").build().getCountry());
+        assertEquals("3digit", "000", builder.setRegion("000").build().getCountry());
+    }
+
+    public void testBuilderSetVariant() {
+        // Variant case is not normalized in lenient variant mode
+        String source = "NewYork";
+        String target = source;
+        String defaulted = "";
+        Builder builder = new Builder();
+        String result = builder
+            .setVariant(source)
+            .build()
+            .getVariant();
+        assertEquals("NewYork", target, result);
+
+        result = builder
+            .setVariant("NeWeR_YoRkEr")
+            .build()
+            .toLanguageTag();
+        assertEquals("newer yorker", "und-NeWeR-YoRkEr", result);
+
+        // subtags of variant are NOT reordered
+        result = builder
+            .setVariant("zzzzz_yyyyy_xxxxx")
+            .build()
+            .getVariant();
+        assertEquals("zyx", "zzzzz_yyyyy_xxxxx", result);
+
+        // setting to empty resets
+        result = builder
+            .setVariant(target)
+            .setVariant("")
+            .build()
+            .getVariant();
+        assertEquals("empty", defaulted, result);
+
+        // setting to null also resets
+        result = builder
+                .setVariant(target)
+                .setVariant(null)
+                .build()
+                .getVariant();
+        assertEquals("null", defaulted, result);
+
+        // ill-formed variants throw IAE
+        // digit followed by 3-7 characters, or alpha followed by 4-8 characters.
+        new BuilderILE("abcd", "abcdefghi", "1ab", "1abcdefgh") { public void call() { b.setVariant(arg); }};
+
+        // 4 characters is ok as long as the first is a digit
+        assertEquals("digit+3alpha", "1abc", builder.setVariant("1abc").build().getVariant());
+
+        // all subfields must conform
+        new BuilderILE("abcde-fg") { public void call() { b.setVariant(arg); }};
+    }
+
+    public void testBuilderSetExtension() {
+        // upper case characters are normalized to lower case
+        final char sourceKey = 'a';
+        final String sourceValue = "aB-aBcdefgh-12-12345678";
+        String target = "ab-abcdefgh-12-12345678";
+        Builder builder = new Builder();
+        String result = builder
+            .setExtension(sourceKey, sourceValue)
+            .build()
+            .getExtension(sourceKey);
+        assertEquals("extension", target, result);
+
+        // setting with empty resets
+        result = builder
+            .setExtension(sourceKey, sourceValue)
+            .setExtension(sourceKey, "")
+            .build()
+            .getExtension(sourceKey);
+        assertEquals("empty", null, result);
+
+        // setting with null also resets
+        result = builder
+                .setExtension(sourceKey, sourceValue)
+                .setExtension(sourceKey, null)
+                .build()
+                .getExtension(sourceKey);
+        assertEquals("null", null, result);
+
+        // ill-formed extension keys throw IAE
+        // must be in [0-9a-ZA-Z]
+        new BuilderILE("$") { public void call() { b.setExtension('$', sourceValue); }};
+
+        // each segment of value must be 2-8 alphanum
+        new BuilderILE("ab-cd-123456789") { public void call() { b.setExtension(sourceKey, arg); }};
+
+        // no multiple hyphens.
+        new BuilderILE("ab--cd") { public void call() { b.setExtension(sourceKey, arg); }};
+
+        // locale extension key has special handling
+        Locale locale = builder
+            .setExtension('u', "co-japanese")
+            .build();
+        assertEquals("locale extension", "japanese", locale.getUnicodeLocaleType("co"));
+
+        // locale extension has same behavior with set locale keyword
+        Locale locale2 = builder
+            .setUnicodeLocaleKeyword("co", "japanese")
+            .build();
+        assertEquals("locales with extension", locale, locale2);
+
+        // setting locale extension overrides all previous calls to setLocaleKeyword
+        Locale locale3 = builder
+            .setExtension('u', "xxx-nu-thai")
+            .build();
+        assertEquals("remove co", null, locale3.getUnicodeLocaleType("co"));
+        assertEquals("override thai", "thai", locale3.getUnicodeLocaleType("nu"));
+        assertEquals("override attribute", 1, locale3.getUnicodeLocaleAttributes().size());
+
+        // setting locale keyword extends values already set by the locale extension
+        Locale locale4 = builder
+            .setUnicodeLocaleKeyword("co", "japanese")
+            .build();
+        assertEquals("extend", "japanese", locale4.getUnicodeLocaleType("co"));
+        assertEquals("extend", "thai", locale4.getUnicodeLocaleType("nu"));
+
+        // locale extension subtags are reordered
+        result = builder
+            .clear()
+            .setExtension('u', "456-123-zz-123-yy-456-xx-789")
+            .build()
+            .toLanguageTag();
+        assertEquals("reorder", "und-u-123-456-xx-789-yy-456-zz-123", result);
+
+        // multiple keyword types
+        result = builder
+            .clear()
+            .setExtension('u', "nu-thai-foobar")
+            .build()
+            .getUnicodeLocaleType("nu");
+        assertEquals("multiple types", "thai-foobar", result);
+
+        // redundant locale extensions are ignored
+        result = builder
+            .clear()
+            .setExtension('u', "nu-thai-NU-chinese-xx-1234")
+            .build()
+            .toLanguageTag();
+        assertEquals("duplicate keys", "und-u-nu-thai-xx-1234", result);
+    }
+
+    public void testBuilderAddUnicodeLocaleAttribute() {
+        Builder builder = new Builder();
+        Locale locale = builder
+            .addUnicodeLocaleAttribute("def")
+            .addUnicodeLocaleAttribute("abc")
+            .build();
+
+        Set<String> uattrs = locale.getUnicodeLocaleAttributes();
+        assertEquals("number of attributes", 2, uattrs.size());
+        assertTrue("attribute abc", uattrs.contains("abc"));
+        assertTrue("attribute def", uattrs.contains("def"));
+
+        // remove attribute
+        locale = builder.removeUnicodeLocaleAttribute("xxx")
+            .build();
+
+        assertEquals("remove bogus", 2, uattrs.size());
+
+        // add duplicate
+        locale = builder.addUnicodeLocaleAttribute("abc")
+            .build();
+        assertEquals("add duplicate", 2, uattrs.size());
+
+        // null attribute throws NPE
+        new BuilderNPE("null attribute") { public void call() { b.addUnicodeLocaleAttribute(null); }};
+
+        // illformed attribute throws IllformedLocaleException
+        new BuilderILE("invalid attribute") { public void call() { b.addUnicodeLocaleAttribute("ca"); }};
+    }
+
+    public void testBuildersetUnicodeLocaleKeyword() {
+        // Note: most behavior is tested in testBuilderSetExtension
+        Builder builder = new Builder();
+        Locale locale = builder
+            .setUnicodeLocaleKeyword("co", "japanese")
+            .setUnicodeLocaleKeyword("nu", "thai")
+            .build();
+        assertEquals("co", "japanese", locale.getUnicodeLocaleType("co"));
+        assertEquals("nu", "thai", locale.getUnicodeLocaleType("nu"));
+        assertEquals("keys", 2, locale.getUnicodeLocaleKeys().size());
+
+        // can clear a keyword by setting to null, others remain
+        String result = builder
+            .setUnicodeLocaleKeyword("co", null)
+            .build()
+            .toLanguageTag();
+        assertEquals("empty co", "und-u-nu-thai", result);
+
+        // locale keyword extension goes when all keywords are gone
+        result = builder
+            .setUnicodeLocaleKeyword("nu", null)
+            .build()
+            .toLanguageTag();
+        assertEquals("empty nu", "und", result);
+
+        // locale keywords are ordered independent of order of addition
+        result = builder
+            .setUnicodeLocaleKeyword("zz", "012")
+            .setUnicodeLocaleKeyword("aa", "345")
+            .build()
+            .toLanguageTag();
+        assertEquals("reordered", "und-u-aa-345-zz-012", result);
+
+        // null keyword throws NPE
+        new BuilderNPE("keyword") { public void call() { b.setUnicodeLocaleKeyword(null, "thai"); }};
+
+        // well-formed keywords are two alphanum
+        new BuilderILE("a", "abc") { public void call() { b.setUnicodeLocaleKeyword(arg, "value"); }};
+
+        // well-formed values are 3-8 alphanum
+        new BuilderILE("ab", "abcdefghi") { public void call() { b.setUnicodeLocaleKeyword("ab", arg); }};
+    }
+
+    public void testBuilderPrivateUseExtension() {
+        // normalizes hyphens to underscore, case to lower
+        String source = "c-B-a";
+        String target = "c-b-a";
+        Builder builder = new Builder();
+        String result = builder
+            .setExtension(Locale.PRIVATE_USE_EXTENSION, source)
+            .build()
+            .getExtension(Locale.PRIVATE_USE_EXTENSION);
+        assertEquals("abc", target, result);
+
+        // multiple hyphens are ill-formed
+        new BuilderILE("a--b") { public void call() { b.setExtension(Locale.PRIVATE_USE_EXTENSION, arg); }};
+    }
+
+    public void testBuilderClear() {
+        String monster = "en-latn-US-NewYork-a-bb-cc-u-co-japanese-x-z-y-x-x";
+        Builder builder = new Builder();
+        Locale locale = Locale.forLanguageTag(monster);
+        String result = builder
+            .setLocale(locale)
+            .clear()
+            .build()
+            .toLanguageTag();
+        assertEquals("clear", "und", result);
+    }
+
+    public void testBuilderRemoveUnicodeAttribute() {
+        // tested in testBuilderAddUnicodeAttribute
+    }
+
+    public void testBuilderBuild() {
+        // tested in other test methods
+    }
+
+    public void testSerialize() {
+        final Locale[] testLocales = {
+            Locale.ROOT,
+            new Locale("en"),
+            new Locale("en", "US"),
+            new Locale("en", "US", "Win"),
+            new Locale("en", "US", "Win_XP"),
+            new Locale("ja", "JP"),
+            new Locale("ja", "JP", "JP"),
+            new Locale("th", "TH"),
+            new Locale("th", "TH", "TH"),
+            new Locale("no", "NO"),
+            new Locale("nb", "NO"),
+            new Locale("nn", "NO"),
+            new Locale("no", "NO", "NY"),
+            new Locale("nn", "NO", "NY"),
+            new Locale("he", "IL"),
+            new Locale("he", "IL", "var"),
+            new Locale("Language", "Country", "Variant"),
+            new Locale("", "US"),
+            new Locale("", "", "Java"),
+            Locale.forLanguageTag("en-Latn-US"),
+            Locale.forLanguageTag("zh-Hans"),
+            Locale.forLanguageTag("zh-Hant-TW"),
+            Locale.forLanguageTag("ja-JP-u-ca-japanese"),
+            Locale.forLanguageTag("und-Hant"),
+            Locale.forLanguageTag("und-a-123-456"),
+            Locale.forLanguageTag("en-x-java"),
+            Locale.forLanguageTag("th-TH-u-ca-buddist-nu-thai-x-lvariant-TH"),
+        };
+
+        for (Locale locale : testLocales) {
+            try {
+                // write
+                ByteArrayOutputStream bos = new ByteArrayOutputStream();
+                ObjectOutputStream oos = new ObjectOutputStream(bos);
+                oos.writeObject(locale);
+
+                // read
+                ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+                ObjectInputStream ois = new ObjectInputStream(bis);
+                Object o = ois.readObject();
+
+                assertEquals("roundtrip " + locale, locale, o);
+            } catch (Exception e) {
+                errln(locale + " encountered exception:" + e.getLocalizedMessage());
+            }
+        }
+    }
+
+    public void testDeserialize6() {
+        final String TESTFILEPREFIX = "java6locale_";
+
+        File dataDir = null;
+        String dataDirName = System.getProperty("serialized.data.dir");
+        if (dataDirName == null) {
+            URL resdirUrl = getClass().getClassLoader().getResource("serialized");
+            if (resdirUrl != null) {
+                try {
+                    dataDir = new File(resdirUrl.toURI());
+                } catch (URISyntaxException urie) {
+                }
+            }
+        } else {
+            dataDir = new File(dataDirName);
+        }
+
+        if (dataDir == null || !dataDir.isDirectory()) {
+            errln("Could not locate the serialized test case data location");
+            return;
+        }
+
+        File[] files = dataDir.listFiles();
+        for (File testfile : files) {
+            if (testfile.isDirectory()) {
+                continue;
+            }
+            String name = testfile.getName();
+            if (!name.startsWith(TESTFILEPREFIX)) {
+                continue;
+            }
+            Locale locale;
+            String locStr = name.substring(TESTFILEPREFIX.length());
+            if (locStr.equals("ROOT")) {
+                locale = Locale.ROOT;
+            } else {
+                String[] fields = locStr.split("_", 3);
+                String lang = fields[0];
+                String country = (fields.length >= 2) ? fields[1] : "";
+                String variant = (fields.length == 3) ? fields[2] : "";
+                locale = new Locale(lang, country, variant);
+            }
+
+            // desrialize
+            try {
+                FileInputStream fis = new FileInputStream(testfile);
+                ObjectInputStream ois = new ObjectInputStream(fis);
+
+                Object o = ois.readObject();
+                assertEquals("Deserialize Java 6 Locale " + locale, o, locale);
+                ois.close();
+            } catch (Exception e) {
+                errln("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage());
+            }
+        }
+    }
+
+    ///
+    /// utility asserts
+    ///
+
+    private void assertTrue(String msg, boolean v) {
+        if (!v) {
+            errln(msg + ": expected true");
+        }
+    }
+
+    private void assertFalse(String msg, boolean v) {
+        if (v) {
+            errln(msg + ": expected false");
+        }
+    }
+
+    private void assertEquals(String msg, Object e, Object v) {
+        if (e == null ? v != null : !e.equals(v)) {
+            if (e != null) {
+                e = "'" + e + "'";
+            }
+            if (v != null) {
+                v = "'" + v + "'";
+            }
+            errln(msg + ": expected " + e + " but got " + v);
+        }
+    }
+
+    private void assertNotEquals(String msg, Object e, Object v) {
+        if (e == null ? v == null : e.equals(v)) {
+            if (e != null) {
+                e = "'" + e + "'";
+            }
+            errln(msg + ": expected not equal " + e);
+        }
+    }
+
+    private void assertNull(String msg, Object o) {
+        if (o != null) {
+            errln(msg + ": expected null but got '" + o + "'");
+        }
+    }
+
+    private void assertNotNull(String msg, Object o) {
+        if (o == null) {
+            errln(msg + ": expected non null");
+        }
+    }
+
+    // not currently used, might get rid of exceptions from the API
+    private abstract class ExceptionTest {
+        private final Class<? extends Exception> exceptionClass;
+
+        ExceptionTest(Class<? extends Exception> exceptionClass) {
+            this.exceptionClass = exceptionClass;
+        }
+
+        public void run() {
+            String failMsg = null;
+            try {
+                call();
+                failMsg = "expected " + exceptionClass.getName() + "  but no exception thrown.";
+            }
+            catch (Exception e) {
+                if (!exceptionClass.isAssignableFrom(e.getClass())) {
+                    failMsg = "expected " + exceptionClass.getName() + " but caught " + e;
+                }
+            }
+            if (failMsg != null) {
+                String msg = message();
+                msg = msg == null ? "" : msg + " ";
+                errln(msg + failMsg);
+            }
+        }
+
+        public String message() {
+            return null;
+        }
+
+        public abstract void call();
+    }
+
+    private abstract class ExpectNPE extends ExceptionTest {
+        ExpectNPE() {
+            super(NullPointerException.class);
+            run();
+        }
+    }
+
+    private abstract class BuilderNPE extends ExceptionTest {
+        protected final String msg;
+        protected final Builder b = new Builder();
+
+        BuilderNPE(String msg) {
+            super(NullPointerException.class);
+
+            this.msg = msg;
+
+            run();
+        }
+
+        public String message() {
+            return msg;
+        }
+    }
+
+    private abstract class ExpectIAE extends ExceptionTest {
+        ExpectIAE() {
+            super(IllegalArgumentException.class);
+            run();
+        }
+    }
+
+    private abstract class BuilderILE extends ExceptionTest {
+        protected final String[] args;
+        protected final Builder b = new Builder();
+
+        protected String arg; // mutates during call
+
+        BuilderILE(String... args) {
+            super(IllformedLocaleException.class);
+
+            this.args = args;
+
+            run();
+        }
+
+        public void run() {
+            for (String arg : args) {
+                this.arg = arg;
+                super.run();
+            }
+        }
+
+        public String message() {
+            return "arg: '" + arg + "'";
+        }
+    }
+}
--- a/test/java/util/Locale/LocaleTestFmwk.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/util/Locale/LocaleTestFmwk.java	Fri Sep 24 16:41:32 2010 -0700
@@ -1,10 +1,12 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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
@@ -20,6 +22,7 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
+
 /*
  *
  *
@@ -112,6 +115,8 @@
                 prompt = true;
             } else if (args[i].equals("-nothrow")) {
                 nothrow = true;
+            } else if (args[i].equals("-exitcode")) {
+                exitcode = true;
             } else {
                 Object m = testMethods.get( args[i] );
                 if( m != null ) {
@@ -165,7 +170,12 @@
             }
         }
         if (nothrow) {
-            System.exit(errorCount);
+            if (exitcode) {
+                System.exit(errorCount);
+            }
+            if (errorCount > 0) {
+                throw new IllegalArgumentException("encountered " + errorCount + " errors");
+            }
         }
     }
 
@@ -235,7 +245,7 @@
      */
     void usage() {
         System.out.println(getClass().getName() +
-                            ": [-verbose] [-nothrow] [-prompt] [test names]");
+                            ": [-verbose] [-nothrow] [-exitcode] [-prompt] [test names]");
 
         System.out.println("test names:");
         Enumeration methodNames = testMethods.keys();
@@ -246,6 +256,7 @@
 
     private boolean     prompt = false;
     private boolean     nothrow = false;
+    private boolean     exitcode = false;
     protected boolean   verbose = false;
 
     private PrintWriter log;
--- a/test/java/util/Locale/PrintDefaultLocale.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/util/Locale/PrintDefaultLocale.java	Fri Sep 24 16:41:32 2010 -0700
@@ -231,8 +231,15 @@
 
 public class PrintDefaultLocale {
     public static void main(String[] args) {
-        System.out.println(Locale.getDefault().toString());
-        System.out.println(Locale.getDefault().getDisplayName(Locale.US));
-        System.out.println(Charset.defaultCharset());
+        System.out.printf("default locale: ID: %s, Name: %s\n",
+            Locale.getDefault().toString(),
+            Locale.getDefault().getDisplayName(Locale.US));
+        System.out.printf("display locale: ID: %s, Name: %s\n",
+            Locale.getDefault(Locale.Category.DISPLAY).toString(),
+            Locale.getDefault(Locale.Category.DISPLAY).getDisplayName(Locale.US));
+        System.out.printf("format locale: ID: %s, Name: %s\n",
+            Locale.getDefault(Locale.Category.FORMAT).toString(),
+            Locale.getDefault(Locale.Category.FORMAT).getDisplayName(Locale.US));
+        System.out.printf("default charset: %s\n", Charset.defaultCharset());
     }
 }
--- a/test/java/util/Locale/data/deflocale.c	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/util/Locale/data/deflocale.c	Fri Sep 24 16:41:32 2010 -0700
@@ -29,100 +29,233 @@
  * WARNING:  This tool directly modifies the locale info in the Windows registry.
  * It may not work with the Windows versions after Windows XP SP2.  Also,
  * if the test did not complete or was manually killed, you will need to reset
- * the user default locale in the Control Panel manually.
+ * the user default locale in the Control Panel manually. This executable has
+ * to be run with the "Administrator" privilege.
  *
  * Usage: "deflocale.exe <java launcher> PrintDefaultLocale
  *
- * How to compile: "cl deflocale.c advapi32.lib"
+ * How to compile: "cl -DUNICODE -D_UNICODE deflocale.c user32.lib advapi32.lib"
  */
 #include <windows.h>
 #include <stdio.h>
 #include <memory.h>
 
-char* launcher;
-char szBuffer[MAX_PATH];
+wchar_t* launcher;
+wchar_t szBuffer[MAX_PATH];
 LCID LCIDArray[1024];
 int numLCIDs = 0;
+BOOL isWin7orUp = FALSE;
 
-void testLCID(int anLCID) {
+// for Windows 7
+BOOL (WINAPI * pfnEnumSystemLocalesEx)(LPVOID, DWORD, LPARAM, LPVOID);
+BOOL (WINAPI * pfnEnumUILanguages)(LPVOID, DWORD, LPARAM);
+LCID (WINAPI * pfnLocaleNameToLCID)(LPCWSTR, DWORD);
+int (WINAPI * pfnLCIDToLocaleName)(LCID, LPWSTR, int, DWORD);
+wchar_t* LocaleNamesArray[1024];
+wchar_t* UILangNamesArray[1024];
+int numLocaleNames = 0;
+int numUILangNames = 0;
+
+void launchAndWait() {
+    STARTUPINFO si;
+    PROCESS_INFORMATION pi;
+
+    ZeroMemory(&si, sizeof(si));
+    si.cb = sizeof(si);
+    ZeroMemory(&pi, sizeof(pi));
+    if (CreateProcess(NULL, launcher, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)==0) {
+        wprintf(L"CreateProcess failed with the error code: %x\n", GetLastError());
+    }
+
+    WaitForSingleObject( pi.hProcess, INFINITE );
+}
+
+void testLocale(int anLCID, wchar_t* pName) {
     HKEY hk;
 
-    printf("\n");
-    printf("OS Locale (lcid: %x): ", anLCID);
+    if (pName != NULL && wcslen(pName) == 2) {
+        // ignore language only locale.
+        return;
+    }
+
+    wprintf(L"\n");
+    wprintf(L"OS Locale (lcid: %x", anLCID);
+    if (pName != NULL) {
+        wprintf(L", name: %s", pName);
+    }
     GetLocaleInfo(anLCID, LOCALE_SENGLANGUAGE, szBuffer, MAX_PATH);
-    printf("%s (", szBuffer);
+    wprintf(L"): %s (", szBuffer);
     GetLocaleInfo(anLCID, LOCALE_SENGCOUNTRY, szBuffer, MAX_PATH);
-    printf("%s) - ", szBuffer);
+    wprintf(L"%s) - ", szBuffer);
     GetLocaleInfo(anLCID, LOCALE_IDEFAULTANSICODEPAGE, szBuffer, MAX_PATH);
-    printf("%s\n", szBuffer);
+    wprintf(L"%s\n", szBuffer);
     fflush(0);
 
-    if (RegOpenKeyEx(HKEY_CURRENT_USER, "Control Panel\\International", 0, KEY_READ | KEY_WRITE, &hk) == ERROR_SUCCESS) {
-        BYTE original[16];
-        BYTE test[16];
-        DWORD cb = 16;
-        STARTUPINFO si;
-        PROCESS_INFORMATION pi;
+    if (RegOpenKeyEx(HKEY_CURRENT_USER, L"Control Panel\\International", 0, KEY_READ | KEY_WRITE, &hk) == ERROR_SUCCESS) {
+        wchar_t originalLocale[16];
+        wchar_t testLocale[16];
+        wchar_t* pKeyName;
+        DWORD cb = sizeof(originalLocale);
+        DWORD cbTest;
 
-        RegQueryValueEx(hk, "Locale", 0, 0, original, &cb);
-        sprintf(test, "%08x", anLCID);
-        RegSetValueEx(hk, "Locale", 0, REG_SZ, test, cb);
-
-        ZeroMemory(&si, sizeof(si));
-        si.cb = sizeof(si);
-        ZeroMemory(&pi, sizeof(pi));
-        if (CreateProcess(NULL, launcher, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)==0) {
-            printf("CreateProcess failed with the error code: %x\n", GetLastError());
+        if (isWin7orUp) {
+            pKeyName = L"LocaleName";
+            wcscpy(testLocale, pName);
+            cbTest = wcslen(pName) * sizeof(wchar_t);
+        } else {
+            pKeyName = L"Locale";
+            swprintf(testLocale, L"%08x", anLCID);
+            cbTest = sizeof(wchar_t) * 8;
         }
 
-        WaitForSingleObject( pi.hProcess, INFINITE );
-
-        RegSetValueEx(hk, "Locale", 0, REG_SZ, original, cb);
+        RegQueryValueEx(hk, pKeyName, 0, 0, (LPBYTE)originalLocale, &cb);
+        RegSetValueEx(hk, pKeyName, 0, REG_SZ, (LPBYTE)testLocale, cbTest );
+        launchAndWait();
+        RegSetValueEx(hk, pKeyName, 0, REG_SZ, (LPBYTE)originalLocale, cb);
         RegCloseKey(hk);
     }
 }
 
-BOOL CALLBACK EnumLocaleProc(LPTSTR lpLocaleStr) {
-    sscanf(lpLocaleStr, "%08x", &LCIDArray[numLCIDs]);
+void testUILang(wchar_t* pName) {
+    HKEY hk;
+
+    wprintf(L"\n");
+    wprintf(L"OS UI Language (name: %s)\n", pName);
+    fflush(0);
+
+    if (RegOpenKeyEx(HKEY_CURRENT_USER, L"Control Panel\\Desktop", 0, KEY_READ | KEY_WRITE, &hk) == ERROR_SUCCESS) {
+        wchar_t originalUILang[16];
+        wchar_t testUILang[16];
+        wchar_t* pKeyName;
+        DWORD cb = sizeof(originalUILang);
+        DWORD cbTest = wcslen(pName) * sizeof(wchar_t);
+
+        pKeyName = L"PreferredUILanguages";
+        wcscpy(testUILang, pName);
+        cbTest = wcslen(pName) * sizeof(wchar_t);
+
+        RegQueryValueEx(hk, pKeyName, 0, 0, (LPBYTE)originalUILang, &cb);
+        RegSetValueEx(hk, pKeyName, 0, REG_SZ, (LPBYTE)testUILang, cbTest);
+        launchAndWait();
+        RegSetValueEx(hk, pKeyName, 0, REG_SZ, (LPBYTE)originalUILang, cb);
+        RegCloseKey(hk);
+    }
+}
+
+BOOL CALLBACK EnumLocalesProc(LPWSTR lpLocaleStr) {
+    swscanf(lpLocaleStr, L"%08x", &LCIDArray[numLCIDs]);
     numLCIDs ++;
 
     return TRUE;
 }
 
+BOOL CALLBACK EnumLocalesProcEx(LPWSTR lpLocaleStr, DWORD flags, LPARAM lp) {
+    wchar_t* pName = malloc((wcslen(lpLocaleStr) + 1) * sizeof(wchar_t *));
+    wcscpy(pName, lpLocaleStr);
+    LocaleNamesArray[numLocaleNames] = pName;
+    numLocaleNames ++;
+
+    return TRUE;
+}
+
+BOOL CALLBACK EnumUILanguagesProc(LPWSTR lpUILangStr, LPARAM lp) {
+    wchar_t* pName = malloc((wcslen(lpUILangStr) + 1) * sizeof(wchar_t *));
+    wcscpy(pName, lpUILangStr);
+    UILangNamesArray[numUILangNames] = pName;
+    numUILangNames ++;
+
+    return TRUE;
+}
+
 int sortLCIDs(LCID * pLCID1, LCID * pLCID2) {
     if (*pLCID1 < *pLCID2) return (-1);
     if (*pLCID1 == *pLCID2) return 0;
-    if (*pLCID1 > *pLCID2) return 1;
+    return 1;
+}
+
+int sortLocaleNames(wchar_t** ppName1, wchar_t** ppName2) {
+    LCID l1 = pfnLocaleNameToLCID(*ppName1, 0);
+    LCID l2 = pfnLocaleNameToLCID(*ppName2, 0);
+    return sortLCIDs(&l1, &l2);
 }
 
 int main(int argc, char** argv) {
     OSVERSIONINFO osvi;
-    LPTSTR commandline = GetCommandLine();
+    LPWSTR commandline = GetCommandLine();
     int i;
 
     osvi.dwOSVersionInfoSize = sizeof(osvi);
     GetVersionEx(&osvi);
-    printf("# OSVersionInfo\n");
-    printf("# MajorVersion: %d\n", osvi.dwMajorVersion);
-    printf("# MinorVersion: %d\n", osvi.dwMinorVersion);
-    printf("# BuildNumber: %d\n", osvi.dwBuildNumber);
-    printf("# CSDVersion: %s\n", osvi.szCSDVersion);
-    printf("\n");
+    wprintf(L"# OSVersionInfo\n");
+    wprintf(L"# MajorVersion: %d\n", osvi.dwMajorVersion);
+    wprintf(L"# MinorVersion: %d\n", osvi.dwMinorVersion);
+    wprintf(L"# BuildNumber: %d\n", osvi.dwBuildNumber);
+    wprintf(L"# CSDVersion: %s\n", osvi.szCSDVersion);
+    wprintf(L"\n");
     fflush(0);
 
-    launcher = strchr(commandline, ' ')+1;
-    while (*launcher == ' ') {
+    launcher = wcschr(commandline, L' ')+1;
+    while (*launcher == L' ') {
         launcher++;
     }
 
-    // Enumerate locales
-    EnumSystemLocales(EnumLocaleProc, LCID_INSTALLED);
+    isWin7orUp = (osvi.dwMajorVersion > 6) ||
+                 (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion >= 1);
+
+    if (!isWin7orUp) {
+        // Enumerate locales
+        EnumSystemLocales(EnumLocalesProc, LCID_INSTALLED);
 
-    // Sort LCIDs
-    qsort(LCIDArray, numLCIDs, sizeof(LCID), (void *)sortLCIDs);
+        // Sort LCIDs
+        qsort(LCIDArray, numLCIDs, sizeof(LCID), (void *)sortLCIDs);
+    } else {
+        // For Windows 7, use "LocaleName" registry key for the user locale
+        // as they seem to switch from "Locale".
+        HMODULE hmod = GetModuleHandle(L"kernel32");
+        *(FARPROC*)&pfnEnumSystemLocalesEx =
+            GetProcAddress(hmod, "EnumSystemLocalesEx");
+        *(FARPROC*)&pfnEnumUILanguages =
+            GetProcAddress(hmod, "EnumUILanguagesW");
+        *(FARPROC*)&pfnLocaleNameToLCID =
+            GetProcAddress(hmod, "LocaleNameToLCID");
+        *(FARPROC*)&pfnLCIDToLocaleName =
+            GetProcAddress(hmod, "LCIDToLocaleName");
+        if (pfnEnumSystemLocalesEx != NULL &&
+            pfnEnumUILanguages != NULL &&
+            pfnLocaleNameToLCID != NULL &&
+            pfnLCIDToLocaleName != NULL) {
+            // Enumerate locales
+            pfnEnumSystemLocalesEx(EnumLocalesProcEx,
+                    1, // LOCALE_WINDOWS
+                    (LPARAM)NULL, NULL);
+            // Enumerate UI Languages.
+            pfnEnumUILanguages(EnumUILanguagesProc,
+                    0x8, // MUI_LANGUAGE_NAME
+                    (LPARAM)NULL);
+        } else {
+            wprintf(L"Could not get needed entry points. quitting.\n");
+            exit(-1);
+        }
+
+        // Sort LocaleNames
+        qsort(LocaleNamesArray, numLocaleNames,
+              sizeof(wchar_t*), (void *)sortLocaleNames);
+        qsort(UILangNamesArray, numUILangNames,
+              sizeof(wchar_t*), (void *)sortLocaleNames);
+    }
 
     // Execute enumeration of Java default locales
-    for (i = 0; i < numLCIDs; i ++) {
-        testLCID(LCIDArray[i]);
+    if (isWin7orUp) {
+        for (i = 0; i < numLocaleNames; i ++) {
+            testLocale(pfnLocaleNameToLCID(LocaleNamesArray[i], 0),
+                                     LocaleNamesArray[i]);
+        }
+        for (i = 0; i < numUILangNames; i ++) {
+            testUILang(UILangNamesArray[i]);
+        }
+    } else {
+        for (i = 0; i < numLCIDs; i ++) {
+            testLocale(LCIDArray[i], NULL);
+        }
     }
 }
Binary file test/java/util/Locale/data/deflocale.exe has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/data/deflocale.input	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,7 @@
+# data file for deflocale.sh. Each line must have two locales in the following order.
+#
+#       LC_CTYPE        LC_MESSAGES
+ 
+        ja_JP.UTF-8     zh_CN.UTF-8
+        zh_CN.UTF-8     en_US.UTF-8
+        C               zh_CN.UTF-8
--- a/test/java/util/Locale/data/deflocale.jds3	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1793 +0,0 @@
-Sun Java Desktop System, Release 3 - build 36
-Assembled 23 May 2005
-Linux dnm-dtf-012 2.6.5-7.139-default #1 Fri Jan 14 15:41:33 UTC 2005 i686 i686 i386 GNU/Linux
-
-OS Locale:  aa_DJ
-aa_DJ
-Afar (Djibouti)
-ISO-8859-1
-
-OS Locale:  aa_ER
-aa_ER
-Afar (Eritrea)
-UTF-8
-
-OS Locale:  aa_ER.utf8
-aa_ER
-Afar (Eritrea)
-UTF-8
-
-OS Locale:  aa_ER@saaho
-aa_ER
-Afar (Eritrea)
-UTF-8
-
-OS Locale:  aa_ET
-aa_ET
-Afar (Ethiopia)
-UTF-8
-
-OS Locale:  aa_ET.utf8
-aa_ET
-Afar (Ethiopia)
-UTF-8
-
-OS Locale:  af_ZA
-af_ZA
-Afrikaans (South Africa)
-ISO-8859-1
-
-OS Locale:  am_ET
-am_ET
-Amharic (Ethiopia)
-UTF-8
-
-OS Locale:  am_ET.utf8
-am_ET
-Amharic (Ethiopia)
-UTF-8
-
-OS Locale:  an_ES
-an_ES
-Aragonese (Spain)
-ISO-8859-15
-
-OS Locale:  ar_AE
-ar_AE
-Arabic (United Arab Emirates)
-ISO-8859-6
-
-OS Locale:  ar_AE.utf8
-ar_AE
-Arabic (United Arab Emirates)
-UTF-8
-
-OS Locale:  ar_BH
-ar_BH
-Arabic (Bahrain)
-ISO-8859-6
-
-OS Locale:  ar_BH.utf8
-ar_BH
-Arabic (Bahrain)
-UTF-8
-
-OS Locale:  ar_DZ
-ar_DZ
-Arabic (Algeria)
-ISO-8859-6
-
-OS Locale:  ar_DZ.utf8
-ar_DZ
-Arabic (Algeria)
-UTF-8
-
-OS Locale:  ar_EG
-ar_EG
-Arabic (Egypt)
-ISO-8859-6
-
-OS Locale:  ar_EG.utf8
-ar_EG
-Arabic (Egypt)
-UTF-8
-
-OS Locale:  ar_IN
-ar_IN
-Arabic (India)
-UTF-8
-
-OS Locale:  ar_IN.utf8
-ar_IN
-Arabic (India)
-UTF-8
-
-OS Locale:  ar_IQ
-ar_IQ
-Arabic (Iraq)
-ISO-8859-6
-
-OS Locale:  ar_IQ.utf8
-ar_IQ
-Arabic (Iraq)
-UTF-8
-
-OS Locale:  ar_JO
-ar_JO
-Arabic (Jordan)
-ISO-8859-6
-
-OS Locale:  ar_JO.utf8
-ar_JO
-Arabic (Jordan)
-UTF-8
-
-OS Locale:  ar_KW
-ar_KW
-Arabic (Kuwait)
-ISO-8859-6
-
-OS Locale:  ar_KW.utf8
-ar_KW
-Arabic (Kuwait)
-UTF-8
-
-OS Locale:  ar_LB
-ar_LB
-Arabic (Lebanon)
-ISO-8859-6
-
-OS Locale:  ar_LB.utf8
-ar_LB
-Arabic (Lebanon)
-UTF-8
-
-OS Locale:  ar_LY
-ar_LY
-Arabic (Libya)
-ISO-8859-6
-
-OS Locale:  ar_LY.utf8
-ar_LY
-Arabic (Libya)
-UTF-8
-
-OS Locale:  ar_MA
-ar_MA
-Arabic (Morocco)
-ISO-8859-6
-
-OS Locale:  ar_MA.utf8
-ar_MA
-Arabic (Morocco)
-UTF-8
-
-OS Locale:  ar_OM
-ar_OM
-Arabic (Oman)
-ISO-8859-6
-
-OS Locale:  ar_OM.utf8
-ar_OM
-Arabic (Oman)
-UTF-8
-
-OS Locale:  ar_QA
-ar_QA
-Arabic (Qatar)
-ISO-8859-6
-
-OS Locale:  ar_QA.utf8
-ar_QA
-Arabic (Qatar)
-UTF-8
-
-OS Locale:  ar_SA
-ar_SA
-Arabic (Saudi Arabia)
-ISO-8859-6
-
-OS Locale:  ar_SA.utf8
-ar_SA
-Arabic (Saudi Arabia)
-UTF-8
-
-OS Locale:  ar_SD
-ar_SD
-Arabic (Sudan)
-ISO-8859-6
-
-OS Locale:  ar_SD.utf8
-ar_SD
-Arabic (Sudan)
-UTF-8
-
-OS Locale:  ar_SY
-ar_SY
-Arabic (Syria)
-ISO-8859-6
-
-OS Locale:  ar_SY.utf8
-ar_SY
-Arabic (Syria)
-UTF-8
-
-OS Locale:  ar_TN
-ar_TN
-Arabic (Tunisia)
-ISO-8859-6
-
-OS Locale:  ar_TN.utf8
-ar_TN
-Arabic (Tunisia)
-UTF-8
-
-OS Locale:  ar_YE
-ar_YE
-Arabic (Yemen)
-ISO-8859-6
-
-OS Locale:  ar_YE.utf8
-ar_YE
-Arabic (Yemen)
-UTF-8
-
-OS Locale:  az_AZ.utf8
-az_AZ
-Azerbaijani (Azerbaijan)
-UTF-8
-
-OS Locale:  be_BY
-be_BY
-Belarusian (Belarus)
-windows-1251
-
-OS Locale:  be_BY.utf8
-be_BY
-Belarusian (Belarus)
-UTF-8
-
-OS Locale:  bg_BG
-bg_BG
-Bulgarian (Bulgaria)
-windows-1251
-
-OS Locale:  bg_BG.utf8
-bg_BG
-Bulgarian (Bulgaria)
-UTF-8
-
-OS Locale:  bn_BD
-bn_BD
-Bengali (Bangladesh)
-UTF-8
-
-OS Locale:  bn_BD.utf8
-bn_BD
-Bengali (Bangladesh)
-UTF-8
-
-OS Locale:  bn_IN
-bn_IN
-Bengali (India)
-UTF-8
-
-OS Locale:  bn_IN.utf8
-bn_IN
-Bengali (India)
-UTF-8
-
-OS Locale:  br_FR
-br_FR
-Breton (France)
-ISO-8859-1
-
-OS Locale:  br_FR@euro
-br_FR
-Breton (France)
-ISO-8859-15
-
-OS Locale:  bs_BA
-bs_BA
-Bosnian (Bosnia and Herzegovina)
-ISO-8859-2
-
-OS Locale:  byn_ER
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  byn_ER.utf8
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  ca_ES
-ca_ES
-Catalan (Spain)
-ISO-8859-1
-
-OS Locale:  ca_ES.utf8
-ca_ES
-Catalan (Spain)
-UTF-8
-
-OS Locale:  ca_ES@euro
-ca_ES
-Catalan (Spain)
-ISO-8859-15
-
-OS Locale:  cs_CZ
-cs_CZ
-Czech (Czech Republic)
-ISO-8859-2
-
-OS Locale:  cs_CZ.utf8
-cs_CZ
-Czech (Czech Republic)
-UTF-8
-
-OS Locale:  cy_GB
-cy_GB
-Welsh (United Kingdom)
-UTF-8
-
-OS Locale:  cy_GB.utf8
-cy_GB
-Welsh (United Kingdom)
-UTF-8
-
-OS Locale:  da_DK
-da_DK
-Danish (Denmark)
-ISO-8859-1
-
-OS Locale:  da_DK.utf8
-da_DK
-Danish (Denmark)
-UTF-8
-
-OS Locale:  da_DK@euro
-da_DK
-Danish (Denmark)
-ISO-8859-1
-
-OS Locale:  de_AT
-de_AT
-German (Austria)
-ISO-8859-1
-
-OS Locale:  de_AT.utf8
-de_AT
-German (Austria)
-UTF-8
-
-OS Locale:  de_AT@euro
-de_AT
-German (Austria)
-ISO-8859-15
-
-OS Locale:  de_BE
-de_BE
-German (Belgium)
-ISO-8859-1
-
-OS Locale:  de_BE.utf8
-de_BE
-German (Belgium)
-UTF-8
-
-OS Locale:  de_BE@euro
-de_BE
-German (Belgium)
-ISO-8859-15
-
-OS Locale:  de_CH
-de_CH
-German (Switzerland)
-ISO-8859-1
-
-OS Locale:  de_CH.utf8
-de_CH
-German (Switzerland)
-UTF-8
-
-OS Locale:  de_DE
-de_DE
-German (Germany)
-ISO-8859-1
-
-OS Locale:  de_DE.utf8
-de_DE
-German (Germany)
-UTF-8
-
-OS Locale:  de_DE@euro
-de_DE
-German (Germany)
-ISO-8859-15
-
-OS Locale:  de_LU
-de_LU
-German (Luxembourg)
-ISO-8859-1
-
-OS Locale:  de_LU.utf8
-de_LU
-German (Luxembourg)
-UTF-8
-
-OS Locale:  de_LU@euro
-de_LU
-German (Luxembourg)
-ISO-8859-15
-
-OS Locale:  el_GR
-el_GR
-Greek (Greece)
-ISO-8859-7
-
-OS Locale:  el_GR.utf8
-el_GR
-Greek (Greece)
-UTF-8
-
-OS Locale:  en_AU
-en_AU
-English (Australia)
-ISO-8859-1
-
-OS Locale:  en_AU.utf8
-en_AU
-English (Australia)
-UTF-8
-
-OS Locale:  en_BE
-en_BE
-English (Belgium)
-ISO-8859-1
-
-OS Locale:  en_BE.utf8
-en_BE
-English (Belgium)
-UTF-8
-
-OS Locale:  en_BE@euro
-en_BE
-English (Belgium)
-ISO-8859-15
-
-OS Locale:  en_BW
-en_BW
-English (Botswana)
-ISO-8859-1
-
-OS Locale:  en_BW.utf8
-en_BW
-English (Botswana)
-UTF-8
-
-OS Locale:  en_CA
-en_CA
-English (Canada)
-ISO-8859-1
-
-OS Locale:  en_CA.utf8
-en_CA
-English (Canada)
-UTF-8
-
-OS Locale:  en_DK
-en_DK
-English (Denmark)
-ISO-8859-1
-
-OS Locale:  en_DK.utf8
-en_DK
-English (Denmark)
-UTF-8
-
-OS Locale:  en_GB
-en_GB
-English (United Kingdom)
-ISO-8859-1
-
-OS Locale:  en_GB.iso885915
-en_GB
-English (United Kingdom)
-ISO-8859-15
-
-OS Locale:  en_GB.utf8
-en_GB
-English (United Kingdom)
-UTF-8
-
-OS Locale:  en_HK
-en_HK
-English (Hong Kong)
-ISO-8859-1
-
-OS Locale:  en_HK.utf8
-en_HK
-English (Hong Kong)
-UTF-8
-
-OS Locale:  en_IE
-en_IE
-English (Ireland)
-ISO-8859-1
-
-OS Locale:  en_IE.utf8
-en_IE
-English (Ireland)
-UTF-8
-
-OS Locale:  en_IE@euro
-en_IE
-English (Ireland)
-ISO-8859-15
-
-OS Locale:  en_IN
-en_IN
-English (India)
-UTF-8
-
-OS Locale:  en_NZ
-en_NZ
-English (New Zealand)
-ISO-8859-1
-
-OS Locale:  en_NZ.utf8
-en_NZ
-English (New Zealand)
-UTF-8
-
-OS Locale:  en_PH
-en_PH
-English (Philippines)
-ISO-8859-1
-
-OS Locale:  en_PH.utf8
-en_PH
-English (Philippines)
-UTF-8
-
-OS Locale:  en_SG
-en_SG
-English (Singapore)
-ISO-8859-1
-
-OS Locale:  en_SG.utf8
-en_SG
-English (Singapore)
-UTF-8
-
-OS Locale:  en_US
-en_US
-English (United States)
-ISO-8859-1
-
-OS Locale:  en_US.iso885915
-en_US
-English (United States)
-ISO-8859-15
-
-OS Locale:  en_US.utf8
-en_US
-English (United States)
-UTF-8
-
-OS Locale:  en_ZA
-en_ZA
-English (South Africa)
-ISO-8859-1
-
-OS Locale:  en_ZA.utf8
-en_ZA
-English (South Africa)
-UTF-8
-
-OS Locale:  en_ZW
-en_ZW
-English (Zimbabwe)
-ISO-8859-1
-
-OS Locale:  en_ZW.utf8
-en_ZW
-English (Zimbabwe)
-UTF-8
-
-OS Locale:  es_AR
-es_AR
-Spanish (Argentina)
-ISO-8859-1
-
-OS Locale:  es_AR.utf8
-es_AR
-Spanish (Argentina)
-UTF-8
-
-OS Locale:  es_BO
-es_BO
-Spanish (Bolivia)
-ISO-8859-1
-
-OS Locale:  es_BO.utf8
-es_BO
-Spanish (Bolivia)
-UTF-8
-
-OS Locale:  es_CL
-es_CL
-Spanish (Chile)
-ISO-8859-1
-
-OS Locale:  es_CL.utf8
-es_CL
-Spanish (Chile)
-UTF-8
-
-OS Locale:  es_CO
-es_CO
-Spanish (Colombia)
-ISO-8859-1
-
-OS Locale:  es_CO.utf8
-es_CO
-Spanish (Colombia)
-UTF-8
-
-OS Locale:  es_CR
-es_CR
-Spanish (Costa Rica)
-ISO-8859-1
-
-OS Locale:  es_CR.utf8
-es_CR
-Spanish (Costa Rica)
-UTF-8
-
-OS Locale:  es_DO
-es_DO
-Spanish (Dominican Republic)
-ISO-8859-1
-
-OS Locale:  es_DO.utf8
-es_DO
-Spanish (Dominican Republic)
-UTF-8
-
-OS Locale:  es_EC
-es_EC
-Spanish (Ecuador)
-ISO-8859-1
-
-OS Locale:  es_EC.utf8
-es_EC
-Spanish (Ecuador)
-UTF-8
-
-OS Locale:  es_ES
-es_ES
-Spanish (Spain)
-ISO-8859-1
-
-OS Locale:  es_ES.utf8
-es_ES
-Spanish (Spain)
-UTF-8
-
-OS Locale:  es_ES@euro
-es_ES
-Spanish (Spain)
-ISO-8859-15
-
-OS Locale:  es_GT
-es_GT
-Spanish (Guatemala)
-ISO-8859-1
-
-OS Locale:  es_GT.utf8
-es_GT
-Spanish (Guatemala)
-UTF-8
-
-OS Locale:  es_HN
-es_HN
-Spanish (Honduras)
-ISO-8859-1
-
-OS Locale:  es_HN.utf8
-es_HN
-Spanish (Honduras)
-UTF-8
-
-OS Locale:  es_MX
-es_MX
-Spanish (Mexico)
-ISO-8859-1
-
-OS Locale:  es_MX.utf8
-es_MX
-Spanish (Mexico)
-UTF-8
-
-OS Locale:  es_NI
-es_NI
-Spanish (Nicaragua)
-ISO-8859-1
-
-OS Locale:  es_NI.utf8
-es_NI
-Spanish (Nicaragua)
-UTF-8
-
-OS Locale:  es_PA
-es_PA
-Spanish (Panama)
-ISO-8859-1
-
-OS Locale:  es_PA.utf8
-es_PA
-Spanish (Panama)
-UTF-8
-
-OS Locale:  es_PE
-es_PE
-Spanish (Peru)
-ISO-8859-1
-
-OS Locale:  es_PE.utf8
-es_PE
-Spanish (Peru)
-UTF-8
-
-OS Locale:  es_PR
-es_PR
-Spanish (Puerto Rico)
-ISO-8859-1
-
-OS Locale:  es_PR.utf8
-es_PR
-Spanish (Puerto Rico)
-UTF-8
-
-OS Locale:  es_PY
-es_PY
-Spanish (Paraguay)
-ISO-8859-1
-
-OS Locale:  es_PY.utf8
-es_PY
-Spanish (Paraguay)
-UTF-8
-
-OS Locale:  es_SV
-es_SV
-Spanish (El Salvador)
-ISO-8859-1
-
-OS Locale:  es_SV.utf8
-es_SV
-Spanish (El Salvador)
-UTF-8
-
-OS Locale:  es_US
-es_US
-Spanish (United States)
-ISO-8859-1
-
-OS Locale:  es_US.utf8
-es_US
-Spanish (United States)
-UTF-8
-
-OS Locale:  es_UY
-es_UY
-Spanish (Uruguay)
-ISO-8859-1
-
-OS Locale:  es_UY.utf8
-es_UY
-Spanish (Uruguay)
-UTF-8
-
-OS Locale:  es_VE
-es_VE
-Spanish (Venezuela)
-ISO-8859-1
-
-OS Locale:  es_VE.utf8
-es_VE
-Spanish (Venezuela)
-UTF-8
-
-OS Locale:  et_EE
-et_EE
-Estonian (Estonia)
-ISO-8859-1
-
-OS Locale:  et_EE.iso885915
-et_EE
-Estonian (Estonia)
-ISO-8859-15
-
-OS Locale:  et_EE.utf8
-et_EE
-Estonian (Estonia)
-UTF-8
-
-OS Locale:  eu_ES
-eu_ES
-Basque (Spain)
-ISO-8859-1
-
-OS Locale:  eu_ES.utf8
-eu_ES
-Basque (Spain)
-UTF-8
-
-OS Locale:  eu_ES@euro
-eu_ES
-Basque (Spain)
-ISO-8859-15
-
-OS Locale:  fa_IR
-fa_IR
-Persian (Iran)
-UTF-8
-
-OS Locale:  fa_IR.utf8
-fa_IR
-Persian (Iran)
-UTF-8
-
-OS Locale:  fi_FI
-fi_FI
-Finnish (Finland)
-ISO-8859-1
-
-OS Locale:  fi_FI.utf8
-fi_FI
-Finnish (Finland)
-UTF-8
-
-OS Locale:  fi_FI@euro
-fi_FI
-Finnish (Finland)
-ISO-8859-15
-
-OS Locale:  fo_FO
-fo_FO
-Faroese (Faroe Islands)
-ISO-8859-1
-
-OS Locale:  fo_FO.utf8
-fo_FO
-Faroese (Faroe Islands)
-UTF-8
-
-OS Locale:  fr_BE
-fr_BE
-French (Belgium)
-ISO-8859-1
-
-OS Locale:  fr_BE.utf8
-fr_BE
-French (Belgium)
-UTF-8
-
-OS Locale:  fr_BE@euro
-fr_BE
-French (Belgium)
-ISO-8859-15
-
-OS Locale:  fr_CA
-fr_CA
-French (Canada)
-ISO-8859-1
-
-OS Locale:  fr_CA.utf8
-fr_CA
-French (Canada)
-UTF-8
-
-OS Locale:  fr_CH
-fr_CH
-French (Switzerland)
-ISO-8859-1
-
-OS Locale:  fr_CH.utf8
-fr_CH
-French (Switzerland)
-UTF-8
-
-OS Locale:  fr_FR
-fr_FR
-French (France)
-ISO-8859-1
-
-OS Locale:  fr_FR.utf8
-fr_FR
-French (France)
-UTF-8
-
-OS Locale:  fr_FR@euro
-fr_FR
-French (France)
-ISO-8859-15
-
-OS Locale:  fr_LU
-fr_LU
-French (Luxembourg)
-ISO-8859-1
-
-OS Locale:  fr_LU.utf8
-fr_LU
-French (Luxembourg)
-UTF-8
-
-OS Locale:  fr_LU@euro
-fr_LU
-French (Luxembourg)
-ISO-8859-15
-
-OS Locale:  ga_IE
-ga_IE
-Irish (Ireland)
-ISO-8859-1
-
-OS Locale:  ga_IE.utf8
-ga_IE
-Irish (Ireland)
-UTF-8
-
-OS Locale:  ga_IE@euro
-ga_IE
-Irish (Ireland)
-ISO-8859-15
-
-OS Locale:  gd_GB
-gd_GB
-Scottish Gaelic (United Kingdom)
-ISO-8859-15
-
-OS Locale:  gez_ER
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  gez_ER@abegede
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  gez_ET
-en_ET
-English (Ethiopia)
-UTF-8
-
-OS Locale:  gez_ET@abegede
-en_ET
-English (Ethiopia)
-UTF-8
-
-OS Locale:  gl_ES
-gl_ES
-Gallegan (Spain)
-ISO-8859-1
-
-OS Locale:  gl_ES.utf8
-gl_ES
-Gallegan (Spain)
-UTF-8
-
-OS Locale:  gl_ES@euro
-gl_ES
-Gallegan (Spain)
-ISO-8859-15
-
-OS Locale:  gu_IN
-gu_IN
-Gujarati (India)
-UTF-8
-
-OS Locale:  gv_GB
-gv_GB
-Manx (United Kingdom)
-ISO-8859-1
-
-OS Locale:  gv_GB.utf8
-gv_GB
-Manx (United Kingdom)
-UTF-8
-
-OS Locale:  he_IL
-iw_IL
-Hebrew (Israel)
-ISO-8859-8
-
-OS Locale:  he_IL.utf8
-iw_IL
-Hebrew (Israel)
-UTF-8
-
-OS Locale:  hi_IN
-hi_IN
-Hindi (India)
-UTF-8
-
-OS Locale:  hi_IN.utf8
-hi_IN
-Hindi (India)
-UTF-8
-
-OS Locale:  hr_HR
-hr_HR
-Croatian (Croatia)
-ISO-8859-2
-
-OS Locale:  hr_HR.utf8
-hr_HR
-Croatian (Croatia)
-UTF-8
-
-OS Locale:  hu_HU
-hu_HU
-Hungarian (Hungary)
-ISO-8859-2
-
-OS Locale:  hu_HU.utf8
-hu_HU
-Hungarian (Hungary)
-UTF-8
-
-OS Locale:  id_ID
-in_ID
-Indonesian (Indonesia)
-ISO-8859-1
-
-OS Locale:  id_ID.utf8
-in_ID
-Indonesian (Indonesia)
-UTF-8
-
-OS Locale:  is_IS
-is_IS
-Icelandic (Iceland)
-ISO-8859-1
-
-OS Locale:  is_IS.utf8
-is_IS
-Icelandic (Iceland)
-UTF-8
-
-OS Locale:  it_CH
-it_CH
-Italian (Switzerland)
-ISO-8859-1
-
-OS Locale:  it_CH.utf8
-it_CH
-Italian (Switzerland)
-UTF-8
-
-OS Locale:  it_IT
-it_IT
-Italian (Italy)
-ISO-8859-1
-
-OS Locale:  it_IT.utf8
-it_IT
-Italian (Italy)
-UTF-8
-
-OS Locale:  it_IT@euro
-it_IT
-Italian (Italy)
-ISO-8859-15
-
-OS Locale:  iw_IL
-iw_IL
-Hebrew (Israel)
-ISO-8859-8
-
-OS Locale:  iw_IL.utf8
-iw_IL
-Hebrew (Israel)
-UTF-8
-
-OS Locale:  ja_JP.eucjp
-ja_JP
-Japanese (Japan)
-x-euc-jp-linux
-
-OS Locale:  ja_JP.sjis
-ja_JP
-Japanese (Japan)
-Shift_JIS
-
-OS Locale:  ja_JP.utf8
-ja_JP
-Japanese (Japan)
-UTF-8
-
-OS Locale:  ka_GE
-ka_GE
-Georgian (Georgia)
-UTF-8
-
-OS Locale:  kk_KZ
-kk_KZ
-Kazakh (Kazakhstan)
-UTF-8
-
-OS Locale:  kl_GL
-kl_GL
-Greenlandic (Greenland)
-ISO-8859-1
-
-OS Locale:  kl_GL.utf8
-kl_GL
-Greenlandic (Greenland)
-UTF-8
-
-OS Locale:  kn_IN
-kn_IN
-Kannada (India)
-UTF-8
-
-OS Locale:  ko_KR.euckr
-ko_KR
-Korean (South Korea)
-EUC-KR
-
-OS Locale:  ko_KR.utf8
-ko_KR
-Korean (South Korea)
-UTF-8
-
-OS Locale:  kw_GB
-kw_GB
-Cornish (United Kingdom)
-ISO-8859-1
-
-OS Locale:  kw_GB.utf8
-kw_GB
-Cornish (United Kingdom)
-UTF-8
-
-OS Locale:  lg_UG
-lg_UG
-Ganda (Uganda)
-UTF-8
-
-OS Locale:  lo_LA
-lo_LA
-Lao (Laos)
-UTF-8
-
-OS Locale:  lt_LT
-lt_LT
-Lithuanian (Lithuania)
-ISO-8859-13
-
-OS Locale:  lt_LT.utf8
-lt_LT
-Lithuanian (Lithuania)
-UTF-8
-
-OS Locale:  lv_LV
-lv_LV
-Latvian (Latvia)
-ISO-8859-13
-
-OS Locale:  lv_LV.utf8
-lv_LV
-Latvian (Latvia)
-UTF-8
-
-OS Locale:  mi_NZ
-mi_NZ
-Maori (New Zealand)
-ISO-8859-13
-
-OS Locale:  mk_MK
-mk_MK
-Macedonian (Macedonia)
-ISO-8859-5
-
-OS Locale:  mk_MK.utf8
-mk_MK
-Macedonian (Macedonia)
-UTF-8
-
-OS Locale:  ml_IN
-ml_IN
-Malayalam (India)
-UTF-8
-
-OS Locale:  ml_IN.utf8
-ml_IN
-Malayalam (India)
-UTF-8
-
-OS Locale:  mn_MN
-mn_MN
-Mongolian (Mongolia)
-UTF-8
-
-OS Locale:  mn_MN.utf8
-mn_MN
-Mongolian (Mongolia)
-UTF-8
-
-OS Locale:  mr_IN
-mr_IN
-Marathi (India)
-UTF-8
-
-OS Locale:  mr_IN.utf8
-mr_IN
-Marathi (India)
-UTF-8
-
-OS Locale:  ms_MY
-ms_MY
-Malay (Malaysia)
-ISO-8859-1
-
-OS Locale:  ms_MY.utf8
-ms_MY
-Malay (Malaysia)
-UTF-8
-
-OS Locale:  mt_MT
-mt_MT
-Maltese (Malta)
-ISO-8859-3
-
-OS Locale:  mt_MT.utf8
-mt_MT
-Maltese (Malta)
-UTF-8
-
-OS Locale:  nb_NO
-nb_NO
-Norwegian Bokmål (Norway)
-ISO-8859-1
-
-OS Locale:  nb_NO.utf8
-nb_NO
-Norwegian Bokmål (Norway)
-UTF-8
-
-OS Locale:  ne_NP
-ne_NP
-Nepali (Nepal)
-UTF-8
-
-OS Locale:  ne_NP.utf8
-ne_NP
-Nepali (Nepal)
-UTF-8
-
-OS Locale:  nl_BE
-nl_BE
-Dutch (Belgium)
-ISO-8859-1
-
-OS Locale:  nl_BE.utf8
-nl_BE
-Dutch (Belgium)
-UTF-8
-
-OS Locale:  nl_BE@euro
-nl_BE
-Dutch (Belgium)
-ISO-8859-15
-
-OS Locale:  nl_NL
-nl_NL
-Dutch (Netherlands)
-ISO-8859-1
-
-OS Locale:  nl_NL.utf8
-nl_NL
-Dutch (Netherlands)
-UTF-8
-
-OS Locale:  nl_NL@euro
-nl_NL
-Dutch (Netherlands)
-ISO-8859-15
-
-OS Locale:  nn_NO
-nn_NO
-Norwegian Nynorsk (Norway)
-ISO-8859-1
-
-OS Locale:  nn_NO.utf8
-nn_NO
-Norwegian Nynorsk (Norway)
-UTF-8
-
-OS Locale:  no_NO
-no_NO
-Norwegian (Norway)
-ISO-8859-1
-
-OS Locale:  no_NO.utf8
-no_NO
-Norwegian (Norway)
-UTF-8
-
-OS Locale:  oc_FR
-oc_FR
-Occitan (France)
-ISO-8859-1
-
-OS Locale:  om_ET
-om_ET
-Oromo (Ethiopia)
-UTF-8
-
-OS Locale:  om_ET.utf8
-om_ET
-Oromo (Ethiopia)
-UTF-8
-
-OS Locale:  om_KE
-om_KE
-Oromo (Kenya)
-ISO-8859-1
-
-OS Locale:  pa_IN
-pa_IN
-Panjabi (India)
-UTF-8
-
-OS Locale:  pa_IN.utf8
-pa_IN
-Panjabi (India)
-UTF-8
-
-OS Locale:  pl_PL
-pl_PL
-Polish (Poland)
-ISO-8859-2
-
-OS Locale:  pl_PL.utf8
-pl_PL
-Polish (Poland)
-UTF-8
-
-OS Locale:  pt_BR
-pt_BR
-Portuguese (Brazil)
-ISO-8859-1
-
-OS Locale:  pt_BR.utf8
-pt_BR
-Portuguese (Brazil)
-UTF-8
-
-OS Locale:  pt_PT
-pt_PT
-Portuguese (Portugal)
-ISO-8859-1
-
-OS Locale:  pt_PT.utf8
-pt_PT
-Portuguese (Portugal)
-UTF-8
-
-OS Locale:  pt_PT@euro
-pt_PT
-Portuguese (Portugal)
-ISO-8859-15
-
-OS Locale:  ro_RO
-ro_RO
-Romanian (Romania)
-ISO-8859-2
-
-OS Locale:  ro_RO.utf8
-ro_RO
-Romanian (Romania)
-UTF-8
-
-OS Locale:  ru_RU
-ru_RU
-Russian (Russia)
-ISO-8859-5
-
-OS Locale:  ru_RU.koi8r
-ru_RU
-Russian (Russia)
-KOI8-R
-
-OS Locale:  ru_RU.utf8
-ru_RU
-Russian (Russia)
-UTF-8
-
-OS Locale:  ru_UA
-ru_UA
-Russian (Ukraine)
-KOI8-U
-
-OS Locale:  ru_UA.utf8
-ru_UA
-Russian (Ukraine)
-UTF-8
-
-OS Locale:  se_NO
-se_NO
-Northern Sami (Norway)
-UTF-8
-
-OS Locale:  se_NO.utf8
-se_NO
-Northern Sami (Norway)
-UTF-8
-
-OS Locale:  sh_YU
-sr_CS
-Serbian (Serbia and Montenegro)
-ISO-8859-2
-
-OS Locale:  sh_YU.utf8
-sr_CS
-Serbian (Serbia and Montenegro)
-UTF-8
-
-OS Locale:  sid_ET
-en_ET
-English (Ethiopia)
-UTF-8
-
-OS Locale:  sid_ET.utf8
-en_ET
-English (Ethiopia)
-UTF-8
-
-OS Locale:  sk_SK
-sk_SK
-Slovak (Slovakia)
-ISO-8859-2
-
-OS Locale:  sk_SK.utf8
-sk_SK
-Slovak (Slovakia)
-UTF-8
-
-OS Locale:  sl_SI
-sl_SI
-Slovenian (Slovenia)
-ISO-8859-2
-
-OS Locale:  sl_SI.utf8
-sl_SI
-Slovenian (Slovenia)
-UTF-8
-
-OS Locale:  so_DJ
-so_DJ
-Somali (Djibouti)
-ISO-8859-1
-
-OS Locale:  so_ET
-so_ET
-Somali (Ethiopia)
-UTF-8
-
-OS Locale:  so_ET.utf8
-so_ET
-Somali (Ethiopia)
-UTF-8
-
-OS Locale:  so_KE
-so_KE
-Somali (Kenya)
-ISO-8859-1
-
-OS Locale:  so_SO
-so_SO
-Somali (Somalia)
-ISO-8859-1
-
-OS Locale:  sq_AL
-sq_AL
-Albanian (Albania)
-ISO-8859-1
-
-OS Locale:  sq_AL.utf8
-sq_AL
-Albanian (Albania)
-UTF-8
-
-OS Locale:  sr_YU
-sr_CS
-Serbian (Serbia and Montenegro)
-ISO-8859-2
-
-OS Locale:  sr_YU.utf8
-sr_CS
-Serbian (Serbia and Montenegro)
-UTF-8
-
-OS Locale:  sr_YU.utf8@cyrillic
-sr_CS
-Serbian (Serbia and Montenegro)
-UTF-8
-
-OS Locale:  sr_YU@cyrillic
-sr_CS
-Serbian (Serbia and Montenegro)
-ISO-8859-5
-
-OS Locale:  st_ZA
-st_ZA
-Southern Sotho (South Africa)
-ISO-8859-1
-
-OS Locale:  st_ZA.utf8
-st_ZA
-Southern Sotho (South Africa)
-UTF-8
-
-OS Locale:  sv_FI
-sv_FI
-Swedish (Finland)
-ISO-8859-1
-
-OS Locale:  sv_FI.utf8
-sv_FI
-Swedish (Finland)
-UTF-8
-
-OS Locale:  sv_FI@euro
-sv_FI
-Swedish (Finland)
-ISO-8859-15
-
-OS Locale:  sv_SE
-sv_SE
-Swedish (Sweden)
-ISO-8859-1
-
-OS Locale:  sv_SE.iso885915
-sv_SE
-Swedish (Sweden)
-ISO-8859-15
-
-OS Locale:  sv_SE.utf8
-sv_SE
-Swedish (Sweden)
-UTF-8
-
-OS Locale:  ta_IN
-ta_IN
-Tamil (India)
-UTF-8
-
-OS Locale:  ta_IN.utf8
-ta_IN
-Tamil (India)
-UTF-8
-
-OS Locale:  te_IN
-te_IN
-Telugu (India)
-UTF-8
-
-OS Locale:  te_IN.utf8
-te_IN
-Telugu (India)
-UTF-8
-
-OS Locale:  tg_TJ
-tg_TJ
-Tajik (Tajikistan)
-UTF-8
-
-OS Locale:  th_TH
-th_TH
-Thai (Thailand)
-TIS-620
-
-OS Locale:  th_TH.utf8
-th_TH
-Thai (Thailand)
-UTF-8
-
-OS Locale:  ti_ER
-ti_ER
-Tigrinya (Eritrea)
-UTF-8
-
-OS Locale:  ti_ER.utf8
-ti_ER
-Tigrinya (Eritrea)
-UTF-8
-
-OS Locale:  ti_ET
-ti_ET
-Tigrinya (Ethiopia)
-UTF-8
-
-OS Locale:  ti_ET.utf8
-ti_ET
-Tigrinya (Ethiopia)
-UTF-8
-
-OS Locale:  tig_ER
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  tig_ER.utf8
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  tl_PH
-tl_PH
-Tagalog (Philippines)
-ISO-8859-1
-
-OS Locale:  tr_TR
-tr_TR
-Turkish (Turkey)
-ISO-8859-9
-
-OS Locale:  tr_TR.utf8
-tr_TR
-Turkish (Turkey)
-UTF-8
-
-OS Locale:  tt_RU.utf8
-tt_RU
-Tatar (Russia)
-UTF-8
-
-OS Locale:  uk_UA
-uk_UA
-Ukrainian (Ukraine)
-KOI8-U
-
-OS Locale:  uk_UA.utf8
-uk_UA
-Ukrainian (Ukraine)
-UTF-8
-
-OS Locale:  ur_PK
-ur_PK
-Urdu (Pakistan)
-UTF-8
-
-OS Locale:  ur_PK.utf8
-ur_PK
-Urdu (Pakistan)
-UTF-8
-
-OS Locale:  uz_UZ
-uz_UZ
-Uzbek (Uzbekistan)
-ISO-8859-1
-
-OS Locale:  uz_UZ@cyrillic
-uz_UZ
-Uzbek (Uzbekistan)
-UTF-8
-
-OS Locale:  vi_VN
-vi_VN
-Vietnamese (Vietnam)
-UTF-8
-
-OS Locale:  vi_VN.tcvn
-vi_VN
-Vietnamese (Vietnam)
-UTF-8
-
-OS Locale:  vi_VN.utf8
-vi_VN
-Vietnamese (Vietnam)
-UTF-8
-
-OS Locale:  wa_BE
-wa_BE
-Walloon (Belgium)
-ISO-8859-1
-
-OS Locale:  wa_BE.utf8
-wa_BE
-Walloon (Belgium)
-UTF-8
-
-OS Locale:  wa_BE@euro
-wa_BE
-Walloon (Belgium)
-ISO-8859-15
-
-OS Locale:  xh_ZA
-xh_ZA
-Xhosa (South Africa)
-ISO-8859-1
-
-OS Locale:  xh_ZA.utf8
-xh_ZA
-Xhosa (South Africa)
-UTF-8
-
-OS Locale:  yi_US
-ji_US
-Yiddish (United States)
-windows-1255
-
-OS Locale:  zh_CN
-zh_CN
-Chinese (China)
-GB2312
-
-OS Locale:  zh_CN.gb18030
-zh_CN
-Chinese (China)
-GB18030
-
-OS Locale:  zh_CN.gbk
-zh_CN
-Chinese (China)
-GBK
-
-OS Locale:  zh_CN.utf8
-zh_CN
-Chinese (China)
-UTF-8
-
-OS Locale:  zh_HK
-zh_HK
-Chinese (Hong Kong)
-Big5-HKSCS
-
-OS Locale:  zh_HK.utf8
-zh_HK
-Chinese (Hong Kong)
-UTF-8
-
-OS Locale:  zh_SG
-zh_SG
-Chinese (Singapore)
-GB2312
-
-OS Locale:  zh_SG.gbk
-zh_SG
-Chinese (Singapore)
-GBK
-
-OS Locale:  zh_TW
-zh_TW
-Chinese (Taiwan)
-Big5
-
-OS Locale:  zh_TW.euctw
-zh_TW
-Chinese (Taiwan)
-x-EUC-TW
-
-OS Locale:  zh_TW.utf8
-zh_TW
-Chinese (Taiwan)
-UTF-8
-
-OS Locale:  zu_ZA
-zu_ZA
-Zulu (South Africa)
-ISO-8859-1
-
-OS Locale:  zu_ZA.utf8
-zu_ZA
-Zulu (South Africa)
-UTF-8
--- a/test/java/util/Locale/data/deflocale.rhel4	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1623 +0,0 @@
-LSB_VERSION="1.3"
-Red Hat Enterprise Linux AS release 4 (Nahant Update 1)
-Linux i18n-hp733-6.sfbay.sun.com 2.6.9-6.37.EL #1 Tue Mar 29 15:34:14 EST 2005 i686 i686 i386 GNU/Linux
-
-OS Locale:  aa_DJ
-aa_DJ
-Afar (Djibouti)
-ISO-8859-1
-
-OS Locale:  aa_ER
-aa_ER
-Afar (Eritrea)
-UTF-8
-
-OS Locale:  aa_ER@saaho
-aa_ER
-Afar (Eritrea)
-UTF-8
-
-OS Locale:  aa_ET
-aa_ET
-Afar (Ethiopia)
-UTF-8
-
-OS Locale:  af_ZA
-af_ZA
-Afrikaans (South Africa)
-ISO-8859-1
-
-OS Locale:  am_ET
-am_ET
-Amharic (Ethiopia)
-UTF-8
-
-OS Locale:  an_ES
-an_ES
-Aragonese (Spain)
-ISO-8859-15
-
-OS Locale:  ar_AE
-ar_AE
-Arabic (United Arab Emirates)
-ISO-8859-6
-
-OS Locale:  ar_AE.utf8
-ar_AE
-Arabic (United Arab Emirates)
-UTF-8
-
-OS Locale:  ar_BH
-ar_BH
-Arabic (Bahrain)
-ISO-8859-6
-
-OS Locale:  ar_BH.utf8
-ar_BH
-Arabic (Bahrain)
-UTF-8
-
-OS Locale:  ar_DZ
-ar_DZ
-Arabic (Algeria)
-ISO-8859-6
-
-OS Locale:  ar_DZ.utf8
-ar_DZ
-Arabic (Algeria)
-UTF-8
-
-OS Locale:  ar_EG
-ar_EG
-Arabic (Egypt)
-ISO-8859-6
-
-OS Locale:  ar_EG.utf8
-ar_EG
-Arabic (Egypt)
-UTF-8
-
-OS Locale:  ar_IN
-ar_IN
-Arabic (India)
-UTF-8
-
-OS Locale:  ar_IQ
-ar_IQ
-Arabic (Iraq)
-ISO-8859-6
-
-OS Locale:  ar_IQ.utf8
-ar_IQ
-Arabic (Iraq)
-UTF-8
-
-OS Locale:  ar_JO
-ar_JO
-Arabic (Jordan)
-ISO-8859-6
-
-OS Locale:  ar_JO.utf8
-ar_JO
-Arabic (Jordan)
-UTF-8
-
-OS Locale:  ar_KW
-ar_KW
-Arabic (Kuwait)
-ISO-8859-6
-
-OS Locale:  ar_KW.utf8
-ar_KW
-Arabic (Kuwait)
-UTF-8
-
-OS Locale:  ar_LB
-ar_LB
-Arabic (Lebanon)
-ISO-8859-6
-
-OS Locale:  ar_LB.utf8
-ar_LB
-Arabic (Lebanon)
-UTF-8
-
-OS Locale:  ar_LY
-ar_LY
-Arabic (Libya)
-ISO-8859-6
-
-OS Locale:  ar_LY.utf8
-ar_LY
-Arabic (Libya)
-UTF-8
-
-OS Locale:  ar_MA
-ar_MA
-Arabic (Morocco)
-ISO-8859-6
-
-OS Locale:  ar_MA.utf8
-ar_MA
-Arabic (Morocco)
-UTF-8
-
-OS Locale:  ar_OM
-ar_OM
-Arabic (Oman)
-ISO-8859-6
-
-OS Locale:  ar_OM.utf8
-ar_OM
-Arabic (Oman)
-UTF-8
-
-OS Locale:  ar_QA
-ar_QA
-Arabic (Qatar)
-ISO-8859-6
-
-OS Locale:  ar_QA.utf8
-ar_QA
-Arabic (Qatar)
-UTF-8
-
-OS Locale:  ar_SA
-ar_SA
-Arabic (Saudi Arabia)
-ISO-8859-6
-
-OS Locale:  ar_SA.utf8
-ar_SA
-Arabic (Saudi Arabia)
-UTF-8
-
-OS Locale:  ar_SD
-ar_SD
-Arabic (Sudan)
-ISO-8859-6
-
-OS Locale:  ar_SD.utf8
-ar_SD
-Arabic (Sudan)
-UTF-8
-
-OS Locale:  ar_SY
-ar_SY
-Arabic (Syria)
-ISO-8859-6
-
-OS Locale:  ar_SY.utf8
-ar_SY
-Arabic (Syria)
-UTF-8
-
-OS Locale:  ar_TN
-ar_TN
-Arabic (Tunisia)
-ISO-8859-6
-
-OS Locale:  ar_TN.utf8
-ar_TN
-Arabic (Tunisia)
-UTF-8
-
-OS Locale:  ar_YE
-ar_YE
-Arabic (Yemen)
-ISO-8859-6
-
-OS Locale:  ar_YE.utf8
-ar_YE
-Arabic (Yemen)
-UTF-8
-
-OS Locale:  az_AZ.utf8
-az_AZ
-Azerbaijani (Azerbaijan)
-UTF-8
-
-OS Locale:  be_BY
-be_BY
-Belarusian (Belarus)
-windows-1251
-
-OS Locale:  be_BY.utf8
-be_BY
-Belarusian (Belarus)
-UTF-8
-
-OS Locale:  bg_BG
-bg_BG
-Bulgarian (Bulgaria)
-windows-1251
-
-OS Locale:  bg_BG.utf8
-bg_BG
-Bulgarian (Bulgaria)
-UTF-8
-
-OS Locale:  bn_BD
-bn_BD
-Bengali (Bangladesh)
-UTF-8
-
-OS Locale:  bn_IN
-bn_IN
-Bengali (India)
-UTF-8
-
-OS Locale:  br_FR
-br_FR
-Breton (France)
-ISO-8859-1
-
-OS Locale:  br_FR@euro
-br_FR
-Breton (France)
-ISO-8859-15
-
-OS Locale:  bs_BA
-bs_BA
-Bosnian (Bosnia and Herzegovina)
-ISO-8859-2
-
-OS Locale:  byn_ER
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  ca_ES
-ca_ES
-Catalan (Spain)
-ISO-8859-1
-
-OS Locale:  ca_ES.utf8
-ca_ES
-Catalan (Spain)
-UTF-8
-
-OS Locale:  ca_ES@euro
-ca_ES
-Catalan (Spain)
-ISO-8859-15
-
-OS Locale:  cs_CZ
-cs_CZ
-Czech (Czech Republic)
-ISO-8859-2
-
-OS Locale:  cs_CZ.utf8
-cs_CZ
-Czech (Czech Republic)
-UTF-8
-
-OS Locale:  cy_GB
-cy_GB
-Welsh (United Kingdom)
-UTF-8
-
-OS Locale:  cy_GB.utf8
-cy_GB
-Welsh (United Kingdom)
-UTF-8
-
-OS Locale:  da_DK
-da_DK
-Danish (Denmark)
-ISO-8859-1
-
-OS Locale:  da_DK.iso885915
-da_DK
-Danish (Denmark)
-ISO-8859-15
-
-OS Locale:  da_DK.utf8
-da_DK
-Danish (Denmark)
-UTF-8
-
-OS Locale:  de_AT
-de_AT
-German (Austria)
-ISO-8859-1
-
-OS Locale:  de_AT.utf8
-de_AT
-German (Austria)
-UTF-8
-
-OS Locale:  de_AT@euro
-de_AT
-German (Austria)
-ISO-8859-15
-
-OS Locale:  de_BE
-de_BE
-German (Belgium)
-ISO-8859-1
-
-OS Locale:  de_BE.utf8
-de_BE
-German (Belgium)
-UTF-8
-
-OS Locale:  de_BE@euro
-de_BE
-German (Belgium)
-ISO-8859-15
-
-OS Locale:  de_CH
-de_CH
-German (Switzerland)
-ISO-8859-1
-
-OS Locale:  de_CH.utf8
-de_CH
-German (Switzerland)
-UTF-8
-
-OS Locale:  de_DE
-de_DE
-German (Germany)
-ISO-8859-1
-
-OS Locale:  de_DE.utf8
-de_DE
-German (Germany)
-UTF-8
-
-OS Locale:  de_DE@euro
-de_DE
-German (Germany)
-ISO-8859-15
-
-OS Locale:  de_LU
-de_LU
-German (Luxembourg)
-ISO-8859-1
-
-OS Locale:  de_LU.utf8
-de_LU
-German (Luxembourg)
-UTF-8
-
-OS Locale:  de_LU@euro
-de_LU
-German (Luxembourg)
-ISO-8859-15
-
-OS Locale:  el_GR
-el_GR
-Greek (Greece)
-ISO-8859-7
-
-OS Locale:  el_GR.utf8
-el_GR
-Greek (Greece)
-UTF-8
-
-OS Locale:  en_AU
-en_AU
-English (Australia)
-ISO-8859-1
-
-OS Locale:  en_AU.utf8
-en_AU
-English (Australia)
-UTF-8
-
-OS Locale:  en_BW
-en_BW
-English (Botswana)
-ISO-8859-1
-
-OS Locale:  en_BW.utf8
-en_BW
-English (Botswana)
-UTF-8
-
-OS Locale:  en_CA
-en_CA
-English (Canada)
-ISO-8859-1
-
-OS Locale:  en_CA.utf8
-en_CA
-English (Canada)
-UTF-8
-
-OS Locale:  en_DK
-en_DK
-English (Denmark)
-ISO-8859-1
-
-OS Locale:  en_DK.utf8
-en_DK
-English (Denmark)
-UTF-8
-
-OS Locale:  en_GB
-en_GB
-English (United Kingdom)
-ISO-8859-1
-
-OS Locale:  en_GB.iso885915
-en_GB
-English (United Kingdom)
-ISO-8859-15
-
-OS Locale:  en_GB.utf8
-en_GB
-English (United Kingdom)
-UTF-8
-
-OS Locale:  en_HK
-en_HK
-English (Hong Kong)
-ISO-8859-1
-
-OS Locale:  en_HK.utf8
-en_HK
-English (Hong Kong)
-UTF-8
-
-OS Locale:  en_IE
-en_IE
-English (Ireland)
-ISO-8859-1
-
-OS Locale:  en_IE.utf8
-en_IE
-English (Ireland)
-UTF-8
-
-OS Locale:  en_IE@euro
-en_IE
-English (Ireland)
-ISO-8859-15
-
-OS Locale:  en_IN
-en_IN
-English (India)
-UTF-8
-
-OS Locale:  en_NZ
-en_NZ
-English (New Zealand)
-ISO-8859-1
-
-OS Locale:  en_NZ.utf8
-en_NZ
-English (New Zealand)
-UTF-8
-
-OS Locale:  en_PH
-en_PH
-English (Philippines)
-ISO-8859-1
-
-OS Locale:  en_PH.utf8
-en_PH
-English (Philippines)
-UTF-8
-
-OS Locale:  en_SG
-en_SG
-English (Singapore)
-ISO-8859-1
-
-OS Locale:  en_SG.utf8
-en_SG
-English (Singapore)
-UTF-8
-
-OS Locale:  en_US
-en_US
-English (United States)
-ISO-8859-1
-
-OS Locale:  en_US.iso885915
-en_US
-English (United States)
-ISO-8859-15
-
-OS Locale:  en_US.utf8
-en_US
-English (United States)
-UTF-8
-
-OS Locale:  en_ZA
-en_ZA
-English (South Africa)
-ISO-8859-1
-
-OS Locale:  en_ZA.utf8
-en_ZA
-English (South Africa)
-UTF-8
-
-OS Locale:  en_ZW
-en_ZW
-English (Zimbabwe)
-ISO-8859-1
-
-OS Locale:  en_ZW.utf8
-en_ZW
-English (Zimbabwe)
-UTF-8
-
-OS Locale:  es_AR
-es_AR
-Spanish (Argentina)
-ISO-8859-1
-
-OS Locale:  es_AR.utf8
-es_AR
-Spanish (Argentina)
-UTF-8
-
-OS Locale:  es_BO
-es_BO
-Spanish (Bolivia)
-ISO-8859-1
-
-OS Locale:  es_BO.utf8
-es_BO
-Spanish (Bolivia)
-UTF-8
-
-OS Locale:  es_CL
-es_CL
-Spanish (Chile)
-ISO-8859-1
-
-OS Locale:  es_CL.utf8
-es_CL
-Spanish (Chile)
-UTF-8
-
-OS Locale:  es_CO
-es_CO
-Spanish (Colombia)
-ISO-8859-1
-
-OS Locale:  es_CO.utf8
-es_CO
-Spanish (Colombia)
-UTF-8
-
-OS Locale:  es_CR
-es_CR
-Spanish (Costa Rica)
-ISO-8859-1
-
-OS Locale:  es_CR.utf8
-es_CR
-Spanish (Costa Rica)
-UTF-8
-
-OS Locale:  es_DO
-es_DO
-Spanish (Dominican Republic)
-ISO-8859-1
-
-OS Locale:  es_DO.utf8
-es_DO
-Spanish (Dominican Republic)
-UTF-8
-
-OS Locale:  es_EC
-es_EC
-Spanish (Ecuador)
-ISO-8859-1
-
-OS Locale:  es_EC.utf8
-es_EC
-Spanish (Ecuador)
-UTF-8
-
-OS Locale:  es_ES
-es_ES
-Spanish (Spain)
-ISO-8859-1
-
-OS Locale:  es_ES.utf8
-es_ES
-Spanish (Spain)
-UTF-8
-
-OS Locale:  es_ES@euro
-es_ES
-Spanish (Spain)
-ISO-8859-15
-
-OS Locale:  es_GT
-es_GT
-Spanish (Guatemala)
-ISO-8859-1
-
-OS Locale:  es_GT.utf8
-es_GT
-Spanish (Guatemala)
-UTF-8
-
-OS Locale:  es_HN
-es_HN
-Spanish (Honduras)
-ISO-8859-1
-
-OS Locale:  es_HN.utf8
-es_HN
-Spanish (Honduras)
-UTF-8
-
-OS Locale:  es_MX
-es_MX
-Spanish (Mexico)
-ISO-8859-1
-
-OS Locale:  es_MX.utf8
-es_MX
-Spanish (Mexico)
-UTF-8
-
-OS Locale:  es_NI
-es_NI
-Spanish (Nicaragua)
-ISO-8859-1
-
-OS Locale:  es_NI.utf8
-es_NI
-Spanish (Nicaragua)
-UTF-8
-
-OS Locale:  es_PA
-es_PA
-Spanish (Panama)
-ISO-8859-1
-
-OS Locale:  es_PA.utf8
-es_PA
-Spanish (Panama)
-UTF-8
-
-OS Locale:  es_PE
-es_PE
-Spanish (Peru)
-ISO-8859-1
-
-OS Locale:  es_PE.utf8
-es_PE
-Spanish (Peru)
-UTF-8
-
-OS Locale:  es_PR
-es_PR
-Spanish (Puerto Rico)
-ISO-8859-1
-
-OS Locale:  es_PR.utf8
-es_PR
-Spanish (Puerto Rico)
-UTF-8
-
-OS Locale:  es_PY
-es_PY
-Spanish (Paraguay)
-ISO-8859-1
-
-OS Locale:  es_PY.utf8
-es_PY
-Spanish (Paraguay)
-UTF-8
-
-OS Locale:  es_SV
-es_SV
-Spanish (El Salvador)
-ISO-8859-1
-
-OS Locale:  es_SV.utf8
-es_SV
-Spanish (El Salvador)
-UTF-8
-
-OS Locale:  es_US
-es_US
-Spanish (United States)
-ISO-8859-1
-
-OS Locale:  es_US.utf8
-es_US
-Spanish (United States)
-UTF-8
-
-OS Locale:  es_UY
-es_UY
-Spanish (Uruguay)
-ISO-8859-1
-
-OS Locale:  es_UY.utf8
-es_UY
-Spanish (Uruguay)
-UTF-8
-
-OS Locale:  es_VE
-es_VE
-Spanish (Venezuela)
-ISO-8859-1
-
-OS Locale:  es_VE.utf8
-es_VE
-Spanish (Venezuela)
-UTF-8
-
-OS Locale:  et_EE
-et_EE
-Estonian (Estonia)
-ISO-8859-1
-
-OS Locale:  et_EE.iso885915
-et_EE
-Estonian (Estonia)
-ISO-8859-15
-
-OS Locale:  et_EE.utf8
-et_EE
-Estonian (Estonia)
-UTF-8
-
-OS Locale:  eu_ES
-eu_ES
-Basque (Spain)
-ISO-8859-1
-
-OS Locale:  eu_ES.utf8
-eu_ES
-Basque (Spain)
-UTF-8
-
-OS Locale:  eu_ES@euro
-eu_ES
-Basque (Spain)
-ISO-8859-15
-
-OS Locale:  fa_IR
-fa_IR
-Persian (Iran)
-UTF-8
-
-OS Locale:  fi_FI
-fi_FI
-Finnish (Finland)
-ISO-8859-1
-
-OS Locale:  fi_FI.utf8
-fi_FI
-Finnish (Finland)
-UTF-8
-
-OS Locale:  fi_FI@euro
-fi_FI
-Finnish (Finland)
-ISO-8859-15
-
-OS Locale:  fo_FO
-fo_FO
-Faroese (Faroe Islands)
-ISO-8859-1
-
-OS Locale:  fo_FO.utf8
-fo_FO
-Faroese (Faroe Islands)
-UTF-8
-
-OS Locale:  fr_BE
-fr_BE
-French (Belgium)
-ISO-8859-1
-
-OS Locale:  fr_BE.utf8
-fr_BE
-French (Belgium)
-UTF-8
-
-OS Locale:  fr_BE@euro
-fr_BE
-French (Belgium)
-ISO-8859-15
-
-OS Locale:  fr_CA
-fr_CA
-French (Canada)
-ISO-8859-1
-
-OS Locale:  fr_CA.utf8
-fr_CA
-French (Canada)
-UTF-8
-
-OS Locale:  fr_CH
-fr_CH
-French (Switzerland)
-ISO-8859-1
-
-OS Locale:  fr_CH.utf8
-fr_CH
-French (Switzerland)
-UTF-8
-
-OS Locale:  fr_FR
-fr_FR
-French (France)
-ISO-8859-1
-
-OS Locale:  fr_FR.utf8
-fr_FR
-French (France)
-UTF-8
-
-OS Locale:  fr_FR@euro
-fr_FR
-French (France)
-ISO-8859-15
-
-OS Locale:  fr_LU
-fr_LU
-French (Luxembourg)
-ISO-8859-1
-
-OS Locale:  fr_LU.utf8
-fr_LU
-French (Luxembourg)
-UTF-8
-
-OS Locale:  fr_LU@euro
-fr_LU
-French (Luxembourg)
-ISO-8859-15
-
-OS Locale:  ga_IE
-ga_IE
-Irish (Ireland)
-ISO-8859-1
-
-OS Locale:  ga_IE.utf8
-ga_IE
-Irish (Ireland)
-UTF-8
-
-OS Locale:  ga_IE@euro
-ga_IE
-Irish (Ireland)
-ISO-8859-15
-
-OS Locale:  gd_GB
-gd_GB
-Scottish Gaelic (United Kingdom)
-ISO-8859-15
-
-OS Locale:  gez_ER
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  gez_ER@abegede
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  gez_ET
-en_ET
-English (Ethiopia)
-UTF-8
-
-OS Locale:  gez_ET@abegede
-en_ET
-English (Ethiopia)
-UTF-8
-
-OS Locale:  gl_ES
-gl_ES
-Gallegan (Spain)
-ISO-8859-1
-
-OS Locale:  gl_ES.utf8
-gl_ES
-Gallegan (Spain)
-UTF-8
-
-OS Locale:  gl_ES@euro
-gl_ES
-Gallegan (Spain)
-ISO-8859-15
-
-OS Locale:  gu_IN
-gu_IN
-Gujarati (India)
-UTF-8
-
-OS Locale:  gv_GB
-gv_GB
-Manx (United Kingdom)
-ISO-8859-1
-
-OS Locale:  gv_GB.utf8
-gv_GB
-Manx (United Kingdom)
-UTF-8
-
-OS Locale:  he_IL
-iw_IL
-Hebrew (Israel)
-ISO-8859-8
-
-OS Locale:  he_IL.utf8
-iw_IL
-Hebrew (Israel)
-UTF-8
-
-OS Locale:  hi_IN
-hi_IN
-Hindi (India)
-UTF-8
-
-OS Locale:  hr_HR
-hr_HR
-Croatian (Croatia)
-ISO-8859-2
-
-OS Locale:  hr_HR.utf8
-hr_HR
-Croatian (Croatia)
-UTF-8
-
-OS Locale:  hu_HU
-hu_HU
-Hungarian (Hungary)
-ISO-8859-2
-
-OS Locale:  hu_HU.utf8
-hu_HU
-Hungarian (Hungary)
-UTF-8
-
-OS Locale:  id_ID
-in_ID
-Indonesian (Indonesia)
-ISO-8859-1
-
-OS Locale:  id_ID.utf8
-in_ID
-Indonesian (Indonesia)
-UTF-8
-
-OS Locale:  is_IS
-is_IS
-Icelandic (Iceland)
-ISO-8859-1
-
-OS Locale:  is_IS.utf8
-is_IS
-Icelandic (Iceland)
-UTF-8
-
-OS Locale:  it_CH
-it_CH
-Italian (Switzerland)
-ISO-8859-1
-
-OS Locale:  it_CH.utf8
-it_CH
-Italian (Switzerland)
-UTF-8
-
-OS Locale:  it_IT
-it_IT
-Italian (Italy)
-ISO-8859-1
-
-OS Locale:  it_IT.utf8
-it_IT
-Italian (Italy)
-UTF-8
-
-OS Locale:  it_IT@euro
-it_IT
-Italian (Italy)
-ISO-8859-15
-
-OS Locale:  iw_IL
-iw_IL
-Hebrew (Israel)
-ISO-8859-8
-
-OS Locale:  iw_IL.utf8
-iw_IL
-Hebrew (Israel)
-UTF-8
-
-OS Locale:  ja_JP.eucjp
-ja_JP
-Japanese (Japan)
-x-euc-jp-linux
-
-OS Locale:  ja_JP.utf8
-ja_JP
-Japanese (Japan)
-UTF-8
-
-OS Locale:  ka_GE
-ka_GE
-Georgian (Georgia)
-UTF-8
-
-OS Locale:  kk_KZ
-kk_KZ
-Kazakh (Kazakhstan)
-UTF-8
-
-OS Locale:  kl_GL
-kl_GL
-Greenlandic (Greenland)
-ISO-8859-1
-
-OS Locale:  kl_GL.utf8
-kl_GL
-Greenlandic (Greenland)
-UTF-8
-
-OS Locale:  kn_IN
-kn_IN
-Kannada (India)
-UTF-8
-
-OS Locale:  ko_KR.euckr
-ko_KR
-Korean (South Korea)
-EUC-KR
-
-OS Locale:  ko_KR.utf8
-ko_KR
-Korean (South Korea)
-UTF-8
-
-OS Locale:  kw_GB
-kw_GB
-Cornish (United Kingdom)
-ISO-8859-1
-
-OS Locale:  kw_GB.utf8
-kw_GB
-Cornish (United Kingdom)
-UTF-8
-
-OS Locale:  lg_UG
-lg_UG
-Ganda (Uganda)
-UTF-8
-
-OS Locale:  lo_LA
-lo_LA
-Lao (Laos)
-UTF-8
-
-OS Locale:  locale-archive
-en_US
-English (United States)
-US-ASCII
-
-OS Locale:  lt_LT
-lt_LT
-Lithuanian (Lithuania)
-ISO-8859-13
-
-OS Locale:  lt_LT.utf8
-lt_LT
-Lithuanian (Lithuania)
-UTF-8
-
-OS Locale:  lv_LV
-lv_LV
-Latvian (Latvia)
-ISO-8859-13
-
-OS Locale:  lv_LV.utf8
-lv_LV
-Latvian (Latvia)
-UTF-8
-
-OS Locale:  mi_NZ
-mi_NZ
-Maori (New Zealand)
-ISO-8859-13
-
-OS Locale:  mk_MK
-mk_MK
-Macedonian (Macedonia)
-ISO-8859-5
-
-OS Locale:  mk_MK.utf8
-mk_MK
-Macedonian (Macedonia)
-UTF-8
-
-OS Locale:  ml_IN
-ml_IN
-Malayalam (India)
-UTF-8
-
-OS Locale:  mn_MN
-mn_MN
-Mongolian (Mongolia)
-UTF-8
-
-OS Locale:  mr_IN
-mr_IN
-Marathi (India)
-UTF-8
-
-OS Locale:  ms_MY
-ms_MY
-Malay (Malaysia)
-ISO-8859-1
-
-OS Locale:  ms_MY.utf8
-ms_MY
-Malay (Malaysia)
-UTF-8
-
-OS Locale:  mt_MT
-mt_MT
-Maltese (Malta)
-ISO-8859-3
-
-OS Locale:  mt_MT.utf8
-mt_MT
-Maltese (Malta)
-UTF-8
-
-OS Locale:  nb_NO
-nb_NO
-Norwegian Bokmål (Norway)
-ISO-8859-1
-
-OS Locale:  nb_NO.utf8
-nb_NO
-Norwegian Bokmål (Norway)
-UTF-8
-
-OS Locale:  ne_NP
-ne_NP
-Nepali (Nepal)
-UTF-8
-
-OS Locale:  nl_BE
-nl_BE
-Dutch (Belgium)
-ISO-8859-1
-
-OS Locale:  nl_BE.utf8
-nl_BE
-Dutch (Belgium)
-UTF-8
-
-OS Locale:  nl_BE@euro
-nl_BE
-Dutch (Belgium)
-ISO-8859-15
-
-OS Locale:  nl_NL
-nl_NL
-Dutch (Netherlands)
-ISO-8859-1
-
-OS Locale:  nl_NL.utf8
-nl_NL
-Dutch (Netherlands)
-UTF-8
-
-OS Locale:  nl_NL@euro
-nl_NL
-Dutch (Netherlands)
-ISO-8859-15
-
-OS Locale:  nn_NO
-nn_NO
-Norwegian Nynorsk (Norway)
-ISO-8859-1
-
-OS Locale:  nn_NO.utf8
-nn_NO
-Norwegian Nynorsk (Norway)
-UTF-8
-
-OS Locale:  no_NO
-no_NO
-Norwegian (Norway)
-ISO-8859-1
-
-OS Locale:  no_NO.utf8
-no_NO
-Norwegian (Norway)
-UTF-8
-
-OS Locale:  oc_FR
-oc_FR
-Occitan (France)
-ISO-8859-1
-
-OS Locale:  om_ET
-om_ET
-Oromo (Ethiopia)
-UTF-8
-
-OS Locale:  om_KE
-om_KE
-Oromo (Kenya)
-ISO-8859-1
-
-OS Locale:  pa_IN
-pa_IN
-Panjabi (India)
-UTF-8
-
-OS Locale:  pl_PL
-pl_PL
-Polish (Poland)
-ISO-8859-2
-
-OS Locale:  pl_PL.utf8
-pl_PL
-Polish (Poland)
-UTF-8
-
-OS Locale:  pt_BR
-pt_BR
-Portuguese (Brazil)
-ISO-8859-1
-
-OS Locale:  pt_BR.utf8
-pt_BR
-Portuguese (Brazil)
-UTF-8
-
-OS Locale:  pt_PT
-pt_PT
-Portuguese (Portugal)
-ISO-8859-1
-
-OS Locale:  pt_PT.utf8
-pt_PT
-Portuguese (Portugal)
-UTF-8
-
-OS Locale:  pt_PT@euro
-pt_PT
-Portuguese (Portugal)
-ISO-8859-15
-
-OS Locale:  ro_RO
-ro_RO
-Romanian (Romania)
-ISO-8859-2
-
-OS Locale:  ro_RO.utf8
-ro_RO
-Romanian (Romania)
-UTF-8
-
-OS Locale:  ru_RU
-ru_RU
-Russian (Russia)
-ISO-8859-5
-
-OS Locale:  ru_RU.koi8r
-ru_RU
-Russian (Russia)
-KOI8-R
-
-OS Locale:  ru_RU.utf8
-ru_RU
-Russian (Russia)
-UTF-8
-
-OS Locale:  ru_UA
-ru_UA
-Russian (Ukraine)
-KOI8-U
-
-OS Locale:  ru_UA.utf8
-ru_UA
-Russian (Ukraine)
-UTF-8
-
-OS Locale:  se_NO
-se_NO
-Northern Sami (Norway)
-UTF-8
-
-OS Locale:  sid_ET
-en_ET
-English (Ethiopia)
-UTF-8
-
-OS Locale:  sk_SK
-sk_SK
-Slovak (Slovakia)
-ISO-8859-2
-
-OS Locale:  sk_SK.utf8
-sk_SK
-Slovak (Slovakia)
-UTF-8
-
-OS Locale:  sl_SI
-sl_SI
-Slovenian (Slovenia)
-ISO-8859-2
-
-OS Locale:  sl_SI.utf8
-sl_SI
-Slovenian (Slovenia)
-UTF-8
-
-OS Locale:  so_DJ
-so_DJ
-Somali (Djibouti)
-ISO-8859-1
-
-OS Locale:  so_ET
-so_ET
-Somali (Ethiopia)
-UTF-8
-
-OS Locale:  so_KE
-so_KE
-Somali (Kenya)
-ISO-8859-1
-
-OS Locale:  so_SO
-so_SO
-Somali (Somalia)
-ISO-8859-1
-
-OS Locale:  sq_AL
-sq_AL
-Albanian (Albania)
-ISO-8859-1
-
-OS Locale:  sq_AL.utf8
-sq_AL
-Albanian (Albania)
-UTF-8
-
-OS Locale:  st_ZA
-st_ZA
-Southern Sotho (South Africa)
-ISO-8859-1
-
-OS Locale:  st_ZA.utf8
-st_ZA
-Southern Sotho (South Africa)
-UTF-8
-
-OS Locale:  sv_FI
-sv_FI
-Swedish (Finland)
-ISO-8859-1
-
-OS Locale:  sv_FI.utf8
-sv_FI
-Swedish (Finland)
-UTF-8
-
-OS Locale:  sv_FI@euro
-sv_FI
-Swedish (Finland)
-ISO-8859-15
-
-OS Locale:  sv_SE
-sv_SE
-Swedish (Sweden)
-ISO-8859-1
-
-OS Locale:  sv_SE.iso885915
-sv_SE
-Swedish (Sweden)
-ISO-8859-15
-
-OS Locale:  sv_SE.utf8
-sv_SE
-Swedish (Sweden)
-UTF-8
-
-OS Locale:  ta_IN
-ta_IN
-Tamil (India)
-UTF-8
-
-OS Locale:  te_IN
-te_IN
-Telugu (India)
-UTF-8
-
-OS Locale:  tg_TJ
-tg_TJ
-Tajik (Tajikistan)
-UTF-8
-
-OS Locale:  th_TH
-th_TH
-Thai (Thailand)
-TIS-620
-
-OS Locale:  th_TH.utf8
-th_TH
-Thai (Thailand)
-UTF-8
-
-OS Locale:  ti_ER
-ti_ER
-Tigrinya (Eritrea)
-UTF-8
-
-OS Locale:  ti_ET
-ti_ET
-Tigrinya (Ethiopia)
-UTF-8
-
-OS Locale:  tig_ER
-en_ER
-English (Eritrea)
-UTF-8
-
-OS Locale:  tl_PH
-tl_PH
-Tagalog (Philippines)
-ISO-8859-1
-
-OS Locale:  tr_TR
-tr_TR
-Turkish (Turkey)
-ISO-8859-9
-
-OS Locale:  tr_TR.utf8
-tr_TR
-Turkish (Turkey)
-UTF-8
-
-OS Locale:  tt_RU.utf8
-tt_RU
-Tatar (Russia)
-UTF-8
-
-OS Locale:  uk_UA
-uk_UA
-Ukrainian (Ukraine)
-KOI8-U
-
-OS Locale:  uk_UA.utf8
-uk_UA
-Ukrainian (Ukraine)
-UTF-8
-
-OS Locale:  ur_PK
-ur_PK
-Urdu (Pakistan)
-UTF-8
-
-OS Locale:  uz_UZ
-uz_UZ
-Uzbek (Uzbekistan)
-ISO-8859-1
-
-OS Locale:  uz_UZ@cyrillic
-uz_UZ
-Uzbek (Uzbekistan)
-UTF-8
-
-OS Locale:  vi_VN
-vi_VN
-Vietnamese (Vietnam)
-UTF-8
-
-OS Locale:  vi_VN.tcvn
-vi_VN
-Vietnamese (Vietnam)
-UTF-8
-
-OS Locale:  wa_BE
-wa_BE
-Walloon (Belgium)
-ISO-8859-1
-
-OS Locale:  wa_BE.utf8
-wa_BE
-Walloon (Belgium)
-UTF-8
-
-OS Locale:  wa_BE@euro
-wa_BE
-Walloon (Belgium)
-ISO-8859-15
-
-OS Locale:  xh_ZA
-xh_ZA
-Xhosa (South Africa)
-ISO-8859-1
-
-OS Locale:  xh_ZA.utf8
-xh_ZA
-Xhosa (South Africa)
-UTF-8
-
-OS Locale:  yi_US
-ji_US
-Yiddish (United States)
-windows-1255
-
-OS Locale:  zh_CN
-zh_CN
-Chinese (China)
-GB2312
-
-OS Locale:  zh_CN.gb18030
-zh_CN
-Chinese (China)
-GB18030
-
-OS Locale:  zh_CN.gbk
-zh_CN
-Chinese (China)
-GBK
-
-OS Locale:  zh_CN.utf8
-zh_CN
-Chinese (China)
-UTF-8
-
-OS Locale:  zh_HK
-zh_HK
-Chinese (Hong Kong)
-Big5-HKSCS
-
-OS Locale:  zh_HK.utf8
-zh_HK
-Chinese (Hong Kong)
-UTF-8
-
-OS Locale:  zh_SG
-zh_SG
-Chinese (Singapore)
-GB2312
-
-OS Locale:  zh_SG.gbk
-zh_SG
-Chinese (Singapore)
-GBK
-
-OS Locale:  zh_TW
-zh_TW
-Chinese (Taiwan)
-Big5
-
-OS Locale:  zh_TW.euctw
-zh_TW
-Chinese (Taiwan)
-x-EUC-TW
-
-OS Locale:  zh_TW.utf8
-zh_TW
-Chinese (Taiwan)
-UTF-8
-
-OS Locale:  zu_ZA
-zu_ZA
-Zulu (South Africa)
-ISO-8859-1
-
-OS Locale:  zu_ZA.utf8
-zu_ZA
-Zulu (South Africa)
-UTF-8
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/data/deflocale.rhel5	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,3924 @@
+Red Hat Enterprise Linux Server release 5.3 (Tikanga)
+Linux localhost.localdomain 2.6.18-128.el5 #1 SMP Wed Dec 17 11:42:39 EST 2008 i686 i686 i386 GNU/Linux
+Testing all available locales
+
+OS Locale:  C
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: US-ASCII
+
+OS Locale:  POSIX
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: US-ASCII
+
+OS Locale:  aa_DJ
+default locale: ID: aa_DJ, Name: Afar (Djibouti)
+display locale: ID: aa_DJ, Name: Afar (Djibouti)
+format locale: ID: aa_DJ, Name: Afar (Djibouti)
+default charset: ISO-8859-1
+
+OS Locale:  aa_DJ.iso88591
+default locale: ID: aa_DJ, Name: Afar (Djibouti)
+display locale: ID: aa_DJ, Name: Afar (Djibouti)
+format locale: ID: aa_DJ, Name: Afar (Djibouti)
+default charset: ISO-8859-1
+
+OS Locale:  aa_DJ.utf8
+default locale: ID: aa_DJ, Name: Afar (Djibouti)
+display locale: ID: aa_DJ, Name: Afar (Djibouti)
+format locale: ID: aa_DJ, Name: Afar (Djibouti)
+default charset: UTF-8
+
+OS Locale:  aa_ER
+default locale: ID: aa_ER, Name: Afar (Eritrea)
+display locale: ID: aa_ER, Name: Afar (Eritrea)
+format locale: ID: aa_ER, Name: Afar (Eritrea)
+default charset: UTF-8
+
+OS Locale:  aa_ER.utf8
+default locale: ID: aa_ER, Name: Afar (Eritrea)
+display locale: ID: aa_ER, Name: Afar (Eritrea)
+format locale: ID: aa_ER, Name: Afar (Eritrea)
+default charset: UTF-8
+
+OS Locale:  aa_ER.utf8@saaho
+default locale: ID: aa_ER, Name: Afar (Eritrea)
+display locale: ID: aa_ER, Name: Afar (Eritrea)
+format locale: ID: aa_ER, Name: Afar (Eritrea)
+default charset: UTF-8
+
+OS Locale:  aa_ER@saaho
+default locale: ID: aa_ER, Name: Afar (Eritrea)
+display locale: ID: aa_ER, Name: Afar (Eritrea)
+format locale: ID: aa_ER, Name: Afar (Eritrea)
+default charset: UTF-8
+
+OS Locale:  aa_ET
+default locale: ID: aa_ET, Name: Afar (Ethiopia)
+display locale: ID: aa_ET, Name: Afar (Ethiopia)
+format locale: ID: aa_ET, Name: Afar (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  aa_ET.utf8
+default locale: ID: aa_ET, Name: Afar (Ethiopia)
+display locale: ID: aa_ET, Name: Afar (Ethiopia)
+format locale: ID: aa_ET, Name: Afar (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  af_ZA
+default locale: ID: af_ZA, Name: Afrikaans (South Africa)
+display locale: ID: af_ZA, Name: Afrikaans (South Africa)
+format locale: ID: af_ZA, Name: Afrikaans (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  af_ZA.iso88591
+default locale: ID: af_ZA, Name: Afrikaans (South Africa)
+display locale: ID: af_ZA, Name: Afrikaans (South Africa)
+format locale: ID: af_ZA, Name: Afrikaans (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  af_ZA.utf8
+default locale: ID: af_ZA, Name: Afrikaans (South Africa)
+display locale: ID: af_ZA, Name: Afrikaans (South Africa)
+format locale: ID: af_ZA, Name: Afrikaans (South Africa)
+default charset: UTF-8
+
+OS Locale:  am_ET
+default locale: ID: am_ET, Name: Amharic (Ethiopia)
+display locale: ID: am_ET, Name: Amharic (Ethiopia)
+format locale: ID: am_ET, Name: Amharic (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  am_ET.utf8
+default locale: ID: am_ET, Name: Amharic (Ethiopia)
+display locale: ID: am_ET, Name: Amharic (Ethiopia)
+format locale: ID: am_ET, Name: Amharic (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  an_ES
+default locale: ID: an_ES, Name: Aragonese (Spain)
+display locale: ID: an_ES, Name: Aragonese (Spain)
+format locale: ID: an_ES, Name: Aragonese (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  an_ES.iso885915
+default locale: ID: an_ES, Name: Aragonese (Spain)
+display locale: ID: an_ES, Name: Aragonese (Spain)
+format locale: ID: an_ES, Name: Aragonese (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  an_ES.utf8
+default locale: ID: an_ES, Name: Aragonese (Spain)
+display locale: ID: an_ES, Name: Aragonese (Spain)
+format locale: ID: an_ES, Name: Aragonese (Spain)
+default charset: UTF-8
+
+OS Locale:  ar_AE
+default locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+display locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+format locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+default charset: ISO-8859-6
+
+OS Locale:  ar_AE.iso88596
+default locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+display locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+format locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+default charset: ISO-8859-6
+
+OS Locale:  ar_AE.utf8
+default locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+display locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+format locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+default charset: UTF-8
+
+OS Locale:  ar_BH
+default locale: ID: ar_BH, Name: Arabic (Bahrain)
+display locale: ID: ar_BH, Name: Arabic (Bahrain)
+format locale: ID: ar_BH, Name: Arabic (Bahrain)
+default charset: ISO-8859-6
+
+OS Locale:  ar_BH.iso88596
+default locale: ID: ar_BH, Name: Arabic (Bahrain)
+display locale: ID: ar_BH, Name: Arabic (Bahrain)
+format locale: ID: ar_BH, Name: Arabic (Bahrain)
+default charset: ISO-8859-6
+
+OS Locale:  ar_BH.utf8
+default locale: ID: ar_BH, Name: Arabic (Bahrain)
+display locale: ID: ar_BH, Name: Arabic (Bahrain)
+format locale: ID: ar_BH, Name: Arabic (Bahrain)
+default charset: UTF-8
+
+OS Locale:  ar_DZ
+default locale: ID: ar_DZ, Name: Arabic (Algeria)
+display locale: ID: ar_DZ, Name: Arabic (Algeria)
+format locale: ID: ar_DZ, Name: Arabic (Algeria)
+default charset: ISO-8859-6
+
+OS Locale:  ar_DZ.iso88596
+default locale: ID: ar_DZ, Name: Arabic (Algeria)
+display locale: ID: ar_DZ, Name: Arabic (Algeria)
+format locale: ID: ar_DZ, Name: Arabic (Algeria)
+default charset: ISO-8859-6
+
+OS Locale:  ar_DZ.utf8
+default locale: ID: ar_DZ, Name: Arabic (Algeria)
+display locale: ID: ar_DZ, Name: Arabic (Algeria)
+format locale: ID: ar_DZ, Name: Arabic (Algeria)
+default charset: UTF-8
+
+OS Locale:  ar_EG
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: ISO-8859-6
+
+OS Locale:  ar_EG.iso88596
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: ISO-8859-6
+
+OS Locale:  ar_EG.utf8
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: UTF-8
+
+OS Locale:  ar_IN
+default locale: ID: ar_IN, Name: Arabic (India)
+display locale: ID: ar_IN, Name: Arabic (India)
+format locale: ID: ar_IN, Name: Arabic (India)
+default charset: UTF-8
+
+OS Locale:  ar_IN.utf8
+default locale: ID: ar_IN, Name: Arabic (India)
+display locale: ID: ar_IN, Name: Arabic (India)
+format locale: ID: ar_IN, Name: Arabic (India)
+default charset: UTF-8
+
+OS Locale:  ar_IQ
+default locale: ID: ar_IQ, Name: Arabic (Iraq)
+display locale: ID: ar_IQ, Name: Arabic (Iraq)
+format locale: ID: ar_IQ, Name: Arabic (Iraq)
+default charset: ISO-8859-6
+
+OS Locale:  ar_IQ.iso88596
+default locale: ID: ar_IQ, Name: Arabic (Iraq)
+display locale: ID: ar_IQ, Name: Arabic (Iraq)
+format locale: ID: ar_IQ, Name: Arabic (Iraq)
+default charset: ISO-8859-6
+
+OS Locale:  ar_IQ.utf8
+default locale: ID: ar_IQ, Name: Arabic (Iraq)
+display locale: ID: ar_IQ, Name: Arabic (Iraq)
+format locale: ID: ar_IQ, Name: Arabic (Iraq)
+default charset: UTF-8
+
+OS Locale:  ar_JO
+default locale: ID: ar_JO, Name: Arabic (Jordan)
+display locale: ID: ar_JO, Name: Arabic (Jordan)
+format locale: ID: ar_JO, Name: Arabic (Jordan)
+default charset: ISO-8859-6
+
+OS Locale:  ar_JO.iso88596
+default locale: ID: ar_JO, Name: Arabic (Jordan)
+display locale: ID: ar_JO, Name: Arabic (Jordan)
+format locale: ID: ar_JO, Name: Arabic (Jordan)
+default charset: ISO-8859-6
+
+OS Locale:  ar_JO.utf8
+default locale: ID: ar_JO, Name: Arabic (Jordan)
+display locale: ID: ar_JO, Name: Arabic (Jordan)
+format locale: ID: ar_JO, Name: Arabic (Jordan)
+default charset: UTF-8
+
+OS Locale:  ar_KW
+default locale: ID: ar_KW, Name: Arabic (Kuwait)
+display locale: ID: ar_KW, Name: Arabic (Kuwait)
+format locale: ID: ar_KW, Name: Arabic (Kuwait)
+default charset: ISO-8859-6
+
+OS Locale:  ar_KW.iso88596
+default locale: ID: ar_KW, Name: Arabic (Kuwait)
+display locale: ID: ar_KW, Name: Arabic (Kuwait)
+format locale: ID: ar_KW, Name: Arabic (Kuwait)
+default charset: ISO-8859-6
+
+OS Locale:  ar_KW.utf8
+default locale: ID: ar_KW, Name: Arabic (Kuwait)
+display locale: ID: ar_KW, Name: Arabic (Kuwait)
+format locale: ID: ar_KW, Name: Arabic (Kuwait)
+default charset: UTF-8
+
+OS Locale:  ar_LB
+default locale: ID: ar_LB, Name: Arabic (Lebanon)
+display locale: ID: ar_LB, Name: Arabic (Lebanon)
+format locale: ID: ar_LB, Name: Arabic (Lebanon)
+default charset: ISO-8859-6
+
+OS Locale:  ar_LB.iso88596
+default locale: ID: ar_LB, Name: Arabic (Lebanon)
+display locale: ID: ar_LB, Name: Arabic (Lebanon)
+format locale: ID: ar_LB, Name: Arabic (Lebanon)
+default charset: ISO-8859-6
+
+OS Locale:  ar_LB.utf8
+default locale: ID: ar_LB, Name: Arabic (Lebanon)
+display locale: ID: ar_LB, Name: Arabic (Lebanon)
+format locale: ID: ar_LB, Name: Arabic (Lebanon)
+default charset: UTF-8
+
+OS Locale:  ar_LY
+default locale: ID: ar_LY, Name: Arabic (Libya)
+display locale: ID: ar_LY, Name: Arabic (Libya)
+format locale: ID: ar_LY, Name: Arabic (Libya)
+default charset: ISO-8859-6
+
+OS Locale:  ar_LY.iso88596
+default locale: ID: ar_LY, Name: Arabic (Libya)
+display locale: ID: ar_LY, Name: Arabic (Libya)
+format locale: ID: ar_LY, Name: Arabic (Libya)
+default charset: ISO-8859-6
+
+OS Locale:  ar_LY.utf8
+default locale: ID: ar_LY, Name: Arabic (Libya)
+display locale: ID: ar_LY, Name: Arabic (Libya)
+format locale: ID: ar_LY, Name: Arabic (Libya)
+default charset: UTF-8
+
+OS Locale:  ar_MA
+default locale: ID: ar_MA, Name: Arabic (Morocco)
+display locale: ID: ar_MA, Name: Arabic (Morocco)
+format locale: ID: ar_MA, Name: Arabic (Morocco)
+default charset: ISO-8859-6
+
+OS Locale:  ar_MA.iso88596
+default locale: ID: ar_MA, Name: Arabic (Morocco)
+display locale: ID: ar_MA, Name: Arabic (Morocco)
+format locale: ID: ar_MA, Name: Arabic (Morocco)
+default charset: ISO-8859-6
+
+OS Locale:  ar_MA.utf8
+default locale: ID: ar_MA, Name: Arabic (Morocco)
+display locale: ID: ar_MA, Name: Arabic (Morocco)
+format locale: ID: ar_MA, Name: Arabic (Morocco)
+default charset: UTF-8
+
+OS Locale:  ar_OM
+default locale: ID: ar_OM, Name: Arabic (Oman)
+display locale: ID: ar_OM, Name: Arabic (Oman)
+format locale: ID: ar_OM, Name: Arabic (Oman)
+default charset: ISO-8859-6
+
+OS Locale:  ar_OM.iso88596
+default locale: ID: ar_OM, Name: Arabic (Oman)
+display locale: ID: ar_OM, Name: Arabic (Oman)
+format locale: ID: ar_OM, Name: Arabic (Oman)
+default charset: ISO-8859-6
+
+OS Locale:  ar_OM.utf8
+default locale: ID: ar_OM, Name: Arabic (Oman)
+display locale: ID: ar_OM, Name: Arabic (Oman)
+format locale: ID: ar_OM, Name: Arabic (Oman)
+default charset: UTF-8
+
+OS Locale:  ar_QA
+default locale: ID: ar_QA, Name: Arabic (Qatar)
+display locale: ID: ar_QA, Name: Arabic (Qatar)
+format locale: ID: ar_QA, Name: Arabic (Qatar)
+default charset: ISO-8859-6
+
+OS Locale:  ar_QA.iso88596
+default locale: ID: ar_QA, Name: Arabic (Qatar)
+display locale: ID: ar_QA, Name: Arabic (Qatar)
+format locale: ID: ar_QA, Name: Arabic (Qatar)
+default charset: ISO-8859-6
+
+OS Locale:  ar_QA.utf8
+default locale: ID: ar_QA, Name: Arabic (Qatar)
+display locale: ID: ar_QA, Name: Arabic (Qatar)
+format locale: ID: ar_QA, Name: Arabic (Qatar)
+default charset: UTF-8
+
+OS Locale:  ar_SA
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SA.iso88596
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SA.utf8
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: UTF-8
+
+OS Locale:  ar_SD
+default locale: ID: ar_SD, Name: Arabic (Sudan)
+display locale: ID: ar_SD, Name: Arabic (Sudan)
+format locale: ID: ar_SD, Name: Arabic (Sudan)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SD.iso88596
+default locale: ID: ar_SD, Name: Arabic (Sudan)
+display locale: ID: ar_SD, Name: Arabic (Sudan)
+format locale: ID: ar_SD, Name: Arabic (Sudan)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SD.utf8
+default locale: ID: ar_SD, Name: Arabic (Sudan)
+display locale: ID: ar_SD, Name: Arabic (Sudan)
+format locale: ID: ar_SD, Name: Arabic (Sudan)
+default charset: UTF-8
+
+OS Locale:  ar_SY
+default locale: ID: ar_SY, Name: Arabic (Syria)
+display locale: ID: ar_SY, Name: Arabic (Syria)
+format locale: ID: ar_SY, Name: Arabic (Syria)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SY.iso88596
+default locale: ID: ar_SY, Name: Arabic (Syria)
+display locale: ID: ar_SY, Name: Arabic (Syria)
+format locale: ID: ar_SY, Name: Arabic (Syria)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SY.utf8
+default locale: ID: ar_SY, Name: Arabic (Syria)
+display locale: ID: ar_SY, Name: Arabic (Syria)
+format locale: ID: ar_SY, Name: Arabic (Syria)
+default charset: UTF-8
+
+OS Locale:  ar_TN
+default locale: ID: ar_TN, Name: Arabic (Tunisia)
+display locale: ID: ar_TN, Name: Arabic (Tunisia)
+format locale: ID: ar_TN, Name: Arabic (Tunisia)
+default charset: ISO-8859-6
+
+OS Locale:  ar_TN.iso88596
+default locale: ID: ar_TN, Name: Arabic (Tunisia)
+display locale: ID: ar_TN, Name: Arabic (Tunisia)
+format locale: ID: ar_TN, Name: Arabic (Tunisia)
+default charset: ISO-8859-6
+
+OS Locale:  ar_TN.utf8
+default locale: ID: ar_TN, Name: Arabic (Tunisia)
+display locale: ID: ar_TN, Name: Arabic (Tunisia)
+format locale: ID: ar_TN, Name: Arabic (Tunisia)
+default charset: UTF-8
+
+OS Locale:  ar_YE
+default locale: ID: ar_YE, Name: Arabic (Yemen)
+display locale: ID: ar_YE, Name: Arabic (Yemen)
+format locale: ID: ar_YE, Name: Arabic (Yemen)
+default charset: ISO-8859-6
+
+OS Locale:  ar_YE.iso88596
+default locale: ID: ar_YE, Name: Arabic (Yemen)
+display locale: ID: ar_YE, Name: Arabic (Yemen)
+format locale: ID: ar_YE, Name: Arabic (Yemen)
+default charset: ISO-8859-6
+
+OS Locale:  ar_YE.utf8
+default locale: ID: ar_YE, Name: Arabic (Yemen)
+display locale: ID: ar_YE, Name: Arabic (Yemen)
+format locale: ID: ar_YE, Name: Arabic (Yemen)
+default charset: UTF-8
+
+OS Locale:  as_IN.utf8
+default locale: ID: as_IN, Name: Assamese (India)
+display locale: ID: as_IN, Name: Assamese (India)
+format locale: ID: as_IN, Name: Assamese (India)
+default charset: UTF-8
+
+OS Locale:  az_AZ.utf8
+default locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+display locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: UTF-8
+
+OS Locale:  be_BY
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: windows-1251
+
+OS Locale:  be_BY.cp1251
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: windows-1251
+
+OS Locale:  be_BY.utf8
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: UTF-8
+
+OS Locale:  be_BY.utf8@latin
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: UTF-8
+
+OS Locale:  be_BY@latin
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: UTF-8
+
+OS Locale:  bg_BG
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: windows-1251
+
+OS Locale:  bg_BG.cp1251
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: windows-1251
+
+OS Locale:  bg_BG.utf8
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: UTF-8
+
+OS Locale:  bn_BD
+default locale: ID: bn_BD, Name: Bengali (Bangladesh)
+display locale: ID: bn_BD, Name: Bengali (Bangladesh)
+format locale: ID: bn_BD, Name: Bengali (Bangladesh)
+default charset: UTF-8
+
+OS Locale:  bn_BD.utf8
+default locale: ID: bn_BD, Name: Bengali (Bangladesh)
+display locale: ID: bn_BD, Name: Bengali (Bangladesh)
+format locale: ID: bn_BD, Name: Bengali (Bangladesh)
+default charset: UTF-8
+
+OS Locale:  bn_IN
+default locale: ID: bn_IN, Name: Bengali (India)
+display locale: ID: bn_IN, Name: Bengali (India)
+format locale: ID: bn_IN, Name: Bengali (India)
+default charset: UTF-8
+
+OS Locale:  bn_IN.utf8
+default locale: ID: bn_IN, Name: Bengali (India)
+display locale: ID: bn_IN, Name: Bengali (India)
+format locale: ID: bn_IN, Name: Bengali (India)
+default charset: UTF-8
+
+OS Locale:  bokmål
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  bokmal
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  br_FR
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: ISO-8859-1
+
+OS Locale:  br_FR.iso88591
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: ISO-8859-1
+
+OS Locale:  br_FR.iso885915@euro
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: ISO-8859-15
+
+OS Locale:  br_FR.utf8
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: UTF-8
+
+OS Locale:  br_FR@euro
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: ISO-8859-15
+
+OS Locale:  bs_BA
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: ISO-8859-2
+
+OS Locale:  bs_BA.iso88592
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: ISO-8859-2
+
+OS Locale:  bs_BA.utf8
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: UTF-8
+
+OS Locale:  byn_ER
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  byn_ER.utf8
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  ca_AD
+default locale: ID: ca_AD, Name: Catalan (Andorra)
+display locale: ID: ca_AD, Name: Catalan (Andorra)
+format locale: ID: ca_AD, Name: Catalan (Andorra)
+default charset: ISO-8859-15
+
+OS Locale:  ca_AD.iso885915
+default locale: ID: ca_AD, Name: Catalan (Andorra)
+display locale: ID: ca_AD, Name: Catalan (Andorra)
+format locale: ID: ca_AD, Name: Catalan (Andorra)
+default charset: ISO-8859-15
+
+OS Locale:  ca_AD.utf8
+default locale: ID: ca_AD, Name: Catalan (Andorra)
+display locale: ID: ca_AD, Name: Catalan (Andorra)
+format locale: ID: ca_AD, Name: Catalan (Andorra)
+default charset: UTF-8
+
+OS Locale:  ca_ES
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  ca_ES.iso88591
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  ca_ES.iso885915@euro
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  ca_ES.utf8
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: UTF-8
+
+OS Locale:  ca_ES@euro
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  ca_FR
+default locale: ID: ca_FR, Name: Catalan (France)
+display locale: ID: ca_FR, Name: Catalan (France)
+format locale: ID: ca_FR, Name: Catalan (France)
+default charset: ISO-8859-15
+
+OS Locale:  ca_FR.iso885915
+default locale: ID: ca_FR, Name: Catalan (France)
+display locale: ID: ca_FR, Name: Catalan (France)
+format locale: ID: ca_FR, Name: Catalan (France)
+default charset: ISO-8859-15
+
+OS Locale:  ca_FR.utf8
+default locale: ID: ca_FR, Name: Catalan (France)
+display locale: ID: ca_FR, Name: Catalan (France)
+format locale: ID: ca_FR, Name: Catalan (France)
+default charset: UTF-8
+
+OS Locale:  ca_IT
+default locale: ID: ca_IT, Name: Catalan (Italy)
+display locale: ID: ca_IT, Name: Catalan (Italy)
+format locale: ID: ca_IT, Name: Catalan (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  ca_IT.iso885915
+default locale: ID: ca_IT, Name: Catalan (Italy)
+display locale: ID: ca_IT, Name: Catalan (Italy)
+format locale: ID: ca_IT, Name: Catalan (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  ca_IT.utf8
+default locale: ID: ca_IT, Name: Catalan (Italy)
+display locale: ID: ca_IT, Name: Catalan (Italy)
+format locale: ID: ca_IT, Name: Catalan (Italy)
+default charset: UTF-8
+
+OS Locale:  catalan
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  croatian
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  cs_CZ
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  cs_CZ.iso88592
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  cs_CZ.utf8
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: UTF-8
+
+OS Locale:  csb_PL
+default locale: ID: en_PL, Name: English (Poland)
+display locale: ID: en_PL, Name: English (Poland)
+format locale: ID: en_PL, Name: English (Poland)
+default charset: UTF-8
+
+OS Locale:  csb_PL.utf8
+default locale: ID: en_PL, Name: English (Poland)
+display locale: ID: en_PL, Name: English (Poland)
+format locale: ID: en_PL, Name: English (Poland)
+default charset: UTF-8
+
+OS Locale:  cy_GB
+default locale: ID: cy_GB, Name: Welsh (United Kingdom)
+display locale: ID: cy_GB, Name: Welsh (United Kingdom)
+format locale: ID: cy_GB, Name: Welsh (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  cy_GB.iso885914
+default locale: ID: cy_GB, Name: Welsh (United Kingdom)
+display locale: ID: cy_GB, Name: Welsh (United Kingdom)
+format locale: ID: cy_GB, Name: Welsh (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  cy_GB.utf8
+default locale: ID: cy_GB, Name: Welsh (United Kingdom)
+display locale: ID: cy_GB, Name: Welsh (United Kingdom)
+format locale: ID: cy_GB, Name: Welsh (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  czech
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  da_DK
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  da_DK.iso88591
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  da_DK.iso885915
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-15
+
+OS Locale:  da_DK.utf8
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: UTF-8
+
+OS Locale:  danish
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  dansk
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  de_AT
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-1
+
+OS Locale:  de_AT.iso88591
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-1
+
+OS Locale:  de_AT.iso885915@euro
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-15
+
+OS Locale:  de_AT.utf8
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: UTF-8
+
+OS Locale:  de_AT@euro
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-15
+
+OS Locale:  de_BE
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  de_BE.iso88591
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  de_BE.iso885915@euro
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  de_BE.utf8
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: UTF-8
+
+OS Locale:  de_BE@euro
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  de_CH
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  de_CH.iso88591
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  de_CH.utf8
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: UTF-8
+
+OS Locale:  de_DE
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  de_DE.iso88591
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  de_DE.iso885915@euro
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
+
+OS Locale:  de_DE.utf8
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: UTF-8
+
+OS Locale:  de_DE@euro
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
+
+OS Locale:  de_LU
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: ISO-8859-1
+
+OS Locale:  de_LU.iso88591
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: ISO-8859-1
+
+OS Locale:  de_LU.iso885915@euro
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: ISO-8859-15
+
+OS Locale:  de_LU.utf8
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: UTF-8
+
+OS Locale:  de_LU@euro
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: ISO-8859-15
+
+OS Locale:  deutsch
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  dutch
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  dz_BT
+default locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+display locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+format locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+default charset: UTF-8
+
+OS Locale:  dz_BT.utf8
+default locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+display locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+format locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+default charset: UTF-8
+
+OS Locale:  eesti
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  el_CY
+default locale: ID: el_CY, Name: Greek (Cyprus)
+display locale: ID: el_CY, Name: Greek (Cyprus)
+format locale: ID: el_CY, Name: Greek (Cyprus)
+default charset: ISO-8859-7
+
+OS Locale:  el_CY.iso88597
+default locale: ID: el_CY, Name: Greek (Cyprus)
+display locale: ID: el_CY, Name: Greek (Cyprus)
+format locale: ID: el_CY, Name: Greek (Cyprus)
+default charset: ISO-8859-7
+
+OS Locale:  el_CY.utf8
+default locale: ID: el_CY, Name: Greek (Cyprus)
+display locale: ID: el_CY, Name: Greek (Cyprus)
+format locale: ID: el_CY, Name: Greek (Cyprus)
+default charset: UTF-8
+
+OS Locale:  el_GR
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  el_GR.iso88597
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  el_GR.utf8
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: UTF-8
+
+OS Locale:  en_AU
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: ISO-8859-1
+
+OS Locale:  en_AU.iso88591
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: ISO-8859-1
+
+OS Locale:  en_AU.utf8
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: UTF-8
+
+OS Locale:  en_BW
+default locale: ID: en_BW, Name: English (Botswana)
+display locale: ID: en_BW, Name: English (Botswana)
+format locale: ID: en_BW, Name: English (Botswana)
+default charset: ISO-8859-1
+
+OS Locale:  en_BW.iso88591
+default locale: ID: en_BW, Name: English (Botswana)
+display locale: ID: en_BW, Name: English (Botswana)
+format locale: ID: en_BW, Name: English (Botswana)
+default charset: ISO-8859-1
+
+OS Locale:  en_BW.utf8
+default locale: ID: en_BW, Name: English (Botswana)
+display locale: ID: en_BW, Name: English (Botswana)
+format locale: ID: en_BW, Name: English (Botswana)
+default charset: UTF-8
+
+OS Locale:  en_CA
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  en_CA.iso88591
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  en_CA.utf8
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: UTF-8
+
+OS Locale:  en_DK
+default locale: ID: en_DK, Name: English (Denmark)
+display locale: ID: en_DK, Name: English (Denmark)
+format locale: ID: en_DK, Name: English (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  en_DK.iso88591
+default locale: ID: en_DK, Name: English (Denmark)
+display locale: ID: en_DK, Name: English (Denmark)
+format locale: ID: en_DK, Name: English (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  en_DK.utf8
+default locale: ID: en_DK, Name: English (Denmark)
+display locale: ID: en_DK, Name: English (Denmark)
+format locale: ID: en_DK, Name: English (Denmark)
+default charset: UTF-8
+
+OS Locale:  en_GB
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  en_GB.iso88591
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  en_GB.iso885915
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-15
+
+OS Locale:  en_GB.utf8
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  en_HK
+default locale: ID: en_HK, Name: English (Hong Kong)
+display locale: ID: en_HK, Name: English (Hong Kong)
+format locale: ID: en_HK, Name: English (Hong Kong)
+default charset: ISO-8859-1
+
+OS Locale:  en_HK.iso88591
+default locale: ID: en_HK, Name: English (Hong Kong)
+display locale: ID: en_HK, Name: English (Hong Kong)
+format locale: ID: en_HK, Name: English (Hong Kong)
+default charset: ISO-8859-1
+
+OS Locale:  en_HK.utf8
+default locale: ID: en_HK, Name: English (Hong Kong)
+display locale: ID: en_HK, Name: English (Hong Kong)
+format locale: ID: en_HK, Name: English (Hong Kong)
+default charset: UTF-8
+
+OS Locale:  en_IE
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  en_IE.iso88591
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  en_IE.iso885915@euro
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  en_IE.utf8
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: UTF-8
+
+OS Locale:  en_IE@euro
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  en_IN
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: UTF-8
+
+OS Locale:  en_IN.utf8
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: UTF-8
+
+OS Locale:  en_NZ
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: ISO-8859-1
+
+OS Locale:  en_NZ.iso88591
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: ISO-8859-1
+
+OS Locale:  en_NZ.utf8
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: UTF-8
+
+OS Locale:  en_PH
+default locale: ID: en_PH, Name: English (Philippines)
+display locale: ID: en_PH, Name: English (Philippines)
+format locale: ID: en_PH, Name: English (Philippines)
+default charset: ISO-8859-1
+
+OS Locale:  en_PH.iso88591
+default locale: ID: en_PH, Name: English (Philippines)
+display locale: ID: en_PH, Name: English (Philippines)
+format locale: ID: en_PH, Name: English (Philippines)
+default charset: ISO-8859-1
+
+OS Locale:  en_PH.utf8
+default locale: ID: en_PH, Name: English (Philippines)
+display locale: ID: en_PH, Name: English (Philippines)
+format locale: ID: en_PH, Name: English (Philippines)
+default charset: UTF-8
+
+OS Locale:  en_SG
+default locale: ID: en_SG, Name: English (Singapore)
+display locale: ID: en_SG, Name: English (Singapore)
+format locale: ID: en_SG, Name: English (Singapore)
+default charset: ISO-8859-1
+
+OS Locale:  en_SG.iso88591
+default locale: ID: en_SG, Name: English (Singapore)
+display locale: ID: en_SG, Name: English (Singapore)
+format locale: ID: en_SG, Name: English (Singapore)
+default charset: ISO-8859-1
+
+OS Locale:  en_SG.utf8
+default locale: ID: en_SG, Name: English (Singapore)
+display locale: ID: en_SG, Name: English (Singapore)
+format locale: ID: en_SG, Name: English (Singapore)
+default charset: UTF-8
+
+OS Locale:  en_US
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-1
+
+OS Locale:  en_US.iso88591
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-1
+
+OS Locale:  en_US.iso885915
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-15
+
+OS Locale:  en_US.utf8
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: UTF-8
+
+OS Locale:  en_ZA
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  en_ZA.iso88591
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  en_ZA.utf8
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: UTF-8
+
+OS Locale:  en_ZW
+default locale: ID: en_ZW, Name: English (Zimbabwe)
+display locale: ID: en_ZW, Name: English (Zimbabwe)
+format locale: ID: en_ZW, Name: English (Zimbabwe)
+default charset: ISO-8859-1
+
+OS Locale:  en_ZW.iso88591
+default locale: ID: en_ZW, Name: English (Zimbabwe)
+display locale: ID: en_ZW, Name: English (Zimbabwe)
+format locale: ID: en_ZW, Name: English (Zimbabwe)
+default charset: ISO-8859-1
+
+OS Locale:  en_ZW.utf8
+default locale: ID: en_ZW, Name: English (Zimbabwe)
+display locale: ID: en_ZW, Name: English (Zimbabwe)
+format locale: ID: en_ZW, Name: English (Zimbabwe)
+default charset: UTF-8
+
+OS Locale:  es_AR
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: ISO-8859-1
+
+OS Locale:  es_AR.iso88591
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: ISO-8859-1
+
+OS Locale:  es_AR.utf8
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: UTF-8
+
+OS Locale:  es_BO
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: ISO-8859-1
+
+OS Locale:  es_BO.iso88591
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: ISO-8859-1
+
+OS Locale:  es_BO.utf8
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: UTF-8
+
+OS Locale:  es_CL
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: ISO-8859-1
+
+OS Locale:  es_CL.iso88591
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: ISO-8859-1
+
+OS Locale:  es_CL.utf8
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: UTF-8
+
+OS Locale:  es_CO
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: ISO-8859-1
+
+OS Locale:  es_CO.iso88591
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: ISO-8859-1
+
+OS Locale:  es_CO.utf8
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: UTF-8
+
+OS Locale:  es_CR
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: ISO-8859-1
+
+OS Locale:  es_CR.iso88591
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: ISO-8859-1
+
+OS Locale:  es_CR.utf8
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: UTF-8
+
+OS Locale:  es_DO
+default locale: ID: es_DO, Name: Spanish (Dominican Republic)
+display locale: ID: es_DO, Name: Spanish (Dominican Republic)
+format locale: ID: es_DO, Name: Spanish (Dominican Republic)
+default charset: ISO-8859-1
+
+OS Locale:  es_DO.iso88591
+default locale: ID: es_DO, Name: Spanish (Dominican Republic)
+display locale: ID: es_DO, Name: Spanish (Dominican Republic)
+format locale: ID: es_DO, Name: Spanish (Dominican Republic)
+default charset: ISO-8859-1
+
+OS Locale:  es_DO.utf8
+default locale: ID: es_DO, Name: Spanish (Dominican Republic)
+display locale: ID: es_DO, Name: Spanish (Dominican Republic)
+format locale: ID: es_DO, Name: Spanish (Dominican Republic)
+default charset: UTF-8
+
+OS Locale:  es_EC
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: ISO-8859-1
+
+OS Locale:  es_EC.iso88591
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: ISO-8859-1
+
+OS Locale:  es_EC.utf8
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: UTF-8
+
+OS Locale:  es_ES
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  es_ES.iso88591
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  es_ES.iso885915@euro
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  es_ES.utf8
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: UTF-8
+
+OS Locale:  es_ES@euro
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  es_GT
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: ISO-8859-1
+
+OS Locale:  es_GT.iso88591
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: ISO-8859-1
+
+OS Locale:  es_GT.utf8
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: UTF-8
+
+OS Locale:  es_HN
+default locale: ID: es_HN, Name: Spanish (Honduras)
+display locale: ID: es_HN, Name: Spanish (Honduras)
+format locale: ID: es_HN, Name: Spanish (Honduras)
+default charset: ISO-8859-1
+
+OS Locale:  es_HN.iso88591
+default locale: ID: es_HN, Name: Spanish (Honduras)
+display locale: ID: es_HN, Name: Spanish (Honduras)
+format locale: ID: es_HN, Name: Spanish (Honduras)
+default charset: ISO-8859-1
+
+OS Locale:  es_HN.utf8
+default locale: ID: es_HN, Name: Spanish (Honduras)
+display locale: ID: es_HN, Name: Spanish (Honduras)
+format locale: ID: es_HN, Name: Spanish (Honduras)
+default charset: UTF-8
+
+OS Locale:  es_MX
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: ISO-8859-1
+
+OS Locale:  es_MX.iso88591
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: ISO-8859-1
+
+OS Locale:  es_MX.utf8
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: UTF-8
+
+OS Locale:  es_NI
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: ISO-8859-1
+
+OS Locale:  es_NI.iso88591
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: ISO-8859-1
+
+OS Locale:  es_NI.utf8
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: UTF-8
+
+OS Locale:  es_PA
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: ISO-8859-1
+
+OS Locale:  es_PA.iso88591
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: ISO-8859-1
+
+OS Locale:  es_PA.utf8
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: UTF-8
+
+OS Locale:  es_PE
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: ISO-8859-1
+
+OS Locale:  es_PE.iso88591
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: ISO-8859-1
+
+OS Locale:  es_PE.utf8
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: UTF-8
+
+OS Locale:  es_PR
+default locale: ID: es_PR, Name: Spanish (Puerto Rico)
+display locale: ID: es_PR, Name: Spanish (Puerto Rico)
+format locale: ID: es_PR, Name: Spanish (Puerto Rico)
+default charset: ISO-8859-1
+
+OS Locale:  es_PR.iso88591
+default locale: ID: es_PR, Name: Spanish (Puerto Rico)
+display locale: ID: es_PR, Name: Spanish (Puerto Rico)
+format locale: ID: es_PR, Name: Spanish (Puerto Rico)
+default charset: ISO-8859-1
+
+OS Locale:  es_PR.utf8
+default locale: ID: es_PR, Name: Spanish (Puerto Rico)
+display locale: ID: es_PR, Name: Spanish (Puerto Rico)
+format locale: ID: es_PR, Name: Spanish (Puerto Rico)
+default charset: UTF-8
+
+OS Locale:  es_PY
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_PY.iso88591
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_PY.utf8
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: UTF-8
+
+OS Locale:  es_SV
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: ISO-8859-1
+
+OS Locale:  es_SV.iso88591
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: ISO-8859-1
+
+OS Locale:  es_SV.utf8
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: UTF-8
+
+OS Locale:  es_US
+default locale: ID: es_US, Name: Spanish (United States)
+display locale: ID: es_US, Name: Spanish (United States)
+format locale: ID: es_US, Name: Spanish (United States)
+default charset: ISO-8859-1
+
+OS Locale:  es_US.iso88591
+default locale: ID: es_US, Name: Spanish (United States)
+display locale: ID: es_US, Name: Spanish (United States)
+format locale: ID: es_US, Name: Spanish (United States)
+default charset: ISO-8859-1
+
+OS Locale:  es_US.utf8
+default locale: ID: es_US, Name: Spanish (United States)
+display locale: ID: es_US, Name: Spanish (United States)
+format locale: ID: es_US, Name: Spanish (United States)
+default charset: UTF-8
+
+OS Locale:  es_UY
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_UY.iso88591
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_UY.utf8
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: UTF-8
+
+OS Locale:  es_VE
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: ISO-8859-1
+
+OS Locale:  es_VE.iso88591
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: ISO-8859-1
+
+OS Locale:  es_VE.utf8
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: UTF-8
+
+OS Locale:  estonian
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  et_EE
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-1
+
+OS Locale:  et_EE.iso88591
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-1
+
+OS Locale:  et_EE.iso885915
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-15
+
+OS Locale:  et_EE.utf8
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: UTF-8
+
+OS Locale:  eu_ES
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  eu_ES.iso88591
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  eu_ES.iso885915@euro
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  eu_ES.utf8
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: UTF-8
+
+OS Locale:  eu_ES@euro
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  fa_IR
+default locale: ID: fa_IR, Name: Persian (Iran)
+display locale: ID: fa_IR, Name: Persian (Iran)
+format locale: ID: fa_IR, Name: Persian (Iran)
+default charset: UTF-8
+
+OS Locale:  fa_IR.utf8
+default locale: ID: fa_IR, Name: Persian (Iran)
+display locale: ID: fa_IR, Name: Persian (Iran)
+format locale: ID: fa_IR, Name: Persian (Iran)
+default charset: UTF-8
+
+OS Locale:  fi_FI
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fi_FI.iso88591
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fi_FI.iso885915@euro
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  fi_FI.utf8
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: UTF-8
+
+OS Locale:  fi_FI@euro
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  finnish
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fo_FO
+default locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+display locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+format locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+default charset: ISO-8859-1
+
+OS Locale:  fo_FO.iso88591
+default locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+display locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+format locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+default charset: ISO-8859-1
+
+OS Locale:  fo_FO.utf8
+default locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+display locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+format locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+default charset: UTF-8
+
+OS Locale:  fr_BE
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  fr_BE.iso88591
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  fr_BE.iso885915@euro
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  fr_BE.utf8
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: UTF-8
+
+OS Locale:  fr_BE@euro
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  fr_CA
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CA.iso88591
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CA.utf8
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: UTF-8
+
+OS Locale:  fr_CH
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CH.iso88591
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CH.utf8
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: UTF-8
+
+OS Locale:  fr_FR
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fr_FR.iso88591
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fr_FR.iso885915@euro
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
+
+OS Locale:  fr_FR.utf8
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: UTF-8
+
+OS Locale:  fr_FR@euro
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
+
+OS Locale:  fr_LU
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: ISO-8859-1
+
+OS Locale:  fr_LU.iso88591
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: ISO-8859-1
+
+OS Locale:  fr_LU.iso885915@euro
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: ISO-8859-15
+
+OS Locale:  fr_LU.utf8
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: UTF-8
+
+OS Locale:  fr_LU@euro
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: ISO-8859-15
+
+OS Locale:  français
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  french
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fy_NL
+default locale: ID: fy_NL, Name: Frisian (Netherlands)
+display locale: ID: fy_NL, Name: Frisian (Netherlands)
+format locale: ID: fy_NL, Name: Frisian (Netherlands)
+default charset: UTF-8
+
+OS Locale:  fy_NL.utf8
+default locale: ID: fy_NL, Name: Frisian (Netherlands)
+display locale: ID: fy_NL, Name: Frisian (Netherlands)
+format locale: ID: fy_NL, Name: Frisian (Netherlands)
+default charset: UTF-8
+
+OS Locale:  ga_IE
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  ga_IE.iso88591
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  ga_IE.iso885915@euro
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  ga_IE.utf8
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: UTF-8
+
+OS Locale:  ga_IE@euro
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  galego
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  galician
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  gd_GB
+default locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+display locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+format locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+default charset: ISO-8859-15
+
+OS Locale:  gd_GB.iso885915
+default locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+display locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+format locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+default charset: ISO-8859-15
+
+OS Locale:  gd_GB.utf8
+default locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+display locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+format locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  german
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  gez_ER
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  gez_ER.utf8
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  gez_ER.utf8@abegede
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  gez_ER@abegede
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  gez_ET
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  gez_ET.utf8
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  gez_ET.utf8@abegede
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  gez_ET@abegede
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  gl_ES
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  gl_ES.iso88591
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  gl_ES.iso885915@euro
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  gl_ES.utf8
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: UTF-8
+
+OS Locale:  gl_ES@euro
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  greek
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  gu_IN
+default locale: ID: gu_IN, Name: Gujarati (India)
+display locale: ID: gu_IN, Name: Gujarati (India)
+format locale: ID: gu_IN, Name: Gujarati (India)
+default charset: UTF-8
+
+OS Locale:  gu_IN.utf8
+default locale: ID: gu_IN, Name: Gujarati (India)
+display locale: ID: gu_IN, Name: Gujarati (India)
+format locale: ID: gu_IN, Name: Gujarati (India)
+default charset: UTF-8
+
+OS Locale:  gv_GB
+default locale: ID: gv_GB, Name: Manx (United Kingdom)
+display locale: ID: gv_GB, Name: Manx (United Kingdom)
+format locale: ID: gv_GB, Name: Manx (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  gv_GB.iso88591
+default locale: ID: gv_GB, Name: Manx (United Kingdom)
+display locale: ID: gv_GB, Name: Manx (United Kingdom)
+format locale: ID: gv_GB, Name: Manx (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  gv_GB.utf8
+default locale: ID: gv_GB, Name: Manx (United Kingdom)
+display locale: ID: gv_GB, Name: Manx (United Kingdom)
+format locale: ID: gv_GB, Name: Manx (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  he_IL
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  he_IL.iso88598
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  he_IL.utf8
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: UTF-8
+
+OS Locale:  hebrew
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  hi_IN
+default locale: ID: hi_IN, Name: Hindi (India)
+display locale: ID: hi_IN, Name: Hindi (India)
+format locale: ID: hi_IN, Name: Hindi (India)
+default charset: UTF-8
+
+OS Locale:  hi_IN.utf8
+default locale: ID: hi_IN, Name: Hindi (India)
+display locale: ID: hi_IN, Name: Hindi (India)
+format locale: ID: hi_IN, Name: Hindi (India)
+default charset: UTF-8
+
+OS Locale:  hr_HR
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  hr_HR.iso88592
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  hr_HR.utf8
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: UTF-8
+
+OS Locale:  hrvatski
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  hsb_DE
+default locale: ID: en_DE, Name: English (Germany)
+display locale: ID: en_DE, Name: English (Germany)
+format locale: ID: en_DE, Name: English (Germany)
+default charset: ISO-8859-2
+
+OS Locale:  hsb_DE.iso88592
+default locale: ID: en_DE, Name: English (Germany)
+display locale: ID: en_DE, Name: English (Germany)
+format locale: ID: en_DE, Name: English (Germany)
+default charset: ISO-8859-2
+
+OS Locale:  hsb_DE.utf8
+default locale: ID: en_DE, Name: English (Germany)
+display locale: ID: en_DE, Name: English (Germany)
+format locale: ID: en_DE, Name: English (Germany)
+default charset: UTF-8
+
+OS Locale:  hu_HU
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hu_HU.iso88592
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hu_HU.utf8
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: UTF-8
+
+OS Locale:  hungarian
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hy_AM
+default locale: ID: hy_AM, Name: Armenian (Armenia)
+display locale: ID: hy_AM, Name: Armenian (Armenia)
+format locale: ID: hy_AM, Name: Armenian (Armenia)
+default charset: UTF-8
+
+OS Locale:  hy_AM.armscii8
+default locale: ID: hy_AM, Name: Armenian (Armenia)
+display locale: ID: hy_AM, Name: Armenian (Armenia)
+format locale: ID: hy_AM, Name: Armenian (Armenia)
+default charset: UTF-8
+
+OS Locale:  hy_AM.utf8
+default locale: ID: hy_AM, Name: Armenian (Armenia)
+display locale: ID: hy_AM, Name: Armenian (Armenia)
+format locale: ID: hy_AM, Name: Armenian (Armenia)
+default charset: UTF-8
+
+OS Locale:  icelandic
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
+
+OS Locale:  id_ID
+default locale: ID: in_ID, Name: Indonesian (Indonesia)
+display locale: ID: in_ID, Name: Indonesian (Indonesia)
+format locale: ID: in_ID, Name: Indonesian (Indonesia)
+default charset: ISO-8859-1
+
+OS Locale:  id_ID.iso88591
+default locale: ID: in_ID, Name: Indonesian (Indonesia)
+display locale: ID: in_ID, Name: Indonesian (Indonesia)
+format locale: ID: in_ID, Name: Indonesian (Indonesia)
+default charset: ISO-8859-1
+
+OS Locale:  id_ID.utf8
+default locale: ID: in_ID, Name: Indonesian (Indonesia)
+display locale: ID: in_ID, Name: Indonesian (Indonesia)
+format locale: ID: in_ID, Name: Indonesian (Indonesia)
+default charset: UTF-8
+
+OS Locale:  is_IS
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
+
+OS Locale:  is_IS.iso88591
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
+
+OS Locale:  is_IS.utf8
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: UTF-8
+
+OS Locale:  it_CH
+default locale: ID: it_CH, Name: Italian (Switzerland)
+display locale: ID: it_CH, Name: Italian (Switzerland)
+format locale: ID: it_CH, Name: Italian (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  it_CH.iso88591
+default locale: ID: it_CH, Name: Italian (Switzerland)
+display locale: ID: it_CH, Name: Italian (Switzerland)
+format locale: ID: it_CH, Name: Italian (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  it_CH.utf8
+default locale: ID: it_CH, Name: Italian (Switzerland)
+display locale: ID: it_CH, Name: Italian (Switzerland)
+format locale: ID: it_CH, Name: Italian (Switzerland)
+default charset: UTF-8
+
+OS Locale:  it_IT
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  it_IT.iso88591
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  it_IT.iso885915@euro
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  it_IT.utf8
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: UTF-8
+
+OS Locale:  it_IT@euro
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  italian
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  iw_IL
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  iw_IL.iso88598
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  iw_IL.utf8
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: UTF-8
+
+OS Locale:  ja_JP
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  ja_JP.eucjp
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  ja_JP.ujis
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  ja_JP.utf8
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: UTF-8
+
+OS Locale:  japanese
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  japanese.euc
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  ka_GE
+default locale: ID: ka_GE, Name: Georgian (Georgia)
+display locale: ID: ka_GE, Name: Georgian (Georgia)
+format locale: ID: ka_GE, Name: Georgian (Georgia)
+default charset: UTF-8
+
+OS Locale:  ka_GE.georgianps
+default locale: ID: ka_GE, Name: Georgian (Georgia)
+display locale: ID: ka_GE, Name: Georgian (Georgia)
+format locale: ID: ka_GE, Name: Georgian (Georgia)
+default charset: UTF-8
+
+OS Locale:  ka_GE.utf8
+default locale: ID: ka_GE, Name: Georgian (Georgia)
+display locale: ID: ka_GE, Name: Georgian (Georgia)
+format locale: ID: ka_GE, Name: Georgian (Georgia)
+default charset: UTF-8
+
+OS Locale:  kk_KZ
+default locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+display locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+format locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+default charset: UTF-8
+
+OS Locale:  kk_KZ.pt154
+default locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+display locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+format locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+default charset: UTF-8
+
+OS Locale:  kk_KZ.utf8
+default locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+display locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+format locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+default charset: UTF-8
+
+OS Locale:  kl_GL
+default locale: ID: kl_GL, Name: Greenlandic (Greenland)
+display locale: ID: kl_GL, Name: Greenlandic (Greenland)
+format locale: ID: kl_GL, Name: Greenlandic (Greenland)
+default charset: ISO-8859-1
+
+OS Locale:  kl_GL.iso88591
+default locale: ID: kl_GL, Name: Greenlandic (Greenland)
+display locale: ID: kl_GL, Name: Greenlandic (Greenland)
+format locale: ID: kl_GL, Name: Greenlandic (Greenland)
+default charset: ISO-8859-1
+
+OS Locale:  kl_GL.utf8
+default locale: ID: kl_GL, Name: Greenlandic (Greenland)
+display locale: ID: kl_GL, Name: Greenlandic (Greenland)
+format locale: ID: kl_GL, Name: Greenlandic (Greenland)
+default charset: UTF-8
+
+OS Locale:  km_KH
+default locale: ID: km_KH, Name: Khmer (Cambodia)
+display locale: ID: km_KH, Name: Khmer (Cambodia)
+format locale: ID: km_KH, Name: Khmer (Cambodia)
+default charset: UTF-8
+
+OS Locale:  km_KH.utf8
+default locale: ID: km_KH, Name: Khmer (Cambodia)
+display locale: ID: km_KH, Name: Khmer (Cambodia)
+format locale: ID: km_KH, Name: Khmer (Cambodia)
+default charset: UTF-8
+
+OS Locale:  kn_IN
+default locale: ID: kn_IN, Name: Kannada (India)
+display locale: ID: kn_IN, Name: Kannada (India)
+format locale: ID: kn_IN, Name: Kannada (India)
+default charset: UTF-8
+
+OS Locale:  kn_IN.utf8
+default locale: ID: kn_IN, Name: Kannada (India)
+display locale: ID: kn_IN, Name: Kannada (India)
+format locale: ID: kn_IN, Name: Kannada (India)
+default charset: UTF-8
+
+OS Locale:  ko_KR
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
+
+OS Locale:  ko_KR.euckr
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
+
+OS Locale:  ko_KR.utf8
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: UTF-8
+
+OS Locale:  korean
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: EUC-KR
+
+OS Locale:  korean.euc
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: EUC-KR
+
+OS Locale:  ku_TR
+default locale: ID: ku_TR, Name: Kurdish (Turkey)
+display locale: ID: ku_TR, Name: Kurdish (Turkey)
+format locale: ID: ku_TR, Name: Kurdish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  ku_TR.iso88599
+default locale: ID: ku_TR, Name: Kurdish (Turkey)
+display locale: ID: ku_TR, Name: Kurdish (Turkey)
+format locale: ID: ku_TR, Name: Kurdish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  ku_TR.utf8
+default locale: ID: ku_TR, Name: Kurdish (Turkey)
+display locale: ID: ku_TR, Name: Kurdish (Turkey)
+format locale: ID: ku_TR, Name: Kurdish (Turkey)
+default charset: UTF-8
+
+OS Locale:  kw_GB
+default locale: ID: kw_GB, Name: Cornish (United Kingdom)
+display locale: ID: kw_GB, Name: Cornish (United Kingdom)
+format locale: ID: kw_GB, Name: Cornish (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  kw_GB.iso88591
+default locale: ID: kw_GB, Name: Cornish (United Kingdom)
+display locale: ID: kw_GB, Name: Cornish (United Kingdom)
+format locale: ID: kw_GB, Name: Cornish (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  kw_GB.utf8
+default locale: ID: kw_GB, Name: Cornish (United Kingdom)
+display locale: ID: kw_GB, Name: Cornish (United Kingdom)
+format locale: ID: kw_GB, Name: Cornish (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  ky_KG
+default locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+display locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+format locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+default charset: UTF-8
+
+OS Locale:  ky_KG.utf8
+default locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+display locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+format locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+default charset: UTF-8
+
+OS Locale:  lg_UG
+default locale: ID: lg_UG, Name: Ganda (Uganda)
+display locale: ID: lg_UG, Name: Ganda (Uganda)
+format locale: ID: lg_UG, Name: Ganda (Uganda)
+default charset: UTF-8
+
+OS Locale:  lg_UG.iso885910
+default locale: ID: lg_UG, Name: Ganda (Uganda)
+display locale: ID: lg_UG, Name: Ganda (Uganda)
+format locale: ID: lg_UG, Name: Ganda (Uganda)
+default charset: UTF-8
+
+OS Locale:  lg_UG.utf8
+default locale: ID: lg_UG, Name: Ganda (Uganda)
+display locale: ID: lg_UG, Name: Ganda (Uganda)
+format locale: ID: lg_UG, Name: Ganda (Uganda)
+default charset: UTF-8
+
+OS Locale:  lithuanian
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-13
+
+OS Locale:  lo_LA
+default locale: ID: lo_LA, Name: Lao (Laos)
+display locale: ID: lo_LA, Name: Lao (Laos)
+format locale: ID: lo_LA, Name: Lao (Laos)
+default charset: UTF-8
+
+OS Locale:  lo_LA.utf8
+default locale: ID: lo_LA, Name: Lao (Laos)
+display locale: ID: lo_LA, Name: Lao (Laos)
+format locale: ID: lo_LA, Name: Lao (Laos)
+default charset: UTF-8
+
+OS Locale:  lt_LT
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
+
+OS Locale:  lt_LT.iso885913
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
+
+OS Locale:  lt_LT.utf8
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: UTF-8
+
+OS Locale:  lv_LV
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
+
+OS Locale:  lv_LV.iso885913
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
+
+OS Locale:  lv_LV.utf8
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: UTF-8
+
+OS Locale:  mai_IN
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: UTF-8
+
+OS Locale:  mai_IN.utf8
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: UTF-8
+
+OS Locale:  mg_MG
+default locale: ID: mg_MG, Name: Malagasy (Madagascar)
+display locale: ID: mg_MG, Name: Malagasy (Madagascar)
+format locale: ID: mg_MG, Name: Malagasy (Madagascar)
+default charset: ISO-8859-15
+
+OS Locale:  mg_MG.iso885915
+default locale: ID: mg_MG, Name: Malagasy (Madagascar)
+display locale: ID: mg_MG, Name: Malagasy (Madagascar)
+format locale: ID: mg_MG, Name: Malagasy (Madagascar)
+default charset: ISO-8859-15
+
+OS Locale:  mg_MG.utf8
+default locale: ID: mg_MG, Name: Malagasy (Madagascar)
+display locale: ID: mg_MG, Name: Malagasy (Madagascar)
+format locale: ID: mg_MG, Name: Malagasy (Madagascar)
+default charset: UTF-8
+
+OS Locale:  mi_NZ
+default locale: ID: mi_NZ, Name: Maori (New Zealand)
+display locale: ID: mi_NZ, Name: Maori (New Zealand)
+format locale: ID: mi_NZ, Name: Maori (New Zealand)
+default charset: ISO-8859-13
+
+OS Locale:  mi_NZ.iso885913
+default locale: ID: mi_NZ, Name: Maori (New Zealand)
+display locale: ID: mi_NZ, Name: Maori (New Zealand)
+format locale: ID: mi_NZ, Name: Maori (New Zealand)
+default charset: ISO-8859-13
+
+OS Locale:  mi_NZ.utf8
+default locale: ID: mi_NZ, Name: Maori (New Zealand)
+display locale: ID: mi_NZ, Name: Maori (New Zealand)
+format locale: ID: mi_NZ, Name: Maori (New Zealand)
+default charset: UTF-8
+
+OS Locale:  mk_MK
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: ISO-8859-5
+
+OS Locale:  mk_MK.iso88595
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: ISO-8859-5
+
+OS Locale:  mk_MK.utf8
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: UTF-8
+
+OS Locale:  ml_IN
+default locale: ID: ml_IN, Name: Malayalam (India)
+display locale: ID: ml_IN, Name: Malayalam (India)
+format locale: ID: ml_IN, Name: Malayalam (India)
+default charset: UTF-8
+
+OS Locale:  ml_IN.utf8
+default locale: ID: ml_IN, Name: Malayalam (India)
+display locale: ID: ml_IN, Name: Malayalam (India)
+format locale: ID: ml_IN, Name: Malayalam (India)
+default charset: UTF-8
+
+OS Locale:  mn_MN
+default locale: ID: mn_MN, Name: Mongolian (Mongolia)
+display locale: ID: mn_MN, Name: Mongolian (Mongolia)
+format locale: ID: mn_MN, Name: Mongolian (Mongolia)
+default charset: UTF-8
+
+OS Locale:  mn_MN.utf8
+default locale: ID: mn_MN, Name: Mongolian (Mongolia)
+display locale: ID: mn_MN, Name: Mongolian (Mongolia)
+format locale: ID: mn_MN, Name: Mongolian (Mongolia)
+default charset: UTF-8
+
+OS Locale:  mr_IN
+default locale: ID: mr_IN, Name: Marathi (India)
+display locale: ID: mr_IN, Name: Marathi (India)
+format locale: ID: mr_IN, Name: Marathi (India)
+default charset: UTF-8
+
+OS Locale:  mr_IN.utf8
+default locale: ID: mr_IN, Name: Marathi (India)
+display locale: ID: mr_IN, Name: Marathi (India)
+format locale: ID: mr_IN, Name: Marathi (India)
+default charset: UTF-8
+
+OS Locale:  ms_MY
+default locale: ID: ms_MY, Name: Malay (Malaysia)
+display locale: ID: ms_MY, Name: Malay (Malaysia)
+format locale: ID: ms_MY, Name: Malay (Malaysia)
+default charset: ISO-8859-1
+
+OS Locale:  ms_MY.iso88591
+default locale: ID: ms_MY, Name: Malay (Malaysia)
+display locale: ID: ms_MY, Name: Malay (Malaysia)
+format locale: ID: ms_MY, Name: Malay (Malaysia)
+default charset: ISO-8859-1
+
+OS Locale:  ms_MY.utf8
+default locale: ID: ms_MY, Name: Malay (Malaysia)
+display locale: ID: ms_MY, Name: Malay (Malaysia)
+format locale: ID: ms_MY, Name: Malay (Malaysia)
+default charset: UTF-8
+
+OS Locale:  mt_MT
+default locale: ID: mt_MT, Name: Maltese (Malta)
+display locale: ID: mt_MT, Name: Maltese (Malta)
+format locale: ID: mt_MT, Name: Maltese (Malta)
+default charset: ISO-8859-3
+
+OS Locale:  mt_MT.iso88593
+default locale: ID: mt_MT, Name: Maltese (Malta)
+display locale: ID: mt_MT, Name: Maltese (Malta)
+format locale: ID: mt_MT, Name: Maltese (Malta)
+default charset: ISO-8859-3
+
+OS Locale:  mt_MT.utf8
+default locale: ID: mt_MT, Name: Maltese (Malta)
+display locale: ID: mt_MT, Name: Maltese (Malta)
+format locale: ID: mt_MT, Name: Maltese (Malta)
+default charset: UTF-8
+
+OS Locale:  nb_NO
+default locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+display locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+format locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nb_NO.iso88591
+default locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+display locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+format locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nb_NO.utf8
+default locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+display locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+format locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+default charset: UTF-8
+
+OS Locale:  ne_NP
+default locale: ID: ne_NP, Name: Nepali (Nepal)
+display locale: ID: ne_NP, Name: Nepali (Nepal)
+format locale: ID: ne_NP, Name: Nepali (Nepal)
+default charset: UTF-8
+
+OS Locale:  ne_NP.utf8
+default locale: ID: ne_NP, Name: Nepali (Nepal)
+display locale: ID: ne_NP, Name: Nepali (Nepal)
+format locale: ID: ne_NP, Name: Nepali (Nepal)
+default charset: UTF-8
+
+OS Locale:  nl_BE
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  nl_BE.iso88591
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  nl_BE.iso885915@euro
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  nl_BE.utf8
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: UTF-8
+
+OS Locale:  nl_BE@euro
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  nl_NL
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  nl_NL.iso88591
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  nl_NL.iso885915@euro
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
+
+OS Locale:  nl_NL.utf8
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: UTF-8
+
+OS Locale:  nl_NL@euro
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
+
+OS Locale:  nn_NO
+default locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+display locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+format locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nn_NO.iso88591
+default locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+display locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+format locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nn_NO.utf8
+default locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+display locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+format locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+default charset: UTF-8
+
+OS Locale:  no_NO
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  no_NO.iso88591
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  no_NO.utf8
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: UTF-8
+
+OS Locale:  norwegian
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nr_ZA
+default locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+display locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+format locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+default charset: UTF-8
+
+OS Locale:  nr_ZA.utf8
+default locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+display locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+format locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+default charset: UTF-8
+
+OS Locale:  nso_ZA
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: UTF-8
+
+OS Locale:  nso_ZA.utf8
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: UTF-8
+
+OS Locale:  nynorsk
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  oc_FR
+default locale: ID: oc_FR, Name: Occitan (France)
+display locale: ID: oc_FR, Name: Occitan (France)
+format locale: ID: oc_FR, Name: Occitan (France)
+default charset: ISO-8859-1
+
+OS Locale:  oc_FR.iso88591
+default locale: ID: oc_FR, Name: Occitan (France)
+display locale: ID: oc_FR, Name: Occitan (France)
+format locale: ID: oc_FR, Name: Occitan (France)
+default charset: ISO-8859-1
+
+OS Locale:  oc_FR.utf8
+default locale: ID: oc_FR, Name: Occitan (France)
+display locale: ID: oc_FR, Name: Occitan (France)
+format locale: ID: oc_FR, Name: Occitan (France)
+default charset: UTF-8
+
+OS Locale:  om_ET
+default locale: ID: om_ET, Name: Oromo (Ethiopia)
+display locale: ID: om_ET, Name: Oromo (Ethiopia)
+format locale: ID: om_ET, Name: Oromo (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  om_ET.utf8
+default locale: ID: om_ET, Name: Oromo (Ethiopia)
+display locale: ID: om_ET, Name: Oromo (Ethiopia)
+format locale: ID: om_ET, Name: Oromo (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  om_KE
+default locale: ID: om_KE, Name: Oromo (Kenya)
+display locale: ID: om_KE, Name: Oromo (Kenya)
+format locale: ID: om_KE, Name: Oromo (Kenya)
+default charset: ISO-8859-1
+
+OS Locale:  om_KE.iso88591
+default locale: ID: om_KE, Name: Oromo (Kenya)
+display locale: ID: om_KE, Name: Oromo (Kenya)
+format locale: ID: om_KE, Name: Oromo (Kenya)
+default charset: ISO-8859-1
+
+OS Locale:  om_KE.utf8
+default locale: ID: om_KE, Name: Oromo (Kenya)
+display locale: ID: om_KE, Name: Oromo (Kenya)
+format locale: ID: om_KE, Name: Oromo (Kenya)
+default charset: UTF-8
+
+OS Locale:  or_IN
+default locale: ID: or_IN, Name: Oriya (India)
+display locale: ID: or_IN, Name: Oriya (India)
+format locale: ID: or_IN, Name: Oriya (India)
+default charset: UTF-8
+
+OS Locale:  or_IN.utf8
+default locale: ID: or_IN, Name: Oriya (India)
+display locale: ID: or_IN, Name: Oriya (India)
+format locale: ID: or_IN, Name: Oriya (India)
+default charset: UTF-8
+
+OS Locale:  pa_IN
+default locale: ID: pa_IN, Name: Panjabi (India)
+display locale: ID: pa_IN, Name: Panjabi (India)
+format locale: ID: pa_IN, Name: Panjabi (India)
+default charset: UTF-8
+
+OS Locale:  pa_IN.utf8
+default locale: ID: pa_IN, Name: Panjabi (India)
+display locale: ID: pa_IN, Name: Panjabi (India)
+format locale: ID: pa_IN, Name: Panjabi (India)
+default charset: UTF-8
+
+OS Locale:  pa_PK
+default locale: ID: pa_PK, Name: Panjabi (Pakistan)
+display locale: ID: pa_PK, Name: Panjabi (Pakistan)
+format locale: ID: pa_PK, Name: Panjabi (Pakistan)
+default charset: UTF-8
+
+OS Locale:  pa_PK.utf8
+default locale: ID: pa_PK, Name: Panjabi (Pakistan)
+display locale: ID: pa_PK, Name: Panjabi (Pakistan)
+format locale: ID: pa_PK, Name: Panjabi (Pakistan)
+default charset: UTF-8
+
+OS Locale:  pl_PL
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  pl_PL.iso88592
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  pl_PL.utf8
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: UTF-8
+
+OS Locale:  polish
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  portuguese
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt_BR
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: ISO-8859-1
+
+OS Locale:  pt_BR.iso88591
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: ISO-8859-1
+
+OS Locale:  pt_BR.utf8
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: UTF-8
+
+OS Locale:  pt_PT
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt_PT.iso88591
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt_PT.iso885915@euro
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
+
+OS Locale:  pt_PT.utf8
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: UTF-8
+
+OS Locale:  pt_PT@euro
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
+
+OS Locale:  ro_RO
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
+
+OS Locale:  ro_RO.iso88592
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
+
+OS Locale:  ro_RO.utf8
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: UTF-8
+
+OS Locale:  romanian
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
+
+OS Locale:  ru_RU
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  ru_RU.iso88595
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  ru_RU.koi8r
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: KOI8-R
+
+OS Locale:  ru_RU.utf8
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: UTF-8
+
+OS Locale:  ru_UA
+default locale: ID: ru_UA, Name: Russian (Ukraine)
+display locale: ID: ru_UA, Name: Russian (Ukraine)
+format locale: ID: ru_UA, Name: Russian (Ukraine)
+default charset: KOI8-U
+
+OS Locale:  ru_UA.koi8u
+default locale: ID: ru_UA, Name: Russian (Ukraine)
+display locale: ID: ru_UA, Name: Russian (Ukraine)
+format locale: ID: ru_UA, Name: Russian (Ukraine)
+default charset: KOI8-U
+
+OS Locale:  ru_UA.utf8
+default locale: ID: ru_UA, Name: Russian (Ukraine)
+display locale: ID: ru_UA, Name: Russian (Ukraine)
+format locale: ID: ru_UA, Name: Russian (Ukraine)
+default charset: UTF-8
+
+OS Locale:  russian
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  rw_RW
+default locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+display locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+format locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+default charset: UTF-8
+
+OS Locale:  rw_RW.utf8
+default locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+display locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+format locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+default charset: UTF-8
+
+OS Locale:  se_NO
+default locale: ID: se_NO, Name: Northern Sami (Norway)
+display locale: ID: se_NO, Name: Northern Sami (Norway)
+format locale: ID: se_NO, Name: Northern Sami (Norway)
+default charset: UTF-8
+
+OS Locale:  se_NO.utf8
+default locale: ID: se_NO, Name: Northern Sami (Norway)
+display locale: ID: se_NO, Name: Northern Sami (Norway)
+format locale: ID: se_NO, Name: Northern Sami (Norway)
+default charset: UTF-8
+
+OS Locale:  si_LK
+default locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+display locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+format locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+default charset: UTF-8
+
+OS Locale:  si_LK.utf8
+default locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+display locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+format locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+default charset: UTF-8
+
+OS Locale:  sid_ET
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  sid_ET.utf8
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  sk_SK
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
+
+OS Locale:  sk_SK.iso88592
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
+
+OS Locale:  sk_SK.utf8
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: UTF-8
+
+OS Locale:  sl_SI
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  sl_SI.iso88592
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  sl_SI.utf8
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: UTF-8
+
+OS Locale:  slovak
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
+
+OS Locale:  slovene
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  slovenian
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  so_DJ
+default locale: ID: so_DJ, Name: Somali (Djibouti)
+display locale: ID: so_DJ, Name: Somali (Djibouti)
+format locale: ID: so_DJ, Name: Somali (Djibouti)
+default charset: ISO-8859-1
+
+OS Locale:  so_DJ.iso88591
+default locale: ID: so_DJ, Name: Somali (Djibouti)
+display locale: ID: so_DJ, Name: Somali (Djibouti)
+format locale: ID: so_DJ, Name: Somali (Djibouti)
+default charset: ISO-8859-1
+
+OS Locale:  so_DJ.utf8
+default locale: ID: so_DJ, Name: Somali (Djibouti)
+display locale: ID: so_DJ, Name: Somali (Djibouti)
+format locale: ID: so_DJ, Name: Somali (Djibouti)
+default charset: UTF-8
+
+OS Locale:  so_ET
+default locale: ID: so_ET, Name: Somali (Ethiopia)
+display locale: ID: so_ET, Name: Somali (Ethiopia)
+format locale: ID: so_ET, Name: Somali (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  so_ET.utf8
+default locale: ID: so_ET, Name: Somali (Ethiopia)
+display locale: ID: so_ET, Name: Somali (Ethiopia)
+format locale: ID: so_ET, Name: Somali (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  so_KE
+default locale: ID: so_KE, Name: Somali (Kenya)
+display locale: ID: so_KE, Name: Somali (Kenya)
+format locale: ID: so_KE, Name: Somali (Kenya)
+default charset: ISO-8859-1
+
+OS Locale:  so_KE.iso88591
+default locale: ID: so_KE, Name: Somali (Kenya)
+display locale: ID: so_KE, Name: Somali (Kenya)
+format locale: ID: so_KE, Name: Somali (Kenya)
+default charset: ISO-8859-1
+
+OS Locale:  so_KE.utf8
+default locale: ID: so_KE, Name: Somali (Kenya)
+display locale: ID: so_KE, Name: Somali (Kenya)
+format locale: ID: so_KE, Name: Somali (Kenya)
+default charset: UTF-8
+
+OS Locale:  so_SO
+default locale: ID: so_SO, Name: Somali (Somalia)
+display locale: ID: so_SO, Name: Somali (Somalia)
+format locale: ID: so_SO, Name: Somali (Somalia)
+default charset: ISO-8859-1
+
+OS Locale:  so_SO.iso88591
+default locale: ID: so_SO, Name: Somali (Somalia)
+display locale: ID: so_SO, Name: Somali (Somalia)
+format locale: ID: so_SO, Name: Somali (Somalia)
+default charset: ISO-8859-1
+
+OS Locale:  so_SO.utf8
+default locale: ID: so_SO, Name: Somali (Somalia)
+display locale: ID: so_SO, Name: Somali (Somalia)
+format locale: ID: so_SO, Name: Somali (Somalia)
+default charset: UTF-8
+
+OS Locale:  spanish
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  sq_AL
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: ISO-8859-1
+
+OS Locale:  sq_AL.iso88591
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: ISO-8859-1
+
+OS Locale:  sq_AL.utf8
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: UTF-8
+
+OS Locale:  sr_CS
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: ISO-8859-5
+
+OS Locale:  sr_CS.iso88595
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: ISO-8859-5
+
+OS Locale:  sr_CS.utf8
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: UTF-8
+
+OS Locale:  sr_ME
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_ME.utf8
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_RS
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_RS.utf8
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_RS.utf8@latin
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_RS@latin
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  ss_ZA
+default locale: ID: ss_ZA, Name: Swati (South Africa)
+display locale: ID: ss_ZA, Name: Swati (South Africa)
+format locale: ID: ss_ZA, Name: Swati (South Africa)
+default charset: UTF-8
+
+OS Locale:  ss_ZA.utf8
+default locale: ID: ss_ZA, Name: Swati (South Africa)
+display locale: ID: ss_ZA, Name: Swati (South Africa)
+format locale: ID: ss_ZA, Name: Swati (South Africa)
+default charset: UTF-8
+
+OS Locale:  st_ZA
+default locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+display locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+format locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  st_ZA.iso88591
+default locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+display locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+format locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  st_ZA.utf8
+default locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+display locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+format locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+default charset: UTF-8
+
+OS Locale:  sv_FI
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  sv_FI.iso88591
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  sv_FI.iso885915@euro
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  sv_FI.utf8
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: UTF-8
+
+OS Locale:  sv_FI@euro
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  sv_SE
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  sv_SE.iso88591
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  sv_SE.iso885915
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-15
+
+OS Locale:  sv_SE.utf8
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: UTF-8
+
+OS Locale:  swedish
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  ta_IN
+default locale: ID: ta_IN, Name: Tamil (India)
+display locale: ID: ta_IN, Name: Tamil (India)
+format locale: ID: ta_IN, Name: Tamil (India)
+default charset: UTF-8
+
+OS Locale:  ta_IN.utf8
+default locale: ID: ta_IN, Name: Tamil (India)
+display locale: ID: ta_IN, Name: Tamil (India)
+format locale: ID: ta_IN, Name: Tamil (India)
+default charset: UTF-8
+
+OS Locale:  te_IN
+default locale: ID: te_IN, Name: Telugu (India)
+display locale: ID: te_IN, Name: Telugu (India)
+format locale: ID: te_IN, Name: Telugu (India)
+default charset: UTF-8
+
+OS Locale:  te_IN.utf8
+default locale: ID: te_IN, Name: Telugu (India)
+display locale: ID: te_IN, Name: Telugu (India)
+format locale: ID: te_IN, Name: Telugu (India)
+default charset: UTF-8
+
+OS Locale:  tg_TJ
+default locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+display locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: UTF-8
+
+OS Locale:  tg_TJ.koi8t
+default locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+display locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: UTF-8
+
+OS Locale:  tg_TJ.utf8
+default locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+display locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: UTF-8
+
+OS Locale:  th_TH
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
+
+OS Locale:  th_TH.tis620
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
+
+OS Locale:  th_TH.utf8
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: UTF-8
+
+OS Locale:  thai
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: TIS-620
+
+OS Locale:  ti_ER
+default locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+display locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+format locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+default charset: UTF-8
+
+OS Locale:  ti_ER.utf8
+default locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+display locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+format locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+default charset: UTF-8
+
+OS Locale:  ti_ET
+default locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+display locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+format locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  ti_ET.utf8
+default locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+display locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+format locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  tig_ER
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  tig_ER.utf8
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  tl_PH
+default locale: ID: tl_PH, Name: Tagalog (Philippines)
+display locale: ID: tl_PH, Name: Tagalog (Philippines)
+format locale: ID: tl_PH, Name: Tagalog (Philippines)
+default charset: ISO-8859-1
+
+OS Locale:  tl_PH.iso88591
+default locale: ID: tl_PH, Name: Tagalog (Philippines)
+display locale: ID: tl_PH, Name: Tagalog (Philippines)
+format locale: ID: tl_PH, Name: Tagalog (Philippines)
+default charset: ISO-8859-1
+
+OS Locale:  tl_PH.utf8
+default locale: ID: tl_PH, Name: Tagalog (Philippines)
+display locale: ID: tl_PH, Name: Tagalog (Philippines)
+format locale: ID: tl_PH, Name: Tagalog (Philippines)
+default charset: UTF-8
+
+OS Locale:  tn_ZA
+default locale: ID: tn_ZA, Name: Tswana (South Africa)
+display locale: ID: tn_ZA, Name: Tswana (South Africa)
+format locale: ID: tn_ZA, Name: Tswana (South Africa)
+default charset: UTF-8
+
+OS Locale:  tn_ZA.utf8
+default locale: ID: tn_ZA, Name: Tswana (South Africa)
+display locale: ID: tn_ZA, Name: Tswana (South Africa)
+format locale: ID: tn_ZA, Name: Tswana (South Africa)
+default charset: UTF-8
+
+OS Locale:  tr_CY
+default locale: ID: tr_CY, Name: Turkish (Cyprus)
+display locale: ID: tr_CY, Name: Turkish (Cyprus)
+format locale: ID: tr_CY, Name: Turkish (Cyprus)
+default charset: ISO-8859-9
+
+OS Locale:  tr_CY.iso88599
+default locale: ID: tr_CY, Name: Turkish (Cyprus)
+display locale: ID: tr_CY, Name: Turkish (Cyprus)
+format locale: ID: tr_CY, Name: Turkish (Cyprus)
+default charset: ISO-8859-9
+
+OS Locale:  tr_CY.utf8
+default locale: ID: tr_CY, Name: Turkish (Cyprus)
+display locale: ID: tr_CY, Name: Turkish (Cyprus)
+format locale: ID: tr_CY, Name: Turkish (Cyprus)
+default charset: UTF-8
+
+OS Locale:  tr_TR
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  tr_TR.iso88599
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  tr_TR.utf8
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: UTF-8
+
+OS Locale:  ts_ZA
+default locale: ID: ts_ZA, Name: Tsonga (South Africa)
+display locale: ID: ts_ZA, Name: Tsonga (South Africa)
+format locale: ID: ts_ZA, Name: Tsonga (South Africa)
+default charset: UTF-8
+
+OS Locale:  ts_ZA.utf8
+default locale: ID: ts_ZA, Name: Tsonga (South Africa)
+display locale: ID: ts_ZA, Name: Tsonga (South Africa)
+format locale: ID: ts_ZA, Name: Tsonga (South Africa)
+default charset: UTF-8
+
+OS Locale:  tt_RU.utf8
+default locale: ID: tt_RU, Name: Tatar (Russia)
+display locale: ID: tt_RU, Name: Tatar (Russia)
+format locale: ID: tt_RU, Name: Tatar (Russia)
+default charset: UTF-8
+
+OS Locale:  turkish
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  uk_UA
+default locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+display locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+format locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+default charset: KOI8-U
+
+OS Locale:  uk_UA.koi8u
+default locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+display locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+format locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+default charset: KOI8-U
+
+OS Locale:  uk_UA.utf8
+default locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+display locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+format locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+default charset: UTF-8
+
+OS Locale:  ur_PK
+default locale: ID: ur_PK, Name: Urdu (Pakistan)
+display locale: ID: ur_PK, Name: Urdu (Pakistan)
+format locale: ID: ur_PK, Name: Urdu (Pakistan)
+default charset: UTF-8
+
+OS Locale:  ur_PK.utf8
+default locale: ID: ur_PK, Name: Urdu (Pakistan)
+display locale: ID: ur_PK, Name: Urdu (Pakistan)
+format locale: ID: ur_PK, Name: Urdu (Pakistan)
+default charset: UTF-8
+
+OS Locale:  uz_UZ
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: ISO-8859-1
+
+OS Locale:  uz_UZ.iso88591
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: ISO-8859-1
+
+OS Locale:  uz_UZ.utf8@cyrillic
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: UTF-8
+
+OS Locale:  uz_UZ@cyrillic
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: UTF-8
+
+OS Locale:  ve_ZA
+default locale: ID: ve_ZA, Name: Venda (South Africa)
+display locale: ID: ve_ZA, Name: Venda (South Africa)
+format locale: ID: ve_ZA, Name: Venda (South Africa)
+default charset: UTF-8
+
+OS Locale:  ve_ZA.utf8
+default locale: ID: ve_ZA, Name: Venda (South Africa)
+display locale: ID: ve_ZA, Name: Venda (South Africa)
+format locale: ID: ve_ZA, Name: Venda (South Africa)
+default charset: UTF-8
+
+OS Locale:  vi_VN
+default locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+display locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+format locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+default charset: UTF-8
+
+OS Locale:  vi_VN.tcvn
+default locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+display locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+format locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+default charset: UTF-8
+
+OS Locale:  vi_VN.utf8
+default locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+display locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+format locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+default charset: UTF-8
+
+OS Locale:  wa_BE
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  wa_BE.iso88591
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  wa_BE.iso885915@euro
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  wa_BE.utf8
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: UTF-8
+
+OS Locale:  wa_BE@euro
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  xh_ZA
+default locale: ID: xh_ZA, Name: Xhosa (South Africa)
+display locale: ID: xh_ZA, Name: Xhosa (South Africa)
+format locale: ID: xh_ZA, Name: Xhosa (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  xh_ZA.iso88591
+default locale: ID: xh_ZA, Name: Xhosa (South Africa)
+display locale: ID: xh_ZA, Name: Xhosa (South Africa)
+format locale: ID: xh_ZA, Name: Xhosa (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  xh_ZA.utf8
+default locale: ID: xh_ZA, Name: Xhosa (South Africa)
+display locale: ID: xh_ZA, Name: Xhosa (South Africa)
+format locale: ID: xh_ZA, Name: Xhosa (South Africa)
+default charset: UTF-8
+
+OS Locale:  yi_US
+default locale: ID: ji_US, Name: Yiddish (United States)
+display locale: ID: ji_US, Name: Yiddish (United States)
+format locale: ID: ji_US, Name: Yiddish (United States)
+default charset: windows-1255
+
+OS Locale:  yi_US.cp1255
+default locale: ID: ji_US, Name: Yiddish (United States)
+display locale: ID: ji_US, Name: Yiddish (United States)
+format locale: ID: ji_US, Name: Yiddish (United States)
+default charset: windows-1255
+
+OS Locale:  yi_US.utf8
+default locale: ID: ji_US, Name: Yiddish (United States)
+display locale: ID: ji_US, Name: Yiddish (United States)
+format locale: ID: ji_US, Name: Yiddish (United States)
+default charset: UTF-8
+
+OS Locale:  zh_CN
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh_CN.gb18030
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
+
+OS Locale:  zh_CN.gb2312
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh_CN.gbk
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale:  zh_CN.utf8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale:  zh_HK
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: Big5-HKSCS
+
+OS Locale:  zh_HK.big5hkscs
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: Big5-HKSCS
+
+OS Locale:  zh_HK.utf8
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: UTF-8
+
+OS Locale:  zh_SG
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: zh_SG, Name: Chinese (Singapore)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: GB2312
+
+OS Locale:  zh_SG.gb2312
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: zh_SG, Name: Chinese (Singapore)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: GB2312
+
+OS Locale:  zh_SG.gbk
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: zh_SG, Name: Chinese (Singapore)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: GBK
+
+OS Locale:  zh_SG.utf8
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: zh_SG, Name: Chinese (Singapore)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: UTF-8
+
+OS Locale:  zh_TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: Big5
+
+OS Locale:  zh_TW.big5
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: Big5
+
+OS Locale:  zh_TW.euctw
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
+
+OS Locale:  zh_TW.utf8
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
+
+OS Locale:  zu_ZA
+default locale: ID: zu_ZA, Name: Zulu (South Africa)
+display locale: ID: zu_ZA, Name: Zulu (South Africa)
+format locale: ID: zu_ZA, Name: Zulu (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  zu_ZA.iso88591
+default locale: ID: zu_ZA, Name: Zulu (South Africa)
+display locale: ID: zu_ZA, Name: Zulu (South Africa)
+format locale: ID: zu_ZA, Name: Zulu (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  zu_ZA.utf8
+default locale: ID: zu_ZA, Name: Zulu (South Africa)
+display locale: ID: zu_ZA, Name: Zulu (South Africa)
+format locale: ID: zu_ZA, Name: Zulu (South Africa)
+default charset: UTF-8
+
+Testing some typical combinations
+
+
+OS Locale (LC_CTYPE: ja_JP.UTF-8, LC_MESSAGES: zh_CN.UTF-8)
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: UTF-8
+
+OS Locale (LC_CTYPE: zh_CN.UTF-8, LC_MESSAGES: en_US.UTF-8)
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale (LC_CTYPE: C, LC_MESSAGES: zh_CN.UTF-8)
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: en_US, Name: English (United States)
+default charset: US-ASCII
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/data/deflocale.rhel5.fmtasdefault	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,3924 @@
+Red Hat Enterprise Linux Server release 5.3 (Tikanga)
+Linux localhost.localdomain 2.6.18-128.el5 #1 SMP Wed Dec 17 11:42:39 EST 2008 i686 i686 i386 GNU/Linux
+Testing all available locales
+
+OS Locale:  C
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: US-ASCII
+
+OS Locale:  POSIX
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: US-ASCII
+
+OS Locale:  aa_DJ
+default locale: ID: aa_DJ, Name: Afar (Djibouti)
+display locale: ID: aa_DJ, Name: Afar (Djibouti)
+format locale: ID: aa_DJ, Name: Afar (Djibouti)
+default charset: ISO-8859-1
+
+OS Locale:  aa_DJ.iso88591
+default locale: ID: aa_DJ, Name: Afar (Djibouti)
+display locale: ID: aa_DJ, Name: Afar (Djibouti)
+format locale: ID: aa_DJ, Name: Afar (Djibouti)
+default charset: ISO-8859-1
+
+OS Locale:  aa_DJ.utf8
+default locale: ID: aa_DJ, Name: Afar (Djibouti)
+display locale: ID: aa_DJ, Name: Afar (Djibouti)
+format locale: ID: aa_DJ, Name: Afar (Djibouti)
+default charset: UTF-8
+
+OS Locale:  aa_ER
+default locale: ID: aa_ER, Name: Afar (Eritrea)
+display locale: ID: aa_ER, Name: Afar (Eritrea)
+format locale: ID: aa_ER, Name: Afar (Eritrea)
+default charset: UTF-8
+
+OS Locale:  aa_ER.utf8
+default locale: ID: aa_ER, Name: Afar (Eritrea)
+display locale: ID: aa_ER, Name: Afar (Eritrea)
+format locale: ID: aa_ER, Name: Afar (Eritrea)
+default charset: UTF-8
+
+OS Locale:  aa_ER.utf8@saaho
+default locale: ID: aa_ER, Name: Afar (Eritrea)
+display locale: ID: aa_ER, Name: Afar (Eritrea)
+format locale: ID: aa_ER, Name: Afar (Eritrea)
+default charset: UTF-8
+
+OS Locale:  aa_ER@saaho
+default locale: ID: aa_ER, Name: Afar (Eritrea)
+display locale: ID: aa_ER, Name: Afar (Eritrea)
+format locale: ID: aa_ER, Name: Afar (Eritrea)
+default charset: UTF-8
+
+OS Locale:  aa_ET
+default locale: ID: aa_ET, Name: Afar (Ethiopia)
+display locale: ID: aa_ET, Name: Afar (Ethiopia)
+format locale: ID: aa_ET, Name: Afar (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  aa_ET.utf8
+default locale: ID: aa_ET, Name: Afar (Ethiopia)
+display locale: ID: aa_ET, Name: Afar (Ethiopia)
+format locale: ID: aa_ET, Name: Afar (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  af_ZA
+default locale: ID: af_ZA, Name: Afrikaans (South Africa)
+display locale: ID: af_ZA, Name: Afrikaans (South Africa)
+format locale: ID: af_ZA, Name: Afrikaans (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  af_ZA.iso88591
+default locale: ID: af_ZA, Name: Afrikaans (South Africa)
+display locale: ID: af_ZA, Name: Afrikaans (South Africa)
+format locale: ID: af_ZA, Name: Afrikaans (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  af_ZA.utf8
+default locale: ID: af_ZA, Name: Afrikaans (South Africa)
+display locale: ID: af_ZA, Name: Afrikaans (South Africa)
+format locale: ID: af_ZA, Name: Afrikaans (South Africa)
+default charset: UTF-8
+
+OS Locale:  am_ET
+default locale: ID: am_ET, Name: Amharic (Ethiopia)
+display locale: ID: am_ET, Name: Amharic (Ethiopia)
+format locale: ID: am_ET, Name: Amharic (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  am_ET.utf8
+default locale: ID: am_ET, Name: Amharic (Ethiopia)
+display locale: ID: am_ET, Name: Amharic (Ethiopia)
+format locale: ID: am_ET, Name: Amharic (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  an_ES
+default locale: ID: an_ES, Name: Aragonese (Spain)
+display locale: ID: an_ES, Name: Aragonese (Spain)
+format locale: ID: an_ES, Name: Aragonese (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  an_ES.iso885915
+default locale: ID: an_ES, Name: Aragonese (Spain)
+display locale: ID: an_ES, Name: Aragonese (Spain)
+format locale: ID: an_ES, Name: Aragonese (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  an_ES.utf8
+default locale: ID: an_ES, Name: Aragonese (Spain)
+display locale: ID: an_ES, Name: Aragonese (Spain)
+format locale: ID: an_ES, Name: Aragonese (Spain)
+default charset: UTF-8
+
+OS Locale:  ar_AE
+default locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+display locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+format locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+default charset: ISO-8859-6
+
+OS Locale:  ar_AE.iso88596
+default locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+display locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+format locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+default charset: ISO-8859-6
+
+OS Locale:  ar_AE.utf8
+default locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+display locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+format locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+default charset: UTF-8
+
+OS Locale:  ar_BH
+default locale: ID: ar_BH, Name: Arabic (Bahrain)
+display locale: ID: ar_BH, Name: Arabic (Bahrain)
+format locale: ID: ar_BH, Name: Arabic (Bahrain)
+default charset: ISO-8859-6
+
+OS Locale:  ar_BH.iso88596
+default locale: ID: ar_BH, Name: Arabic (Bahrain)
+display locale: ID: ar_BH, Name: Arabic (Bahrain)
+format locale: ID: ar_BH, Name: Arabic (Bahrain)
+default charset: ISO-8859-6
+
+OS Locale:  ar_BH.utf8
+default locale: ID: ar_BH, Name: Arabic (Bahrain)
+display locale: ID: ar_BH, Name: Arabic (Bahrain)
+format locale: ID: ar_BH, Name: Arabic (Bahrain)
+default charset: UTF-8
+
+OS Locale:  ar_DZ
+default locale: ID: ar_DZ, Name: Arabic (Algeria)
+display locale: ID: ar_DZ, Name: Arabic (Algeria)
+format locale: ID: ar_DZ, Name: Arabic (Algeria)
+default charset: ISO-8859-6
+
+OS Locale:  ar_DZ.iso88596
+default locale: ID: ar_DZ, Name: Arabic (Algeria)
+display locale: ID: ar_DZ, Name: Arabic (Algeria)
+format locale: ID: ar_DZ, Name: Arabic (Algeria)
+default charset: ISO-8859-6
+
+OS Locale:  ar_DZ.utf8
+default locale: ID: ar_DZ, Name: Arabic (Algeria)
+display locale: ID: ar_DZ, Name: Arabic (Algeria)
+format locale: ID: ar_DZ, Name: Arabic (Algeria)
+default charset: UTF-8
+
+OS Locale:  ar_EG
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: ISO-8859-6
+
+OS Locale:  ar_EG.iso88596
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: ISO-8859-6
+
+OS Locale:  ar_EG.utf8
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: UTF-8
+
+OS Locale:  ar_IN
+default locale: ID: ar_IN, Name: Arabic (India)
+display locale: ID: ar_IN, Name: Arabic (India)
+format locale: ID: ar_IN, Name: Arabic (India)
+default charset: UTF-8
+
+OS Locale:  ar_IN.utf8
+default locale: ID: ar_IN, Name: Arabic (India)
+display locale: ID: ar_IN, Name: Arabic (India)
+format locale: ID: ar_IN, Name: Arabic (India)
+default charset: UTF-8
+
+OS Locale:  ar_IQ
+default locale: ID: ar_IQ, Name: Arabic (Iraq)
+display locale: ID: ar_IQ, Name: Arabic (Iraq)
+format locale: ID: ar_IQ, Name: Arabic (Iraq)
+default charset: ISO-8859-6
+
+OS Locale:  ar_IQ.iso88596
+default locale: ID: ar_IQ, Name: Arabic (Iraq)
+display locale: ID: ar_IQ, Name: Arabic (Iraq)
+format locale: ID: ar_IQ, Name: Arabic (Iraq)
+default charset: ISO-8859-6
+
+OS Locale:  ar_IQ.utf8
+default locale: ID: ar_IQ, Name: Arabic (Iraq)
+display locale: ID: ar_IQ, Name: Arabic (Iraq)
+format locale: ID: ar_IQ, Name: Arabic (Iraq)
+default charset: UTF-8
+
+OS Locale:  ar_JO
+default locale: ID: ar_JO, Name: Arabic (Jordan)
+display locale: ID: ar_JO, Name: Arabic (Jordan)
+format locale: ID: ar_JO, Name: Arabic (Jordan)
+default charset: ISO-8859-6
+
+OS Locale:  ar_JO.iso88596
+default locale: ID: ar_JO, Name: Arabic (Jordan)
+display locale: ID: ar_JO, Name: Arabic (Jordan)
+format locale: ID: ar_JO, Name: Arabic (Jordan)
+default charset: ISO-8859-6
+
+OS Locale:  ar_JO.utf8
+default locale: ID: ar_JO, Name: Arabic (Jordan)
+display locale: ID: ar_JO, Name: Arabic (Jordan)
+format locale: ID: ar_JO, Name: Arabic (Jordan)
+default charset: UTF-8
+
+OS Locale:  ar_KW
+default locale: ID: ar_KW, Name: Arabic (Kuwait)
+display locale: ID: ar_KW, Name: Arabic (Kuwait)
+format locale: ID: ar_KW, Name: Arabic (Kuwait)
+default charset: ISO-8859-6
+
+OS Locale:  ar_KW.iso88596
+default locale: ID: ar_KW, Name: Arabic (Kuwait)
+display locale: ID: ar_KW, Name: Arabic (Kuwait)
+format locale: ID: ar_KW, Name: Arabic (Kuwait)
+default charset: ISO-8859-6
+
+OS Locale:  ar_KW.utf8
+default locale: ID: ar_KW, Name: Arabic (Kuwait)
+display locale: ID: ar_KW, Name: Arabic (Kuwait)
+format locale: ID: ar_KW, Name: Arabic (Kuwait)
+default charset: UTF-8
+
+OS Locale:  ar_LB
+default locale: ID: ar_LB, Name: Arabic (Lebanon)
+display locale: ID: ar_LB, Name: Arabic (Lebanon)
+format locale: ID: ar_LB, Name: Arabic (Lebanon)
+default charset: ISO-8859-6
+
+OS Locale:  ar_LB.iso88596
+default locale: ID: ar_LB, Name: Arabic (Lebanon)
+display locale: ID: ar_LB, Name: Arabic (Lebanon)
+format locale: ID: ar_LB, Name: Arabic (Lebanon)
+default charset: ISO-8859-6
+
+OS Locale:  ar_LB.utf8
+default locale: ID: ar_LB, Name: Arabic (Lebanon)
+display locale: ID: ar_LB, Name: Arabic (Lebanon)
+format locale: ID: ar_LB, Name: Arabic (Lebanon)
+default charset: UTF-8
+
+OS Locale:  ar_LY
+default locale: ID: ar_LY, Name: Arabic (Libya)
+display locale: ID: ar_LY, Name: Arabic (Libya)
+format locale: ID: ar_LY, Name: Arabic (Libya)
+default charset: ISO-8859-6
+
+OS Locale:  ar_LY.iso88596
+default locale: ID: ar_LY, Name: Arabic (Libya)
+display locale: ID: ar_LY, Name: Arabic (Libya)
+format locale: ID: ar_LY, Name: Arabic (Libya)
+default charset: ISO-8859-6
+
+OS Locale:  ar_LY.utf8
+default locale: ID: ar_LY, Name: Arabic (Libya)
+display locale: ID: ar_LY, Name: Arabic (Libya)
+format locale: ID: ar_LY, Name: Arabic (Libya)
+default charset: UTF-8
+
+OS Locale:  ar_MA
+default locale: ID: ar_MA, Name: Arabic (Morocco)
+display locale: ID: ar_MA, Name: Arabic (Morocco)
+format locale: ID: ar_MA, Name: Arabic (Morocco)
+default charset: ISO-8859-6
+
+OS Locale:  ar_MA.iso88596
+default locale: ID: ar_MA, Name: Arabic (Morocco)
+display locale: ID: ar_MA, Name: Arabic (Morocco)
+format locale: ID: ar_MA, Name: Arabic (Morocco)
+default charset: ISO-8859-6
+
+OS Locale:  ar_MA.utf8
+default locale: ID: ar_MA, Name: Arabic (Morocco)
+display locale: ID: ar_MA, Name: Arabic (Morocco)
+format locale: ID: ar_MA, Name: Arabic (Morocco)
+default charset: UTF-8
+
+OS Locale:  ar_OM
+default locale: ID: ar_OM, Name: Arabic (Oman)
+display locale: ID: ar_OM, Name: Arabic (Oman)
+format locale: ID: ar_OM, Name: Arabic (Oman)
+default charset: ISO-8859-6
+
+OS Locale:  ar_OM.iso88596
+default locale: ID: ar_OM, Name: Arabic (Oman)
+display locale: ID: ar_OM, Name: Arabic (Oman)
+format locale: ID: ar_OM, Name: Arabic (Oman)
+default charset: ISO-8859-6
+
+OS Locale:  ar_OM.utf8
+default locale: ID: ar_OM, Name: Arabic (Oman)
+display locale: ID: ar_OM, Name: Arabic (Oman)
+format locale: ID: ar_OM, Name: Arabic (Oman)
+default charset: UTF-8
+
+OS Locale:  ar_QA
+default locale: ID: ar_QA, Name: Arabic (Qatar)
+display locale: ID: ar_QA, Name: Arabic (Qatar)
+format locale: ID: ar_QA, Name: Arabic (Qatar)
+default charset: ISO-8859-6
+
+OS Locale:  ar_QA.iso88596
+default locale: ID: ar_QA, Name: Arabic (Qatar)
+display locale: ID: ar_QA, Name: Arabic (Qatar)
+format locale: ID: ar_QA, Name: Arabic (Qatar)
+default charset: ISO-8859-6
+
+OS Locale:  ar_QA.utf8
+default locale: ID: ar_QA, Name: Arabic (Qatar)
+display locale: ID: ar_QA, Name: Arabic (Qatar)
+format locale: ID: ar_QA, Name: Arabic (Qatar)
+default charset: UTF-8
+
+OS Locale:  ar_SA
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SA.iso88596
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SA.utf8
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: UTF-8
+
+OS Locale:  ar_SD
+default locale: ID: ar_SD, Name: Arabic (Sudan)
+display locale: ID: ar_SD, Name: Arabic (Sudan)
+format locale: ID: ar_SD, Name: Arabic (Sudan)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SD.iso88596
+default locale: ID: ar_SD, Name: Arabic (Sudan)
+display locale: ID: ar_SD, Name: Arabic (Sudan)
+format locale: ID: ar_SD, Name: Arabic (Sudan)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SD.utf8
+default locale: ID: ar_SD, Name: Arabic (Sudan)
+display locale: ID: ar_SD, Name: Arabic (Sudan)
+format locale: ID: ar_SD, Name: Arabic (Sudan)
+default charset: UTF-8
+
+OS Locale:  ar_SY
+default locale: ID: ar_SY, Name: Arabic (Syria)
+display locale: ID: ar_SY, Name: Arabic (Syria)
+format locale: ID: ar_SY, Name: Arabic (Syria)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SY.iso88596
+default locale: ID: ar_SY, Name: Arabic (Syria)
+display locale: ID: ar_SY, Name: Arabic (Syria)
+format locale: ID: ar_SY, Name: Arabic (Syria)
+default charset: ISO-8859-6
+
+OS Locale:  ar_SY.utf8
+default locale: ID: ar_SY, Name: Arabic (Syria)
+display locale: ID: ar_SY, Name: Arabic (Syria)
+format locale: ID: ar_SY, Name: Arabic (Syria)
+default charset: UTF-8
+
+OS Locale:  ar_TN
+default locale: ID: ar_TN, Name: Arabic (Tunisia)
+display locale: ID: ar_TN, Name: Arabic (Tunisia)
+format locale: ID: ar_TN, Name: Arabic (Tunisia)
+default charset: ISO-8859-6
+
+OS Locale:  ar_TN.iso88596
+default locale: ID: ar_TN, Name: Arabic (Tunisia)
+display locale: ID: ar_TN, Name: Arabic (Tunisia)
+format locale: ID: ar_TN, Name: Arabic (Tunisia)
+default charset: ISO-8859-6
+
+OS Locale:  ar_TN.utf8
+default locale: ID: ar_TN, Name: Arabic (Tunisia)
+display locale: ID: ar_TN, Name: Arabic (Tunisia)
+format locale: ID: ar_TN, Name: Arabic (Tunisia)
+default charset: UTF-8
+
+OS Locale:  ar_YE
+default locale: ID: ar_YE, Name: Arabic (Yemen)
+display locale: ID: ar_YE, Name: Arabic (Yemen)
+format locale: ID: ar_YE, Name: Arabic (Yemen)
+default charset: ISO-8859-6
+
+OS Locale:  ar_YE.iso88596
+default locale: ID: ar_YE, Name: Arabic (Yemen)
+display locale: ID: ar_YE, Name: Arabic (Yemen)
+format locale: ID: ar_YE, Name: Arabic (Yemen)
+default charset: ISO-8859-6
+
+OS Locale:  ar_YE.utf8
+default locale: ID: ar_YE, Name: Arabic (Yemen)
+display locale: ID: ar_YE, Name: Arabic (Yemen)
+format locale: ID: ar_YE, Name: Arabic (Yemen)
+default charset: UTF-8
+
+OS Locale:  as_IN.utf8
+default locale: ID: as_IN, Name: Assamese (India)
+display locale: ID: as_IN, Name: Assamese (India)
+format locale: ID: as_IN, Name: Assamese (India)
+default charset: UTF-8
+
+OS Locale:  az_AZ.utf8
+default locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+display locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: UTF-8
+
+OS Locale:  be_BY
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: windows-1251
+
+OS Locale:  be_BY.cp1251
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: windows-1251
+
+OS Locale:  be_BY.utf8
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: UTF-8
+
+OS Locale:  be_BY.utf8@latin
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: UTF-8
+
+OS Locale:  be_BY@latin
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: be_BY, Name: Belarusian (Belarus)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: UTF-8
+
+OS Locale:  bg_BG
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: windows-1251
+
+OS Locale:  bg_BG.cp1251
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: windows-1251
+
+OS Locale:  bg_BG.utf8
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: UTF-8
+
+OS Locale:  bn_BD
+default locale: ID: bn_BD, Name: Bengali (Bangladesh)
+display locale: ID: bn_BD, Name: Bengali (Bangladesh)
+format locale: ID: bn_BD, Name: Bengali (Bangladesh)
+default charset: UTF-8
+
+OS Locale:  bn_BD.utf8
+default locale: ID: bn_BD, Name: Bengali (Bangladesh)
+display locale: ID: bn_BD, Name: Bengali (Bangladesh)
+format locale: ID: bn_BD, Name: Bengali (Bangladesh)
+default charset: UTF-8
+
+OS Locale:  bn_IN
+default locale: ID: bn_IN, Name: Bengali (India)
+display locale: ID: bn_IN, Name: Bengali (India)
+format locale: ID: bn_IN, Name: Bengali (India)
+default charset: UTF-8
+
+OS Locale:  bn_IN.utf8
+default locale: ID: bn_IN, Name: Bengali (India)
+display locale: ID: bn_IN, Name: Bengali (India)
+format locale: ID: bn_IN, Name: Bengali (India)
+default charset: UTF-8
+
+OS Locale:  bokmål
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  bokmal
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  br_FR
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: ISO-8859-1
+
+OS Locale:  br_FR.iso88591
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: ISO-8859-1
+
+OS Locale:  br_FR.iso885915@euro
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: ISO-8859-15
+
+OS Locale:  br_FR.utf8
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: UTF-8
+
+OS Locale:  br_FR@euro
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: br_FR, Name: Breton (France)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: ISO-8859-15
+
+OS Locale:  bs_BA
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: ISO-8859-2
+
+OS Locale:  bs_BA.iso88592
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: ISO-8859-2
+
+OS Locale:  bs_BA.utf8
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: UTF-8
+
+OS Locale:  byn_ER
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  byn_ER.utf8
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  ca_AD
+default locale: ID: ca_AD, Name: Catalan (Andorra)
+display locale: ID: ca_AD, Name: Catalan (Andorra)
+format locale: ID: ca_AD, Name: Catalan (Andorra)
+default charset: ISO-8859-15
+
+OS Locale:  ca_AD.iso885915
+default locale: ID: ca_AD, Name: Catalan (Andorra)
+display locale: ID: ca_AD, Name: Catalan (Andorra)
+format locale: ID: ca_AD, Name: Catalan (Andorra)
+default charset: ISO-8859-15
+
+OS Locale:  ca_AD.utf8
+default locale: ID: ca_AD, Name: Catalan (Andorra)
+display locale: ID: ca_AD, Name: Catalan (Andorra)
+format locale: ID: ca_AD, Name: Catalan (Andorra)
+default charset: UTF-8
+
+OS Locale:  ca_ES
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  ca_ES.iso88591
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  ca_ES.iso885915@euro
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  ca_ES.utf8
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: UTF-8
+
+OS Locale:  ca_ES@euro
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  ca_FR
+default locale: ID: ca_FR, Name: Catalan (France)
+display locale: ID: ca_FR, Name: Catalan (France)
+format locale: ID: ca_FR, Name: Catalan (France)
+default charset: ISO-8859-15
+
+OS Locale:  ca_FR.iso885915
+default locale: ID: ca_FR, Name: Catalan (France)
+display locale: ID: ca_FR, Name: Catalan (France)
+format locale: ID: ca_FR, Name: Catalan (France)
+default charset: ISO-8859-15
+
+OS Locale:  ca_FR.utf8
+default locale: ID: ca_FR, Name: Catalan (France)
+display locale: ID: ca_FR, Name: Catalan (France)
+format locale: ID: ca_FR, Name: Catalan (France)
+default charset: UTF-8
+
+OS Locale:  ca_IT
+default locale: ID: ca_IT, Name: Catalan (Italy)
+display locale: ID: ca_IT, Name: Catalan (Italy)
+format locale: ID: ca_IT, Name: Catalan (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  ca_IT.iso885915
+default locale: ID: ca_IT, Name: Catalan (Italy)
+display locale: ID: ca_IT, Name: Catalan (Italy)
+format locale: ID: ca_IT, Name: Catalan (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  ca_IT.utf8
+default locale: ID: ca_IT, Name: Catalan (Italy)
+display locale: ID: ca_IT, Name: Catalan (Italy)
+format locale: ID: ca_IT, Name: Catalan (Italy)
+default charset: UTF-8
+
+OS Locale:  catalan
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  croatian
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  cs_CZ
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  cs_CZ.iso88592
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  cs_CZ.utf8
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: UTF-8
+
+OS Locale:  csb_PL
+default locale: ID: en_PL, Name: English (Poland)
+display locale: ID: en_PL, Name: English (Poland)
+format locale: ID: en_PL, Name: English (Poland)
+default charset: UTF-8
+
+OS Locale:  csb_PL.utf8
+default locale: ID: en_PL, Name: English (Poland)
+display locale: ID: en_PL, Name: English (Poland)
+format locale: ID: en_PL, Name: English (Poland)
+default charset: UTF-8
+
+OS Locale:  cy_GB
+default locale: ID: cy_GB, Name: Welsh (United Kingdom)
+display locale: ID: cy_GB, Name: Welsh (United Kingdom)
+format locale: ID: cy_GB, Name: Welsh (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  cy_GB.iso885914
+default locale: ID: cy_GB, Name: Welsh (United Kingdom)
+display locale: ID: cy_GB, Name: Welsh (United Kingdom)
+format locale: ID: cy_GB, Name: Welsh (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  cy_GB.utf8
+default locale: ID: cy_GB, Name: Welsh (United Kingdom)
+display locale: ID: cy_GB, Name: Welsh (United Kingdom)
+format locale: ID: cy_GB, Name: Welsh (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  czech
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  da_DK
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  da_DK.iso88591
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  da_DK.iso885915
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-15
+
+OS Locale:  da_DK.utf8
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: UTF-8
+
+OS Locale:  danish
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  dansk
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  de_AT
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-1
+
+OS Locale:  de_AT.iso88591
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-1
+
+OS Locale:  de_AT.iso885915@euro
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-15
+
+OS Locale:  de_AT.utf8
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: UTF-8
+
+OS Locale:  de_AT@euro
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-15
+
+OS Locale:  de_BE
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  de_BE.iso88591
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  de_BE.iso885915@euro
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  de_BE.utf8
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: UTF-8
+
+OS Locale:  de_BE@euro
+default locale: ID: de_BE, Name: German (Belgium)
+display locale: ID: de_BE, Name: German (Belgium)
+format locale: ID: de_BE, Name: German (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  de_CH
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  de_CH.iso88591
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  de_CH.utf8
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: UTF-8
+
+OS Locale:  de_DE
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  de_DE.iso88591
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  de_DE.iso885915@euro
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
+
+OS Locale:  de_DE.utf8
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: UTF-8
+
+OS Locale:  de_DE@euro
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
+
+OS Locale:  de_LU
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: ISO-8859-1
+
+OS Locale:  de_LU.iso88591
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: ISO-8859-1
+
+OS Locale:  de_LU.iso885915@euro
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: ISO-8859-15
+
+OS Locale:  de_LU.utf8
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: UTF-8
+
+OS Locale:  de_LU@euro
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: de_LU, Name: German (Luxembourg)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: ISO-8859-15
+
+OS Locale:  deutsch
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  dutch
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  dz_BT
+default locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+display locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+format locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+default charset: UTF-8
+
+OS Locale:  dz_BT.utf8
+default locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+display locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+format locale: ID: dz_BT, Name: Dzongkha (Bhutan)
+default charset: UTF-8
+
+OS Locale:  eesti
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  el_CY
+default locale: ID: el_CY, Name: Greek (Cyprus)
+display locale: ID: el_CY, Name: Greek (Cyprus)
+format locale: ID: el_CY, Name: Greek (Cyprus)
+default charset: ISO-8859-7
+
+OS Locale:  el_CY.iso88597
+default locale: ID: el_CY, Name: Greek (Cyprus)
+display locale: ID: el_CY, Name: Greek (Cyprus)
+format locale: ID: el_CY, Name: Greek (Cyprus)
+default charset: ISO-8859-7
+
+OS Locale:  el_CY.utf8
+default locale: ID: el_CY, Name: Greek (Cyprus)
+display locale: ID: el_CY, Name: Greek (Cyprus)
+format locale: ID: el_CY, Name: Greek (Cyprus)
+default charset: UTF-8
+
+OS Locale:  el_GR
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  el_GR.iso88597
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  el_GR.utf8
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: UTF-8
+
+OS Locale:  en_AU
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: ISO-8859-1
+
+OS Locale:  en_AU.iso88591
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: ISO-8859-1
+
+OS Locale:  en_AU.utf8
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: UTF-8
+
+OS Locale:  en_BW
+default locale: ID: en_BW, Name: English (Botswana)
+display locale: ID: en_BW, Name: English (Botswana)
+format locale: ID: en_BW, Name: English (Botswana)
+default charset: ISO-8859-1
+
+OS Locale:  en_BW.iso88591
+default locale: ID: en_BW, Name: English (Botswana)
+display locale: ID: en_BW, Name: English (Botswana)
+format locale: ID: en_BW, Name: English (Botswana)
+default charset: ISO-8859-1
+
+OS Locale:  en_BW.utf8
+default locale: ID: en_BW, Name: English (Botswana)
+display locale: ID: en_BW, Name: English (Botswana)
+format locale: ID: en_BW, Name: English (Botswana)
+default charset: UTF-8
+
+OS Locale:  en_CA
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  en_CA.iso88591
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  en_CA.utf8
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: UTF-8
+
+OS Locale:  en_DK
+default locale: ID: en_DK, Name: English (Denmark)
+display locale: ID: en_DK, Name: English (Denmark)
+format locale: ID: en_DK, Name: English (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  en_DK.iso88591
+default locale: ID: en_DK, Name: English (Denmark)
+display locale: ID: en_DK, Name: English (Denmark)
+format locale: ID: en_DK, Name: English (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  en_DK.utf8
+default locale: ID: en_DK, Name: English (Denmark)
+display locale: ID: en_DK, Name: English (Denmark)
+format locale: ID: en_DK, Name: English (Denmark)
+default charset: UTF-8
+
+OS Locale:  en_GB
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  en_GB.iso88591
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  en_GB.iso885915
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-15
+
+OS Locale:  en_GB.utf8
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  en_HK
+default locale: ID: en_HK, Name: English (Hong Kong)
+display locale: ID: en_HK, Name: English (Hong Kong)
+format locale: ID: en_HK, Name: English (Hong Kong)
+default charset: ISO-8859-1
+
+OS Locale:  en_HK.iso88591
+default locale: ID: en_HK, Name: English (Hong Kong)
+display locale: ID: en_HK, Name: English (Hong Kong)
+format locale: ID: en_HK, Name: English (Hong Kong)
+default charset: ISO-8859-1
+
+OS Locale:  en_HK.utf8
+default locale: ID: en_HK, Name: English (Hong Kong)
+display locale: ID: en_HK, Name: English (Hong Kong)
+format locale: ID: en_HK, Name: English (Hong Kong)
+default charset: UTF-8
+
+OS Locale:  en_IE
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  en_IE.iso88591
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  en_IE.iso885915@euro
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  en_IE.utf8
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: UTF-8
+
+OS Locale:  en_IE@euro
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  en_IN
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: UTF-8
+
+OS Locale:  en_IN.utf8
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: UTF-8
+
+OS Locale:  en_NZ
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: ISO-8859-1
+
+OS Locale:  en_NZ.iso88591
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: ISO-8859-1
+
+OS Locale:  en_NZ.utf8
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: UTF-8
+
+OS Locale:  en_PH
+default locale: ID: en_PH, Name: English (Philippines)
+display locale: ID: en_PH, Name: English (Philippines)
+format locale: ID: en_PH, Name: English (Philippines)
+default charset: ISO-8859-1
+
+OS Locale:  en_PH.iso88591
+default locale: ID: en_PH, Name: English (Philippines)
+display locale: ID: en_PH, Name: English (Philippines)
+format locale: ID: en_PH, Name: English (Philippines)
+default charset: ISO-8859-1
+
+OS Locale:  en_PH.utf8
+default locale: ID: en_PH, Name: English (Philippines)
+display locale: ID: en_PH, Name: English (Philippines)
+format locale: ID: en_PH, Name: English (Philippines)
+default charset: UTF-8
+
+OS Locale:  en_SG
+default locale: ID: en_SG, Name: English (Singapore)
+display locale: ID: en_SG, Name: English (Singapore)
+format locale: ID: en_SG, Name: English (Singapore)
+default charset: ISO-8859-1
+
+OS Locale:  en_SG.iso88591
+default locale: ID: en_SG, Name: English (Singapore)
+display locale: ID: en_SG, Name: English (Singapore)
+format locale: ID: en_SG, Name: English (Singapore)
+default charset: ISO-8859-1
+
+OS Locale:  en_SG.utf8
+default locale: ID: en_SG, Name: English (Singapore)
+display locale: ID: en_SG, Name: English (Singapore)
+format locale: ID: en_SG, Name: English (Singapore)
+default charset: UTF-8
+
+OS Locale:  en_US
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-1
+
+OS Locale:  en_US.iso88591
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-1
+
+OS Locale:  en_US.iso885915
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-15
+
+OS Locale:  en_US.utf8
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: UTF-8
+
+OS Locale:  en_ZA
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  en_ZA.iso88591
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  en_ZA.utf8
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: UTF-8
+
+OS Locale:  en_ZW
+default locale: ID: en_ZW, Name: English (Zimbabwe)
+display locale: ID: en_ZW, Name: English (Zimbabwe)
+format locale: ID: en_ZW, Name: English (Zimbabwe)
+default charset: ISO-8859-1
+
+OS Locale:  en_ZW.iso88591
+default locale: ID: en_ZW, Name: English (Zimbabwe)
+display locale: ID: en_ZW, Name: English (Zimbabwe)
+format locale: ID: en_ZW, Name: English (Zimbabwe)
+default charset: ISO-8859-1
+
+OS Locale:  en_ZW.utf8
+default locale: ID: en_ZW, Name: English (Zimbabwe)
+display locale: ID: en_ZW, Name: English (Zimbabwe)
+format locale: ID: en_ZW, Name: English (Zimbabwe)
+default charset: UTF-8
+
+OS Locale:  es_AR
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: ISO-8859-1
+
+OS Locale:  es_AR.iso88591
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: ISO-8859-1
+
+OS Locale:  es_AR.utf8
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: UTF-8
+
+OS Locale:  es_BO
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: ISO-8859-1
+
+OS Locale:  es_BO.iso88591
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: ISO-8859-1
+
+OS Locale:  es_BO.utf8
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: UTF-8
+
+OS Locale:  es_CL
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: ISO-8859-1
+
+OS Locale:  es_CL.iso88591
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: ISO-8859-1
+
+OS Locale:  es_CL.utf8
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: UTF-8
+
+OS Locale:  es_CO
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: ISO-8859-1
+
+OS Locale:  es_CO.iso88591
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: ISO-8859-1
+
+OS Locale:  es_CO.utf8
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: UTF-8
+
+OS Locale:  es_CR
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: ISO-8859-1
+
+OS Locale:  es_CR.iso88591
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: ISO-8859-1
+
+OS Locale:  es_CR.utf8
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: UTF-8
+
+OS Locale:  es_DO
+default locale: ID: es_DO, Name: Spanish (Dominican Republic)
+display locale: ID: es_DO, Name: Spanish (Dominican Republic)
+format locale: ID: es_DO, Name: Spanish (Dominican Republic)
+default charset: ISO-8859-1
+
+OS Locale:  es_DO.iso88591
+default locale: ID: es_DO, Name: Spanish (Dominican Republic)
+display locale: ID: es_DO, Name: Spanish (Dominican Republic)
+format locale: ID: es_DO, Name: Spanish (Dominican Republic)
+default charset: ISO-8859-1
+
+OS Locale:  es_DO.utf8
+default locale: ID: es_DO, Name: Spanish (Dominican Republic)
+display locale: ID: es_DO, Name: Spanish (Dominican Republic)
+format locale: ID: es_DO, Name: Spanish (Dominican Republic)
+default charset: UTF-8
+
+OS Locale:  es_EC
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: ISO-8859-1
+
+OS Locale:  es_EC.iso88591
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: ISO-8859-1
+
+OS Locale:  es_EC.utf8
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: UTF-8
+
+OS Locale:  es_ES
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  es_ES.iso88591
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  es_ES.iso885915@euro
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  es_ES.utf8
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: UTF-8
+
+OS Locale:  es_ES@euro
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  es_GT
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: ISO-8859-1
+
+OS Locale:  es_GT.iso88591
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: ISO-8859-1
+
+OS Locale:  es_GT.utf8
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: UTF-8
+
+OS Locale:  es_HN
+default locale: ID: es_HN, Name: Spanish (Honduras)
+display locale: ID: es_HN, Name: Spanish (Honduras)
+format locale: ID: es_HN, Name: Spanish (Honduras)
+default charset: ISO-8859-1
+
+OS Locale:  es_HN.iso88591
+default locale: ID: es_HN, Name: Spanish (Honduras)
+display locale: ID: es_HN, Name: Spanish (Honduras)
+format locale: ID: es_HN, Name: Spanish (Honduras)
+default charset: ISO-8859-1
+
+OS Locale:  es_HN.utf8
+default locale: ID: es_HN, Name: Spanish (Honduras)
+display locale: ID: es_HN, Name: Spanish (Honduras)
+format locale: ID: es_HN, Name: Spanish (Honduras)
+default charset: UTF-8
+
+OS Locale:  es_MX
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: ISO-8859-1
+
+OS Locale:  es_MX.iso88591
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: ISO-8859-1
+
+OS Locale:  es_MX.utf8
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: UTF-8
+
+OS Locale:  es_NI
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: ISO-8859-1
+
+OS Locale:  es_NI.iso88591
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: ISO-8859-1
+
+OS Locale:  es_NI.utf8
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: UTF-8
+
+OS Locale:  es_PA
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: ISO-8859-1
+
+OS Locale:  es_PA.iso88591
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: ISO-8859-1
+
+OS Locale:  es_PA.utf8
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: UTF-8
+
+OS Locale:  es_PE
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: ISO-8859-1
+
+OS Locale:  es_PE.iso88591
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: ISO-8859-1
+
+OS Locale:  es_PE.utf8
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: UTF-8
+
+OS Locale:  es_PR
+default locale: ID: es_PR, Name: Spanish (Puerto Rico)
+display locale: ID: es_PR, Name: Spanish (Puerto Rico)
+format locale: ID: es_PR, Name: Spanish (Puerto Rico)
+default charset: ISO-8859-1
+
+OS Locale:  es_PR.iso88591
+default locale: ID: es_PR, Name: Spanish (Puerto Rico)
+display locale: ID: es_PR, Name: Spanish (Puerto Rico)
+format locale: ID: es_PR, Name: Spanish (Puerto Rico)
+default charset: ISO-8859-1
+
+OS Locale:  es_PR.utf8
+default locale: ID: es_PR, Name: Spanish (Puerto Rico)
+display locale: ID: es_PR, Name: Spanish (Puerto Rico)
+format locale: ID: es_PR, Name: Spanish (Puerto Rico)
+default charset: UTF-8
+
+OS Locale:  es_PY
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_PY.iso88591
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_PY.utf8
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: UTF-8
+
+OS Locale:  es_SV
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: ISO-8859-1
+
+OS Locale:  es_SV.iso88591
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: ISO-8859-1
+
+OS Locale:  es_SV.utf8
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: UTF-8
+
+OS Locale:  es_US
+default locale: ID: es_US, Name: Spanish (United States)
+display locale: ID: es_US, Name: Spanish (United States)
+format locale: ID: es_US, Name: Spanish (United States)
+default charset: ISO-8859-1
+
+OS Locale:  es_US.iso88591
+default locale: ID: es_US, Name: Spanish (United States)
+display locale: ID: es_US, Name: Spanish (United States)
+format locale: ID: es_US, Name: Spanish (United States)
+default charset: ISO-8859-1
+
+OS Locale:  es_US.utf8
+default locale: ID: es_US, Name: Spanish (United States)
+display locale: ID: es_US, Name: Spanish (United States)
+format locale: ID: es_US, Name: Spanish (United States)
+default charset: UTF-8
+
+OS Locale:  es_UY
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_UY.iso88591
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_UY.utf8
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: UTF-8
+
+OS Locale:  es_VE
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: ISO-8859-1
+
+OS Locale:  es_VE.iso88591
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: ISO-8859-1
+
+OS Locale:  es_VE.utf8
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: UTF-8
+
+OS Locale:  estonian
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  et_EE
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-1
+
+OS Locale:  et_EE.iso88591
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-1
+
+OS Locale:  et_EE.iso885915
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-15
+
+OS Locale:  et_EE.utf8
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: UTF-8
+
+OS Locale:  eu_ES
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  eu_ES.iso88591
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  eu_ES.iso885915@euro
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  eu_ES.utf8
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: UTF-8
+
+OS Locale:  eu_ES@euro
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: eu_ES, Name: Basque (Spain)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  fa_IR
+default locale: ID: fa_IR, Name: Persian (Iran)
+display locale: ID: fa_IR, Name: Persian (Iran)
+format locale: ID: fa_IR, Name: Persian (Iran)
+default charset: UTF-8
+
+OS Locale:  fa_IR.utf8
+default locale: ID: fa_IR, Name: Persian (Iran)
+display locale: ID: fa_IR, Name: Persian (Iran)
+format locale: ID: fa_IR, Name: Persian (Iran)
+default charset: UTF-8
+
+OS Locale:  fi_FI
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fi_FI.iso88591
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fi_FI.iso885915@euro
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  fi_FI.utf8
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: UTF-8
+
+OS Locale:  fi_FI@euro
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  finnish
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fo_FO
+default locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+display locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+format locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+default charset: ISO-8859-1
+
+OS Locale:  fo_FO.iso88591
+default locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+display locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+format locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+default charset: ISO-8859-1
+
+OS Locale:  fo_FO.utf8
+default locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+display locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+format locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+default charset: UTF-8
+
+OS Locale:  fr_BE
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  fr_BE.iso88591
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  fr_BE.iso885915@euro
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  fr_BE.utf8
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: UTF-8
+
+OS Locale:  fr_BE@euro
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  fr_CA
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CA.iso88591
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CA.utf8
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: UTF-8
+
+OS Locale:  fr_CH
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CH.iso88591
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CH.utf8
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: UTF-8
+
+OS Locale:  fr_FR
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fr_FR.iso88591
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fr_FR.iso885915@euro
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
+
+OS Locale:  fr_FR.utf8
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: UTF-8
+
+OS Locale:  fr_FR@euro
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
+
+OS Locale:  fr_LU
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: ISO-8859-1
+
+OS Locale:  fr_LU.iso88591
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: ISO-8859-1
+
+OS Locale:  fr_LU.iso885915@euro
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: ISO-8859-15
+
+OS Locale:  fr_LU.utf8
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: UTF-8
+
+OS Locale:  fr_LU@euro
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: fr_LU, Name: French (Luxembourg)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: ISO-8859-15
+
+OS Locale:  français
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  french
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fy_NL
+default locale: ID: fy_NL, Name: Frisian (Netherlands)
+display locale: ID: fy_NL, Name: Frisian (Netherlands)
+format locale: ID: fy_NL, Name: Frisian (Netherlands)
+default charset: UTF-8
+
+OS Locale:  fy_NL.utf8
+default locale: ID: fy_NL, Name: Frisian (Netherlands)
+display locale: ID: fy_NL, Name: Frisian (Netherlands)
+format locale: ID: fy_NL, Name: Frisian (Netherlands)
+default charset: UTF-8
+
+OS Locale:  ga_IE
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  ga_IE.iso88591
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  ga_IE.iso885915@euro
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  ga_IE.utf8
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: UTF-8
+
+OS Locale:  ga_IE@euro
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: ga_IE, Name: Irish (Ireland)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  galego
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  galician
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  gd_GB
+default locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+display locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+format locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+default charset: ISO-8859-15
+
+OS Locale:  gd_GB.iso885915
+default locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+display locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+format locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+default charset: ISO-8859-15
+
+OS Locale:  gd_GB.utf8
+default locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+display locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+format locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  german
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  gez_ER
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  gez_ER.utf8
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  gez_ER.utf8@abegede
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  gez_ER@abegede
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  gez_ET
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  gez_ET.utf8
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  gez_ET.utf8@abegede
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  gez_ET@abegede
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  gl_ES
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  gl_ES.iso88591
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  gl_ES.iso885915@euro
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  gl_ES.utf8
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: UTF-8
+
+OS Locale:  gl_ES@euro
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: gl_ES, Name: Gallegan (Spain)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  greek
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  gu_IN
+default locale: ID: gu_IN, Name: Gujarati (India)
+display locale: ID: gu_IN, Name: Gujarati (India)
+format locale: ID: gu_IN, Name: Gujarati (India)
+default charset: UTF-8
+
+OS Locale:  gu_IN.utf8
+default locale: ID: gu_IN, Name: Gujarati (India)
+display locale: ID: gu_IN, Name: Gujarati (India)
+format locale: ID: gu_IN, Name: Gujarati (India)
+default charset: UTF-8
+
+OS Locale:  gv_GB
+default locale: ID: gv_GB, Name: Manx (United Kingdom)
+display locale: ID: gv_GB, Name: Manx (United Kingdom)
+format locale: ID: gv_GB, Name: Manx (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  gv_GB.iso88591
+default locale: ID: gv_GB, Name: Manx (United Kingdom)
+display locale: ID: gv_GB, Name: Manx (United Kingdom)
+format locale: ID: gv_GB, Name: Manx (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  gv_GB.utf8
+default locale: ID: gv_GB, Name: Manx (United Kingdom)
+display locale: ID: gv_GB, Name: Manx (United Kingdom)
+format locale: ID: gv_GB, Name: Manx (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  he_IL
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  he_IL.iso88598
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  he_IL.utf8
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: UTF-8
+
+OS Locale:  hebrew
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  hi_IN
+default locale: ID: hi_IN, Name: Hindi (India)
+display locale: ID: hi_IN, Name: Hindi (India)
+format locale: ID: hi_IN, Name: Hindi (India)
+default charset: UTF-8
+
+OS Locale:  hi_IN.utf8
+default locale: ID: hi_IN, Name: Hindi (India)
+display locale: ID: hi_IN, Name: Hindi (India)
+format locale: ID: hi_IN, Name: Hindi (India)
+default charset: UTF-8
+
+OS Locale:  hr_HR
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  hr_HR.iso88592
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  hr_HR.utf8
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: UTF-8
+
+OS Locale:  hrvatski
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  hsb_DE
+default locale: ID: en_DE, Name: English (Germany)
+display locale: ID: en_DE, Name: English (Germany)
+format locale: ID: en_DE, Name: English (Germany)
+default charset: ISO-8859-2
+
+OS Locale:  hsb_DE.iso88592
+default locale: ID: en_DE, Name: English (Germany)
+display locale: ID: en_DE, Name: English (Germany)
+format locale: ID: en_DE, Name: English (Germany)
+default charset: ISO-8859-2
+
+OS Locale:  hsb_DE.utf8
+default locale: ID: en_DE, Name: English (Germany)
+display locale: ID: en_DE, Name: English (Germany)
+format locale: ID: en_DE, Name: English (Germany)
+default charset: UTF-8
+
+OS Locale:  hu_HU
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hu_HU.iso88592
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hu_HU.utf8
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: UTF-8
+
+OS Locale:  hungarian
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hy_AM
+default locale: ID: hy_AM, Name: Armenian (Armenia)
+display locale: ID: hy_AM, Name: Armenian (Armenia)
+format locale: ID: hy_AM, Name: Armenian (Armenia)
+default charset: UTF-8
+
+OS Locale:  hy_AM.armscii8
+default locale: ID: hy_AM, Name: Armenian (Armenia)
+display locale: ID: hy_AM, Name: Armenian (Armenia)
+format locale: ID: hy_AM, Name: Armenian (Armenia)
+default charset: UTF-8
+
+OS Locale:  hy_AM.utf8
+default locale: ID: hy_AM, Name: Armenian (Armenia)
+display locale: ID: hy_AM, Name: Armenian (Armenia)
+format locale: ID: hy_AM, Name: Armenian (Armenia)
+default charset: UTF-8
+
+OS Locale:  icelandic
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
+
+OS Locale:  id_ID
+default locale: ID: in_ID, Name: Indonesian (Indonesia)
+display locale: ID: in_ID, Name: Indonesian (Indonesia)
+format locale: ID: in_ID, Name: Indonesian (Indonesia)
+default charset: ISO-8859-1
+
+OS Locale:  id_ID.iso88591
+default locale: ID: in_ID, Name: Indonesian (Indonesia)
+display locale: ID: in_ID, Name: Indonesian (Indonesia)
+format locale: ID: in_ID, Name: Indonesian (Indonesia)
+default charset: ISO-8859-1
+
+OS Locale:  id_ID.utf8
+default locale: ID: in_ID, Name: Indonesian (Indonesia)
+display locale: ID: in_ID, Name: Indonesian (Indonesia)
+format locale: ID: in_ID, Name: Indonesian (Indonesia)
+default charset: UTF-8
+
+OS Locale:  is_IS
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
+
+OS Locale:  is_IS.iso88591
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
+
+OS Locale:  is_IS.utf8
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: UTF-8
+
+OS Locale:  it_CH
+default locale: ID: it_CH, Name: Italian (Switzerland)
+display locale: ID: it_CH, Name: Italian (Switzerland)
+format locale: ID: it_CH, Name: Italian (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  it_CH.iso88591
+default locale: ID: it_CH, Name: Italian (Switzerland)
+display locale: ID: it_CH, Name: Italian (Switzerland)
+format locale: ID: it_CH, Name: Italian (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  it_CH.utf8
+default locale: ID: it_CH, Name: Italian (Switzerland)
+display locale: ID: it_CH, Name: Italian (Switzerland)
+format locale: ID: it_CH, Name: Italian (Switzerland)
+default charset: UTF-8
+
+OS Locale:  it_IT
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  it_IT.iso88591
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  it_IT.iso885915@euro
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  it_IT.utf8
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: UTF-8
+
+OS Locale:  it_IT@euro
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  italian
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  iw_IL
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  iw_IL.iso88598
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  iw_IL.utf8
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: UTF-8
+
+OS Locale:  ja_JP
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  ja_JP.eucjp
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  ja_JP.ujis
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  ja_JP.utf8
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: UTF-8
+
+OS Locale:  japanese
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  japanese.euc
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-euc-jp-linux
+
+OS Locale:  ka_GE
+default locale: ID: ka_GE, Name: Georgian (Georgia)
+display locale: ID: ka_GE, Name: Georgian (Georgia)
+format locale: ID: ka_GE, Name: Georgian (Georgia)
+default charset: UTF-8
+
+OS Locale:  ka_GE.georgianps
+default locale: ID: ka_GE, Name: Georgian (Georgia)
+display locale: ID: ka_GE, Name: Georgian (Georgia)
+format locale: ID: ka_GE, Name: Georgian (Georgia)
+default charset: UTF-8
+
+OS Locale:  ka_GE.utf8
+default locale: ID: ka_GE, Name: Georgian (Georgia)
+display locale: ID: ka_GE, Name: Georgian (Georgia)
+format locale: ID: ka_GE, Name: Georgian (Georgia)
+default charset: UTF-8
+
+OS Locale:  kk_KZ
+default locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+display locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+format locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+default charset: UTF-8
+
+OS Locale:  kk_KZ.pt154
+default locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+display locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+format locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+default charset: UTF-8
+
+OS Locale:  kk_KZ.utf8
+default locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+display locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+format locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+default charset: UTF-8
+
+OS Locale:  kl_GL
+default locale: ID: kl_GL, Name: Greenlandic (Greenland)
+display locale: ID: kl_GL, Name: Greenlandic (Greenland)
+format locale: ID: kl_GL, Name: Greenlandic (Greenland)
+default charset: ISO-8859-1
+
+OS Locale:  kl_GL.iso88591
+default locale: ID: kl_GL, Name: Greenlandic (Greenland)
+display locale: ID: kl_GL, Name: Greenlandic (Greenland)
+format locale: ID: kl_GL, Name: Greenlandic (Greenland)
+default charset: ISO-8859-1
+
+OS Locale:  kl_GL.utf8
+default locale: ID: kl_GL, Name: Greenlandic (Greenland)
+display locale: ID: kl_GL, Name: Greenlandic (Greenland)
+format locale: ID: kl_GL, Name: Greenlandic (Greenland)
+default charset: UTF-8
+
+OS Locale:  km_KH
+default locale: ID: km_KH, Name: Khmer (Cambodia)
+display locale: ID: km_KH, Name: Khmer (Cambodia)
+format locale: ID: km_KH, Name: Khmer (Cambodia)
+default charset: UTF-8
+
+OS Locale:  km_KH.utf8
+default locale: ID: km_KH, Name: Khmer (Cambodia)
+display locale: ID: km_KH, Name: Khmer (Cambodia)
+format locale: ID: km_KH, Name: Khmer (Cambodia)
+default charset: UTF-8
+
+OS Locale:  kn_IN
+default locale: ID: kn_IN, Name: Kannada (India)
+display locale: ID: kn_IN, Name: Kannada (India)
+format locale: ID: kn_IN, Name: Kannada (India)
+default charset: UTF-8
+
+OS Locale:  kn_IN.utf8
+default locale: ID: kn_IN, Name: Kannada (India)
+display locale: ID: kn_IN, Name: Kannada (India)
+format locale: ID: kn_IN, Name: Kannada (India)
+default charset: UTF-8
+
+OS Locale:  ko_KR
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
+
+OS Locale:  ko_KR.euckr
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
+
+OS Locale:  ko_KR.utf8
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: UTF-8
+
+OS Locale:  korean
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: EUC-KR
+
+OS Locale:  korean.euc
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: EUC-KR
+
+OS Locale:  ku_TR
+default locale: ID: ku_TR, Name: Kurdish (Turkey)
+display locale: ID: ku_TR, Name: Kurdish (Turkey)
+format locale: ID: ku_TR, Name: Kurdish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  ku_TR.iso88599
+default locale: ID: ku_TR, Name: Kurdish (Turkey)
+display locale: ID: ku_TR, Name: Kurdish (Turkey)
+format locale: ID: ku_TR, Name: Kurdish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  ku_TR.utf8
+default locale: ID: ku_TR, Name: Kurdish (Turkey)
+display locale: ID: ku_TR, Name: Kurdish (Turkey)
+format locale: ID: ku_TR, Name: Kurdish (Turkey)
+default charset: UTF-8
+
+OS Locale:  kw_GB
+default locale: ID: kw_GB, Name: Cornish (United Kingdom)
+display locale: ID: kw_GB, Name: Cornish (United Kingdom)
+format locale: ID: kw_GB, Name: Cornish (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  kw_GB.iso88591
+default locale: ID: kw_GB, Name: Cornish (United Kingdom)
+display locale: ID: kw_GB, Name: Cornish (United Kingdom)
+format locale: ID: kw_GB, Name: Cornish (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  kw_GB.utf8
+default locale: ID: kw_GB, Name: Cornish (United Kingdom)
+display locale: ID: kw_GB, Name: Cornish (United Kingdom)
+format locale: ID: kw_GB, Name: Cornish (United Kingdom)
+default charset: UTF-8
+
+OS Locale:  ky_KG
+default locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+display locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+format locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+default charset: UTF-8
+
+OS Locale:  ky_KG.utf8
+default locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+display locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+format locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+default charset: UTF-8
+
+OS Locale:  lg_UG
+default locale: ID: lg_UG, Name: Ganda (Uganda)
+display locale: ID: lg_UG, Name: Ganda (Uganda)
+format locale: ID: lg_UG, Name: Ganda (Uganda)
+default charset: UTF-8
+
+OS Locale:  lg_UG.iso885910
+default locale: ID: lg_UG, Name: Ganda (Uganda)
+display locale: ID: lg_UG, Name: Ganda (Uganda)
+format locale: ID: lg_UG, Name: Ganda (Uganda)
+default charset: UTF-8
+
+OS Locale:  lg_UG.utf8
+default locale: ID: lg_UG, Name: Ganda (Uganda)
+display locale: ID: lg_UG, Name: Ganda (Uganda)
+format locale: ID: lg_UG, Name: Ganda (Uganda)
+default charset: UTF-8
+
+OS Locale:  lithuanian
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-13
+
+OS Locale:  lo_LA
+default locale: ID: lo_LA, Name: Lao (Laos)
+display locale: ID: lo_LA, Name: Lao (Laos)
+format locale: ID: lo_LA, Name: Lao (Laos)
+default charset: UTF-8
+
+OS Locale:  lo_LA.utf8
+default locale: ID: lo_LA, Name: Lao (Laos)
+display locale: ID: lo_LA, Name: Lao (Laos)
+format locale: ID: lo_LA, Name: Lao (Laos)
+default charset: UTF-8
+
+OS Locale:  lt_LT
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
+
+OS Locale:  lt_LT.iso885913
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
+
+OS Locale:  lt_LT.utf8
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: UTF-8
+
+OS Locale:  lv_LV
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
+
+OS Locale:  lv_LV.iso885913
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
+
+OS Locale:  lv_LV.utf8
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: UTF-8
+
+OS Locale:  mai_IN
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: UTF-8
+
+OS Locale:  mai_IN.utf8
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: UTF-8
+
+OS Locale:  mg_MG
+default locale: ID: mg_MG, Name: Malagasy (Madagascar)
+display locale: ID: mg_MG, Name: Malagasy (Madagascar)
+format locale: ID: mg_MG, Name: Malagasy (Madagascar)
+default charset: ISO-8859-15
+
+OS Locale:  mg_MG.iso885915
+default locale: ID: mg_MG, Name: Malagasy (Madagascar)
+display locale: ID: mg_MG, Name: Malagasy (Madagascar)
+format locale: ID: mg_MG, Name: Malagasy (Madagascar)
+default charset: ISO-8859-15
+
+OS Locale:  mg_MG.utf8
+default locale: ID: mg_MG, Name: Malagasy (Madagascar)
+display locale: ID: mg_MG, Name: Malagasy (Madagascar)
+format locale: ID: mg_MG, Name: Malagasy (Madagascar)
+default charset: UTF-8
+
+OS Locale:  mi_NZ
+default locale: ID: mi_NZ, Name: Maori (New Zealand)
+display locale: ID: mi_NZ, Name: Maori (New Zealand)
+format locale: ID: mi_NZ, Name: Maori (New Zealand)
+default charset: ISO-8859-13
+
+OS Locale:  mi_NZ.iso885913
+default locale: ID: mi_NZ, Name: Maori (New Zealand)
+display locale: ID: mi_NZ, Name: Maori (New Zealand)
+format locale: ID: mi_NZ, Name: Maori (New Zealand)
+default charset: ISO-8859-13
+
+OS Locale:  mi_NZ.utf8
+default locale: ID: mi_NZ, Name: Maori (New Zealand)
+display locale: ID: mi_NZ, Name: Maori (New Zealand)
+format locale: ID: mi_NZ, Name: Maori (New Zealand)
+default charset: UTF-8
+
+OS Locale:  mk_MK
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: ISO-8859-5
+
+OS Locale:  mk_MK.iso88595
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: ISO-8859-5
+
+OS Locale:  mk_MK.utf8
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: UTF-8
+
+OS Locale:  ml_IN
+default locale: ID: ml_IN, Name: Malayalam (India)
+display locale: ID: ml_IN, Name: Malayalam (India)
+format locale: ID: ml_IN, Name: Malayalam (India)
+default charset: UTF-8
+
+OS Locale:  ml_IN.utf8
+default locale: ID: ml_IN, Name: Malayalam (India)
+display locale: ID: ml_IN, Name: Malayalam (India)
+format locale: ID: ml_IN, Name: Malayalam (India)
+default charset: UTF-8
+
+OS Locale:  mn_MN
+default locale: ID: mn_MN, Name: Mongolian (Mongolia)
+display locale: ID: mn_MN, Name: Mongolian (Mongolia)
+format locale: ID: mn_MN, Name: Mongolian (Mongolia)
+default charset: UTF-8
+
+OS Locale:  mn_MN.utf8
+default locale: ID: mn_MN, Name: Mongolian (Mongolia)
+display locale: ID: mn_MN, Name: Mongolian (Mongolia)
+format locale: ID: mn_MN, Name: Mongolian (Mongolia)
+default charset: UTF-8
+
+OS Locale:  mr_IN
+default locale: ID: mr_IN, Name: Marathi (India)
+display locale: ID: mr_IN, Name: Marathi (India)
+format locale: ID: mr_IN, Name: Marathi (India)
+default charset: UTF-8
+
+OS Locale:  mr_IN.utf8
+default locale: ID: mr_IN, Name: Marathi (India)
+display locale: ID: mr_IN, Name: Marathi (India)
+format locale: ID: mr_IN, Name: Marathi (India)
+default charset: UTF-8
+
+OS Locale:  ms_MY
+default locale: ID: ms_MY, Name: Malay (Malaysia)
+display locale: ID: ms_MY, Name: Malay (Malaysia)
+format locale: ID: ms_MY, Name: Malay (Malaysia)
+default charset: ISO-8859-1
+
+OS Locale:  ms_MY.iso88591
+default locale: ID: ms_MY, Name: Malay (Malaysia)
+display locale: ID: ms_MY, Name: Malay (Malaysia)
+format locale: ID: ms_MY, Name: Malay (Malaysia)
+default charset: ISO-8859-1
+
+OS Locale:  ms_MY.utf8
+default locale: ID: ms_MY, Name: Malay (Malaysia)
+display locale: ID: ms_MY, Name: Malay (Malaysia)
+format locale: ID: ms_MY, Name: Malay (Malaysia)
+default charset: UTF-8
+
+OS Locale:  mt_MT
+default locale: ID: mt_MT, Name: Maltese (Malta)
+display locale: ID: mt_MT, Name: Maltese (Malta)
+format locale: ID: mt_MT, Name: Maltese (Malta)
+default charset: ISO-8859-3
+
+OS Locale:  mt_MT.iso88593
+default locale: ID: mt_MT, Name: Maltese (Malta)
+display locale: ID: mt_MT, Name: Maltese (Malta)
+format locale: ID: mt_MT, Name: Maltese (Malta)
+default charset: ISO-8859-3
+
+OS Locale:  mt_MT.utf8
+default locale: ID: mt_MT, Name: Maltese (Malta)
+display locale: ID: mt_MT, Name: Maltese (Malta)
+format locale: ID: mt_MT, Name: Maltese (Malta)
+default charset: UTF-8
+
+OS Locale:  nb_NO
+default locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+display locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+format locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nb_NO.iso88591
+default locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+display locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+format locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nb_NO.utf8
+default locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+display locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+format locale: ID: nb_NO, Name: Norwegian Bokmål (Norway)
+default charset: UTF-8
+
+OS Locale:  ne_NP
+default locale: ID: ne_NP, Name: Nepali (Nepal)
+display locale: ID: ne_NP, Name: Nepali (Nepal)
+format locale: ID: ne_NP, Name: Nepali (Nepal)
+default charset: UTF-8
+
+OS Locale:  ne_NP.utf8
+default locale: ID: ne_NP, Name: Nepali (Nepal)
+display locale: ID: ne_NP, Name: Nepali (Nepal)
+format locale: ID: ne_NP, Name: Nepali (Nepal)
+default charset: UTF-8
+
+OS Locale:  nl_BE
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  nl_BE.iso88591
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  nl_BE.iso885915@euro
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  nl_BE.utf8
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: UTF-8
+
+OS Locale:  nl_BE@euro
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  nl_NL
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  nl_NL.iso88591
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  nl_NL.iso885915@euro
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
+
+OS Locale:  nl_NL.utf8
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: UTF-8
+
+OS Locale:  nl_NL@euro
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
+
+OS Locale:  nn_NO
+default locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+display locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+format locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nn_NO.iso88591
+default locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+display locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+format locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nn_NO.utf8
+default locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+display locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+format locale: ID: nn_NO, Name: Norwegian Nynorsk (Norway)
+default charset: UTF-8
+
+OS Locale:  no_NO
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  no_NO.iso88591
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  no_NO.utf8
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: UTF-8
+
+OS Locale:  norwegian
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  nr_ZA
+default locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+display locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+format locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+default charset: UTF-8
+
+OS Locale:  nr_ZA.utf8
+default locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+display locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+format locale: ID: nr_ZA, Name: South Ndebele (South Africa)
+default charset: UTF-8
+
+OS Locale:  nso_ZA
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: UTF-8
+
+OS Locale:  nso_ZA.utf8
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: UTF-8
+
+OS Locale:  nynorsk
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: ISO-8859-1
+
+OS Locale:  oc_FR
+default locale: ID: oc_FR, Name: Occitan (France)
+display locale: ID: oc_FR, Name: Occitan (France)
+format locale: ID: oc_FR, Name: Occitan (France)
+default charset: ISO-8859-1
+
+OS Locale:  oc_FR.iso88591
+default locale: ID: oc_FR, Name: Occitan (France)
+display locale: ID: oc_FR, Name: Occitan (France)
+format locale: ID: oc_FR, Name: Occitan (France)
+default charset: ISO-8859-1
+
+OS Locale:  oc_FR.utf8
+default locale: ID: oc_FR, Name: Occitan (France)
+display locale: ID: oc_FR, Name: Occitan (France)
+format locale: ID: oc_FR, Name: Occitan (France)
+default charset: UTF-8
+
+OS Locale:  om_ET
+default locale: ID: om_ET, Name: Oromo (Ethiopia)
+display locale: ID: om_ET, Name: Oromo (Ethiopia)
+format locale: ID: om_ET, Name: Oromo (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  om_ET.utf8
+default locale: ID: om_ET, Name: Oromo (Ethiopia)
+display locale: ID: om_ET, Name: Oromo (Ethiopia)
+format locale: ID: om_ET, Name: Oromo (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  om_KE
+default locale: ID: om_KE, Name: Oromo (Kenya)
+display locale: ID: om_KE, Name: Oromo (Kenya)
+format locale: ID: om_KE, Name: Oromo (Kenya)
+default charset: ISO-8859-1
+
+OS Locale:  om_KE.iso88591
+default locale: ID: om_KE, Name: Oromo (Kenya)
+display locale: ID: om_KE, Name: Oromo (Kenya)
+format locale: ID: om_KE, Name: Oromo (Kenya)
+default charset: ISO-8859-1
+
+OS Locale:  om_KE.utf8
+default locale: ID: om_KE, Name: Oromo (Kenya)
+display locale: ID: om_KE, Name: Oromo (Kenya)
+format locale: ID: om_KE, Name: Oromo (Kenya)
+default charset: UTF-8
+
+OS Locale:  or_IN
+default locale: ID: or_IN, Name: Oriya (India)
+display locale: ID: or_IN, Name: Oriya (India)
+format locale: ID: or_IN, Name: Oriya (India)
+default charset: UTF-8
+
+OS Locale:  or_IN.utf8
+default locale: ID: or_IN, Name: Oriya (India)
+display locale: ID: or_IN, Name: Oriya (India)
+format locale: ID: or_IN, Name: Oriya (India)
+default charset: UTF-8
+
+OS Locale:  pa_IN
+default locale: ID: pa_IN, Name: Panjabi (India)
+display locale: ID: pa_IN, Name: Panjabi (India)
+format locale: ID: pa_IN, Name: Panjabi (India)
+default charset: UTF-8
+
+OS Locale:  pa_IN.utf8
+default locale: ID: pa_IN, Name: Panjabi (India)
+display locale: ID: pa_IN, Name: Panjabi (India)
+format locale: ID: pa_IN, Name: Panjabi (India)
+default charset: UTF-8
+
+OS Locale:  pa_PK
+default locale: ID: pa_PK, Name: Panjabi (Pakistan)
+display locale: ID: pa_PK, Name: Panjabi (Pakistan)
+format locale: ID: pa_PK, Name: Panjabi (Pakistan)
+default charset: UTF-8
+
+OS Locale:  pa_PK.utf8
+default locale: ID: pa_PK, Name: Panjabi (Pakistan)
+display locale: ID: pa_PK, Name: Panjabi (Pakistan)
+format locale: ID: pa_PK, Name: Panjabi (Pakistan)
+default charset: UTF-8
+
+OS Locale:  pl_PL
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  pl_PL.iso88592
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  pl_PL.utf8
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: UTF-8
+
+OS Locale:  polish
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  portuguese
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt_BR
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: ISO-8859-1
+
+OS Locale:  pt_BR.iso88591
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: ISO-8859-1
+
+OS Locale:  pt_BR.utf8
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: UTF-8
+
+OS Locale:  pt_PT
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt_PT.iso88591
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt_PT.iso885915@euro
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
+
+OS Locale:  pt_PT.utf8
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: UTF-8
+
+OS Locale:  pt_PT@euro
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
+
+OS Locale:  ro_RO
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
+
+OS Locale:  ro_RO.iso88592
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
+
+OS Locale:  ro_RO.utf8
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: UTF-8
+
+OS Locale:  romanian
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
+
+OS Locale:  ru_RU
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  ru_RU.iso88595
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  ru_RU.koi8r
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: KOI8-R
+
+OS Locale:  ru_RU.utf8
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: UTF-8
+
+OS Locale:  ru_UA
+default locale: ID: ru_UA, Name: Russian (Ukraine)
+display locale: ID: ru_UA, Name: Russian (Ukraine)
+format locale: ID: ru_UA, Name: Russian (Ukraine)
+default charset: KOI8-U
+
+OS Locale:  ru_UA.koi8u
+default locale: ID: ru_UA, Name: Russian (Ukraine)
+display locale: ID: ru_UA, Name: Russian (Ukraine)
+format locale: ID: ru_UA, Name: Russian (Ukraine)
+default charset: KOI8-U
+
+OS Locale:  ru_UA.utf8
+default locale: ID: ru_UA, Name: Russian (Ukraine)
+display locale: ID: ru_UA, Name: Russian (Ukraine)
+format locale: ID: ru_UA, Name: Russian (Ukraine)
+default charset: UTF-8
+
+OS Locale:  russian
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  rw_RW
+default locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+display locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+format locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+default charset: UTF-8
+
+OS Locale:  rw_RW.utf8
+default locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+display locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+format locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+default charset: UTF-8
+
+OS Locale:  se_NO
+default locale: ID: se_NO, Name: Northern Sami (Norway)
+display locale: ID: se_NO, Name: Northern Sami (Norway)
+format locale: ID: se_NO, Name: Northern Sami (Norway)
+default charset: UTF-8
+
+OS Locale:  se_NO.utf8
+default locale: ID: se_NO, Name: Northern Sami (Norway)
+display locale: ID: se_NO, Name: Northern Sami (Norway)
+format locale: ID: se_NO, Name: Northern Sami (Norway)
+default charset: UTF-8
+
+OS Locale:  si_LK
+default locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+display locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+format locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+default charset: UTF-8
+
+OS Locale:  si_LK.utf8
+default locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+display locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+format locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+default charset: UTF-8
+
+OS Locale:  sid_ET
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  sid_ET.utf8
+default locale: ID: en_ET, Name: English (Ethiopia)
+display locale: ID: en_ET, Name: English (Ethiopia)
+format locale: ID: en_ET, Name: English (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  sk_SK
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
+
+OS Locale:  sk_SK.iso88592
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
+
+OS Locale:  sk_SK.utf8
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: UTF-8
+
+OS Locale:  sl_SI
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  sl_SI.iso88592
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  sl_SI.utf8
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: UTF-8
+
+OS Locale:  slovak
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
+
+OS Locale:  slovene
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  slovenian
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  so_DJ
+default locale: ID: so_DJ, Name: Somali (Djibouti)
+display locale: ID: so_DJ, Name: Somali (Djibouti)
+format locale: ID: so_DJ, Name: Somali (Djibouti)
+default charset: ISO-8859-1
+
+OS Locale:  so_DJ.iso88591
+default locale: ID: so_DJ, Name: Somali (Djibouti)
+display locale: ID: so_DJ, Name: Somali (Djibouti)
+format locale: ID: so_DJ, Name: Somali (Djibouti)
+default charset: ISO-8859-1
+
+OS Locale:  so_DJ.utf8
+default locale: ID: so_DJ, Name: Somali (Djibouti)
+display locale: ID: so_DJ, Name: Somali (Djibouti)
+format locale: ID: so_DJ, Name: Somali (Djibouti)
+default charset: UTF-8
+
+OS Locale:  so_ET
+default locale: ID: so_ET, Name: Somali (Ethiopia)
+display locale: ID: so_ET, Name: Somali (Ethiopia)
+format locale: ID: so_ET, Name: Somali (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  so_ET.utf8
+default locale: ID: so_ET, Name: Somali (Ethiopia)
+display locale: ID: so_ET, Name: Somali (Ethiopia)
+format locale: ID: so_ET, Name: Somali (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  so_KE
+default locale: ID: so_KE, Name: Somali (Kenya)
+display locale: ID: so_KE, Name: Somali (Kenya)
+format locale: ID: so_KE, Name: Somali (Kenya)
+default charset: ISO-8859-1
+
+OS Locale:  so_KE.iso88591
+default locale: ID: so_KE, Name: Somali (Kenya)
+display locale: ID: so_KE, Name: Somali (Kenya)
+format locale: ID: so_KE, Name: Somali (Kenya)
+default charset: ISO-8859-1
+
+OS Locale:  so_KE.utf8
+default locale: ID: so_KE, Name: Somali (Kenya)
+display locale: ID: so_KE, Name: Somali (Kenya)
+format locale: ID: so_KE, Name: Somali (Kenya)
+default charset: UTF-8
+
+OS Locale:  so_SO
+default locale: ID: so_SO, Name: Somali (Somalia)
+display locale: ID: so_SO, Name: Somali (Somalia)
+format locale: ID: so_SO, Name: Somali (Somalia)
+default charset: ISO-8859-1
+
+OS Locale:  so_SO.iso88591
+default locale: ID: so_SO, Name: Somali (Somalia)
+display locale: ID: so_SO, Name: Somali (Somalia)
+format locale: ID: so_SO, Name: Somali (Somalia)
+default charset: ISO-8859-1
+
+OS Locale:  so_SO.utf8
+default locale: ID: so_SO, Name: Somali (Somalia)
+display locale: ID: so_SO, Name: Somali (Somalia)
+format locale: ID: so_SO, Name: Somali (Somalia)
+default charset: UTF-8
+
+OS Locale:  spanish
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  sq_AL
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: ISO-8859-1
+
+OS Locale:  sq_AL.iso88591
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: ISO-8859-1
+
+OS Locale:  sq_AL.utf8
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: UTF-8
+
+OS Locale:  sr_CS
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: ISO-8859-5
+
+OS Locale:  sr_CS.iso88595
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: ISO-8859-5
+
+OS Locale:  sr_CS.utf8
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: UTF-8
+
+OS Locale:  sr_ME
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_ME.utf8
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_RS
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_RS.utf8
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_RS.utf8@latin
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  sr_RS@latin
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: UTF-8
+
+OS Locale:  ss_ZA
+default locale: ID: ss_ZA, Name: Swati (South Africa)
+display locale: ID: ss_ZA, Name: Swati (South Africa)
+format locale: ID: ss_ZA, Name: Swati (South Africa)
+default charset: UTF-8
+
+OS Locale:  ss_ZA.utf8
+default locale: ID: ss_ZA, Name: Swati (South Africa)
+display locale: ID: ss_ZA, Name: Swati (South Africa)
+format locale: ID: ss_ZA, Name: Swati (South Africa)
+default charset: UTF-8
+
+OS Locale:  st_ZA
+default locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+display locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+format locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  st_ZA.iso88591
+default locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+display locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+format locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  st_ZA.utf8
+default locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+display locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+format locale: ID: st_ZA, Name: Southern Sotho (South Africa)
+default charset: UTF-8
+
+OS Locale:  sv_FI
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  sv_FI.iso88591
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  sv_FI.iso885915@euro
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  sv_FI.utf8
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: UTF-8
+
+OS Locale:  sv_FI@euro
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: sv_FI, Name: Swedish (Finland)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  sv_SE
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  sv_SE.iso88591
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  sv_SE.iso885915
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-15
+
+OS Locale:  sv_SE.utf8
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: UTF-8
+
+OS Locale:  swedish
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  ta_IN
+default locale: ID: ta_IN, Name: Tamil (India)
+display locale: ID: ta_IN, Name: Tamil (India)
+format locale: ID: ta_IN, Name: Tamil (India)
+default charset: UTF-8
+
+OS Locale:  ta_IN.utf8
+default locale: ID: ta_IN, Name: Tamil (India)
+display locale: ID: ta_IN, Name: Tamil (India)
+format locale: ID: ta_IN, Name: Tamil (India)
+default charset: UTF-8
+
+OS Locale:  te_IN
+default locale: ID: te_IN, Name: Telugu (India)
+display locale: ID: te_IN, Name: Telugu (India)
+format locale: ID: te_IN, Name: Telugu (India)
+default charset: UTF-8
+
+OS Locale:  te_IN.utf8
+default locale: ID: te_IN, Name: Telugu (India)
+display locale: ID: te_IN, Name: Telugu (India)
+format locale: ID: te_IN, Name: Telugu (India)
+default charset: UTF-8
+
+OS Locale:  tg_TJ
+default locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+display locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: UTF-8
+
+OS Locale:  tg_TJ.koi8t
+default locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+display locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: UTF-8
+
+OS Locale:  tg_TJ.utf8
+default locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+display locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: UTF-8
+
+OS Locale:  th_TH
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
+
+OS Locale:  th_TH.tis620
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
+
+OS Locale:  th_TH.utf8
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: UTF-8
+
+OS Locale:  thai
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: TIS-620
+
+OS Locale:  ti_ER
+default locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+display locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+format locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+default charset: UTF-8
+
+OS Locale:  ti_ER.utf8
+default locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+display locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+format locale: ID: ti_ER, Name: Tigrinya (Eritrea)
+default charset: UTF-8
+
+OS Locale:  ti_ET
+default locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+display locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+format locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  ti_ET.utf8
+default locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+display locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+format locale: ID: ti_ET, Name: Tigrinya (Ethiopia)
+default charset: UTF-8
+
+OS Locale:  tig_ER
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  tig_ER.utf8
+default locale: ID: en_ER, Name: English (Eritrea)
+display locale: ID: en_ER, Name: English (Eritrea)
+format locale: ID: en_ER, Name: English (Eritrea)
+default charset: UTF-8
+
+OS Locale:  tl_PH
+default locale: ID: tl_PH, Name: Tagalog (Philippines)
+display locale: ID: tl_PH, Name: Tagalog (Philippines)
+format locale: ID: tl_PH, Name: Tagalog (Philippines)
+default charset: ISO-8859-1
+
+OS Locale:  tl_PH.iso88591
+default locale: ID: tl_PH, Name: Tagalog (Philippines)
+display locale: ID: tl_PH, Name: Tagalog (Philippines)
+format locale: ID: tl_PH, Name: Tagalog (Philippines)
+default charset: ISO-8859-1
+
+OS Locale:  tl_PH.utf8
+default locale: ID: tl_PH, Name: Tagalog (Philippines)
+display locale: ID: tl_PH, Name: Tagalog (Philippines)
+format locale: ID: tl_PH, Name: Tagalog (Philippines)
+default charset: UTF-8
+
+OS Locale:  tn_ZA
+default locale: ID: tn_ZA, Name: Tswana (South Africa)
+display locale: ID: tn_ZA, Name: Tswana (South Africa)
+format locale: ID: tn_ZA, Name: Tswana (South Africa)
+default charset: UTF-8
+
+OS Locale:  tn_ZA.utf8
+default locale: ID: tn_ZA, Name: Tswana (South Africa)
+display locale: ID: tn_ZA, Name: Tswana (South Africa)
+format locale: ID: tn_ZA, Name: Tswana (South Africa)
+default charset: UTF-8
+
+OS Locale:  tr_CY
+default locale: ID: tr_CY, Name: Turkish (Cyprus)
+display locale: ID: tr_CY, Name: Turkish (Cyprus)
+format locale: ID: tr_CY, Name: Turkish (Cyprus)
+default charset: ISO-8859-9
+
+OS Locale:  tr_CY.iso88599
+default locale: ID: tr_CY, Name: Turkish (Cyprus)
+display locale: ID: tr_CY, Name: Turkish (Cyprus)
+format locale: ID: tr_CY, Name: Turkish (Cyprus)
+default charset: ISO-8859-9
+
+OS Locale:  tr_CY.utf8
+default locale: ID: tr_CY, Name: Turkish (Cyprus)
+display locale: ID: tr_CY, Name: Turkish (Cyprus)
+format locale: ID: tr_CY, Name: Turkish (Cyprus)
+default charset: UTF-8
+
+OS Locale:  tr_TR
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  tr_TR.iso88599
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  tr_TR.utf8
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: UTF-8
+
+OS Locale:  ts_ZA
+default locale: ID: ts_ZA, Name: Tsonga (South Africa)
+display locale: ID: ts_ZA, Name: Tsonga (South Africa)
+format locale: ID: ts_ZA, Name: Tsonga (South Africa)
+default charset: UTF-8
+
+OS Locale:  ts_ZA.utf8
+default locale: ID: ts_ZA, Name: Tsonga (South Africa)
+display locale: ID: ts_ZA, Name: Tsonga (South Africa)
+format locale: ID: ts_ZA, Name: Tsonga (South Africa)
+default charset: UTF-8
+
+OS Locale:  tt_RU.utf8
+default locale: ID: tt_RU, Name: Tatar (Russia)
+display locale: ID: tt_RU, Name: Tatar (Russia)
+format locale: ID: tt_RU, Name: Tatar (Russia)
+default charset: UTF-8
+
+OS Locale:  turkish
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  uk_UA
+default locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+display locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+format locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+default charset: KOI8-U
+
+OS Locale:  uk_UA.koi8u
+default locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+display locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+format locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+default charset: KOI8-U
+
+OS Locale:  uk_UA.utf8
+default locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+display locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+format locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+default charset: UTF-8
+
+OS Locale:  ur_PK
+default locale: ID: ur_PK, Name: Urdu (Pakistan)
+display locale: ID: ur_PK, Name: Urdu (Pakistan)
+format locale: ID: ur_PK, Name: Urdu (Pakistan)
+default charset: UTF-8
+
+OS Locale:  ur_PK.utf8
+default locale: ID: ur_PK, Name: Urdu (Pakistan)
+display locale: ID: ur_PK, Name: Urdu (Pakistan)
+format locale: ID: ur_PK, Name: Urdu (Pakistan)
+default charset: UTF-8
+
+OS Locale:  uz_UZ
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: ISO-8859-1
+
+OS Locale:  uz_UZ.iso88591
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: ISO-8859-1
+
+OS Locale:  uz_UZ.utf8@cyrillic
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: UTF-8
+
+OS Locale:  uz_UZ@cyrillic
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: UTF-8
+
+OS Locale:  ve_ZA
+default locale: ID: ve_ZA, Name: Venda (South Africa)
+display locale: ID: ve_ZA, Name: Venda (South Africa)
+format locale: ID: ve_ZA, Name: Venda (South Africa)
+default charset: UTF-8
+
+OS Locale:  ve_ZA.utf8
+default locale: ID: ve_ZA, Name: Venda (South Africa)
+display locale: ID: ve_ZA, Name: Venda (South Africa)
+format locale: ID: ve_ZA, Name: Venda (South Africa)
+default charset: UTF-8
+
+OS Locale:  vi_VN
+default locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+display locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+format locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+default charset: UTF-8
+
+OS Locale:  vi_VN.tcvn
+default locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+display locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+format locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+default charset: UTF-8
+
+OS Locale:  vi_VN.utf8
+default locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+display locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+format locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+default charset: UTF-8
+
+OS Locale:  wa_BE
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  wa_BE.iso88591
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  wa_BE.iso885915@euro
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  wa_BE.utf8
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: UTF-8
+
+OS Locale:  wa_BE@euro
+default locale: ID: wa_BE, Name: Walloon (Belgium)
+display locale: ID: wa_BE, Name: Walloon (Belgium)
+format locale: ID: wa_BE, Name: Walloon (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  xh_ZA
+default locale: ID: xh_ZA, Name: Xhosa (South Africa)
+display locale: ID: xh_ZA, Name: Xhosa (South Africa)
+format locale: ID: xh_ZA, Name: Xhosa (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  xh_ZA.iso88591
+default locale: ID: xh_ZA, Name: Xhosa (South Africa)
+display locale: ID: xh_ZA, Name: Xhosa (South Africa)
+format locale: ID: xh_ZA, Name: Xhosa (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  xh_ZA.utf8
+default locale: ID: xh_ZA, Name: Xhosa (South Africa)
+display locale: ID: xh_ZA, Name: Xhosa (South Africa)
+format locale: ID: xh_ZA, Name: Xhosa (South Africa)
+default charset: UTF-8
+
+OS Locale:  yi_US
+default locale: ID: ji_US, Name: Yiddish (United States)
+display locale: ID: ji_US, Name: Yiddish (United States)
+format locale: ID: ji_US, Name: Yiddish (United States)
+default charset: windows-1255
+
+OS Locale:  yi_US.cp1255
+default locale: ID: ji_US, Name: Yiddish (United States)
+display locale: ID: ji_US, Name: Yiddish (United States)
+format locale: ID: ji_US, Name: Yiddish (United States)
+default charset: windows-1255
+
+OS Locale:  yi_US.utf8
+default locale: ID: ji_US, Name: Yiddish (United States)
+display locale: ID: ji_US, Name: Yiddish (United States)
+format locale: ID: ji_US, Name: Yiddish (United States)
+default charset: UTF-8
+
+OS Locale:  zh_CN
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh_CN.gb18030
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
+
+OS Locale:  zh_CN.gb2312
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh_CN.gbk
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale:  zh_CN.utf8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale:  zh_HK
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: Big5-HKSCS
+
+OS Locale:  zh_HK.big5hkscs
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: Big5-HKSCS
+
+OS Locale:  zh_HK.utf8
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: UTF-8
+
+OS Locale:  zh_SG
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: zh_SG, Name: Chinese (Singapore)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: GB2312
+
+OS Locale:  zh_SG.gb2312
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: zh_SG, Name: Chinese (Singapore)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: GB2312
+
+OS Locale:  zh_SG.gbk
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: zh_SG, Name: Chinese (Singapore)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: GBK
+
+OS Locale:  zh_SG.utf8
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: zh_SG, Name: Chinese (Singapore)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: UTF-8
+
+OS Locale:  zh_TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: Big5
+
+OS Locale:  zh_TW.big5
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: Big5
+
+OS Locale:  zh_TW.euctw
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
+
+OS Locale:  zh_TW.utf8
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
+
+OS Locale:  zu_ZA
+default locale: ID: zu_ZA, Name: Zulu (South Africa)
+display locale: ID: zu_ZA, Name: Zulu (South Africa)
+format locale: ID: zu_ZA, Name: Zulu (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  zu_ZA.iso88591
+default locale: ID: zu_ZA, Name: Zulu (South Africa)
+display locale: ID: zu_ZA, Name: Zulu (South Africa)
+format locale: ID: zu_ZA, Name: Zulu (South Africa)
+default charset: ISO-8859-1
+
+OS Locale:  zu_ZA.utf8
+default locale: ID: zu_ZA, Name: Zulu (South Africa)
+display locale: ID: zu_ZA, Name: Zulu (South Africa)
+format locale: ID: zu_ZA, Name: Zulu (South Africa)
+default charset: UTF-8
+
+Testing some typical combinations
+
+
+OS Locale (LC_CTYPE: ja_JP.UTF-8, LC_MESSAGES: zh_CN.UTF-8)
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: UTF-8
+
+OS Locale (LC_CTYPE: zh_CN.UTF-8, LC_MESSAGES: en_US.UTF-8)
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale (LC_CTYPE: C, LC_MESSAGES: zh_CN.UTF-8)
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: en_US, Name: English (United States)
+default charset: US-ASCII
--- a/test/java/util/Locale/data/deflocale.sh	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/util/Locale/data/deflocale.sh	Fri Sep 24 16:41:32 2010 -0700
@@ -31,8 +31,21 @@
 #
 cat /etc/*release
 uname -a
-env LC_COLLATE=C ls /usr/lib/locale | while read line; do
+echo "Testing all available locales"
+/usr/bin/locale -a | while read line; do
     echo ""
     echo "OS Locale: " $line
-    env LANG=$line LC_ALL=$line $1 PrintDefaultLocale
+    env LC_ALL= LC_CTYPE= LC_MESSAGES= LANG=$line $1 $2 $3 $4 $5 $6 $7 $8 $9 PrintDefaultLocale
 done
+
+echo ""
+echo "Testing some typical combinations"
+echo ""
+while read lcctype lcmessages; do
+    if [ "$lcctype" = "#" -o "$lcctype" = "" ]; then
+        continue
+    fi
+    echo ""
+    echo "OS Locale (LC_CTYPE: "$lcctype", LC_MESSAGES: "$lcmessages")"
+    env LC_ALL= LC_CTYPE=$lcctype LC_MESSAGES=$lcmessages $1 $2 $3 $4 $5 $6 $7 $8 $9 PrintDefaultLocale
+done < deflocale.input
--- a/test/java/util/Locale/data/deflocale.sol10	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/util/Locale/data/deflocale.sol10	Fri Sep 24 16:41:32 2010 -0700
@@ -2,1449 +2,1724 @@
 
                       (copyright from `uname -a` goes here)
 
-SunOS deltas4 5.10 Generic_118833-03 sun4u sparc SUNW,Sun-Blade-2500
+SunOS deltas4 5.10 Generic_142900-03 sun4u sparc SUNW,Sun-Blade-2500
+Testing all available locales
 
 OS Locale:  C
-en
-English
-US-ASCII
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: US-ASCII
 
 OS Locale:  POSIX
-en
-English
-US-ASCII
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: US-ASCII
 
 OS Locale:  ar
-ar_EG
-Arabic (Egypt)
-ISO-8859-6
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: ISO-8859-6
 
 OS Locale:  ar_EG.UTF-8
-ar_EG
-Arabic (Egypt)
-UTF-8
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: UTF-8
 
 OS Locale:  ar_SA.UTF-8
-ar_SA
-Arabic (Saudi Arabia)
-UTF-8
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: UTF-8
 
 OS Locale:  bg_BG
-bg_BG
-Bulgarian (Bulgaria)
-ISO-8859-5
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: ISO-8859-5
 
 OS Locale:  bg_BG.ISO8859-5
-bg_BG
-Bulgarian (Bulgaria)
-ISO-8859-5
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: ISO-8859-5
 
 OS Locale:  ca
-ca_ES
-Catalan (Spain)
-ISO-8859-1
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
 
 OS Locale:  ca_ES
-ca_ES
-Catalan (Spain)
-ISO-8859-1
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
 
 OS Locale:  ca_ES.ISO8859-1
-ca_ES
-Catalan (Spain)
-ISO-8859-1
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
 
 OS Locale:  ca_ES.ISO8859-15
-ca_ES
-Catalan (Spain)
-ISO-8859-15
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-15
 
 OS Locale:  ca_ES.ISO8859-15@euro
-ca_ES
-Catalan (Spain)
-ISO-8859-15
-
-OS Locale:  common
-en
-English
-ISO-8859-1
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-15
 
 OS Locale:  cs_CZ
-cs_CZ
-Czech (Czech Republic)
-ISO-8859-2
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
 
 OS Locale:  cs_CZ.ISO8859-2
-cs_CZ
-Czech (Czech Republic)
-ISO-8859-2
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
 
 OS Locale:  cs_CZ.UTF-8
-cs_CZ
-Czech (Czech Republic)
-UTF-8
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: UTF-8
 
 OS Locale:  cs_CZ.UTF-8@euro
-cs_CZ
-Czech (Czech Republic)
-UTF-8
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: UTF-8
 
 OS Locale:  cz
-cs_CZ
-Czech (Czech Republic)
-ISO-8859-2
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
 
 OS Locale:  da
-da_DK
-Danish (Denmark)
-ISO-8859-1
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
 
 OS Locale:  da.ISO8859-15
-da_DK
-Danish (Denmark)
-ISO-8859-15
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-15
 
 OS Locale:  da_DK
-da_DK
-Danish (Denmark)
-ISO-8859-1
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
 
 OS Locale:  da_DK.ISO8859-1
-da_DK
-Danish (Denmark)
-ISO-8859-1
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
 
 OS Locale:  da_DK.ISO8859-15
-da_DK
-Danish (Denmark)
-ISO-8859-15
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-15
 
 OS Locale:  da_DK.ISO8859-15@euro
-da_DK
-Danish (Denmark)
-ISO-8859-15
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-15
 
 OS Locale:  de
-de_DE
-German (Germany)
-ISO-8859-1
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
 
 OS Locale:  de.ISO8859-15
-de_DE
-German (Germany)
-ISO-8859-15
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
 
 OS Locale:  de.UTF-8
-de_DE
-German (Germany)
-UTF-8
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: UTF-8
 
 OS Locale:  de_AT
-de_AT
-German (Austria)
-ISO-8859-1
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-1
 
 OS Locale:  de_AT.ISO8859-1
-de_AT
-German (Austria)
-ISO-8859-1
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-1
 
 OS Locale:  de_AT.ISO8859-15
-de_AT
-German (Austria)
-ISO-8859-15
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-15
 
 OS Locale:  de_AT.ISO8859-15@euro
-de_AT
-German (Austria)
-ISO-8859-15
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-15
 
 OS Locale:  de_CH
-de_CH
-German (Switzerland)
-ISO-8859-1
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: ISO-8859-1
 
 OS Locale:  de_CH.ISO8859-1
-de_CH
-German (Switzerland)
-ISO-8859-1
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: ISO-8859-1
 
 OS Locale:  de_DE
-de_DE
-German (Germany)
-ISO-8859-1
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
 
 OS Locale:  de_DE.ISO8859-1
-de_DE
-German (Germany)
-ISO-8859-1
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
 
 OS Locale:  de_DE.ISO8859-15
-de_DE
-German (Germany)
-ISO-8859-15
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
 
 OS Locale:  de_DE.ISO8859-15@euro
-de_DE
-German (Germany)
-ISO-8859-15
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
 
 OS Locale:  de_DE.UTF-8
-de_DE
-German (Germany)
-UTF-8
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: UTF-8
 
 OS Locale:  de_DE.UTF-8@euro
-de_DE
-German (Germany)
-UTF-8
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: UTF-8
 
 OS Locale:  el
-el_GR
-Greek (Greece)
-ISO-8859-7
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
 
 OS Locale:  el.sun_eu_greek
-el_GR
-Greek (Greece)
-ISO-8859-7
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
 
 OS Locale:  el_GR
-el_GR
-Greek (Greece)
-ISO-8859-7
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
 
 OS Locale:  el_GR.ISO8859-7
-el_GR
-Greek (Greece)
-ISO-8859-7
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
 
 OS Locale:  el_GR.ISO8859-7@euro
-el_GR
-Greek (Greece)
-ISO-8859-7
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
 
 OS Locale:  en_AU
-en_AU
-English (Australia)
-ISO-8859-1
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: ISO-8859-1
 
 OS Locale:  en_AU.ISO8859-1
-en_AU
-English (Australia)
-ISO-8859-1
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: ISO-8859-1
 
 OS Locale:  en_CA
-en_CA
-English (Canada)
-ISO-8859-1
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: ISO-8859-1
 
 OS Locale:  en_CA.ISO8859-1
-en_CA
-English (Canada)
-ISO-8859-1
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  en_CA.UTF-8
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: UTF-8
 
 OS Locale:  en_GB
-en_GB
-English (United Kingdom)
-ISO-8859-1
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-1
 
 OS Locale:  en_GB.ISO8859-1
-en_GB
-English (United Kingdom)
-ISO-8859-1
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-1
 
 OS Locale:  en_GB.ISO8859-15
-en_GB
-English (United Kingdom)
-ISO-8859-15
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-15
 
 OS Locale:  en_GB.ISO8859-15@euro
-en_GB
-English (United Kingdom)
-ISO-8859-15
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-15
 
 OS Locale:  en_IE
-en_IE
-English (Ireland)
-ISO-8859-1
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-1
 
 OS Locale:  en_IE.ISO8859-1
-en_IE
-English (Ireland)
-ISO-8859-1
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-1
 
 OS Locale:  en_IE.ISO8859-15
-en_IE
-English (Ireland)
-ISO-8859-15
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-15
 
 OS Locale:  en_IE.ISO8859-15@euro
-en_IE
-English (Ireland)
-ISO-8859-15
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-15
 
 OS Locale:  en_NZ
-en_NZ
-English (New Zealand)
-ISO-8859-1
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: ISO-8859-1
 
 OS Locale:  en_NZ.ISO8859-1
-en_NZ
-English (New Zealand)
-ISO-8859-1
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: ISO-8859-1
 
 OS Locale:  en_US
-en_US
-English (United States)
-ISO-8859-1
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-1
 
 OS Locale:  en_US.ISO8859-1
-en_US
-English (United States)
-ISO-8859-1
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-1
 
 OS Locale:  en_US.ISO8859-15
-en_US
-English (United States)
-ISO-8859-15
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-15
 
 OS Locale:  en_US.ISO8859-15@euro
-en_US
-English (United States)
-ISO-8859-15
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-15
 
 OS Locale:  en_US.UTF-8
-en_US
-English (United States)
-UTF-8
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: UTF-8
 
 OS Locale:  es
-es_ES
-Spanish (Spain)
-ISO-8859-1
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
 
 OS Locale:  es.ISO8859-15
-es_ES
-Spanish (Spain)
-ISO-8859-15
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
 
 OS Locale:  es.UTF-8
-es_ES
-Spanish (Spain)
-UTF-8
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: UTF-8
 
 OS Locale:  es_AR
-es_AR
-Spanish (Argentina)
-ISO-8859-1
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: ISO-8859-1
 
 OS Locale:  es_AR.ISO8859-1
-es_AR
-Spanish (Argentina)
-ISO-8859-1
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: ISO-8859-1
 
 OS Locale:  es_BO
-es_BO
-Spanish (Bolivia)
-ISO-8859-1
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: ISO-8859-1
 
 OS Locale:  es_BO.ISO8859-1
-es_BO
-Spanish (Bolivia)
-ISO-8859-1
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: ISO-8859-1
 
 OS Locale:  es_CL
-es_CL
-Spanish (Chile)
-ISO-8859-1
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: ISO-8859-1
 
 OS Locale:  es_CL.ISO8859-1
-es_CL
-Spanish (Chile)
-ISO-8859-1
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: ISO-8859-1
 
 OS Locale:  es_CO
-es_CO
-Spanish (Colombia)
-ISO-8859-1
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: ISO-8859-1
 
 OS Locale:  es_CO.ISO8859-1
-es_CO
-Spanish (Colombia)
-ISO-8859-1
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: ISO-8859-1
 
 OS Locale:  es_CR
-es_CR
-Spanish (Costa Rica)
-ISO-8859-1
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: ISO-8859-1
 
 OS Locale:  es_CR.ISO8859-1
-es_CR
-Spanish (Costa Rica)
-ISO-8859-1
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: ISO-8859-1
 
 OS Locale:  es_EC
-es_EC
-Spanish (Ecuador)
-ISO-8859-1
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: ISO-8859-1
 
 OS Locale:  es_EC.ISO8859-1
-es_EC
-Spanish (Ecuador)
-ISO-8859-1
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: ISO-8859-1
 
 OS Locale:  es_ES
-es_ES
-Spanish (Spain)
-ISO-8859-1
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
 
 OS Locale:  es_ES.ISO8859-1
-es_ES
-Spanish (Spain)
-ISO-8859-1
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
 
 OS Locale:  es_ES.ISO8859-15
-es_ES
-Spanish (Spain)
-ISO-8859-15
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
 
 OS Locale:  es_ES.ISO8859-15@euro
-es_ES
-Spanish (Spain)
-ISO-8859-15
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
 
 OS Locale:  es_ES.UTF-8
-es_ES
-Spanish (Spain)
-UTF-8
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: UTF-8
 
 OS Locale:  es_ES.UTF-8@euro
-es_ES
-Spanish (Spain)
-UTF-8
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: UTF-8
 
 OS Locale:  es_GT
-es_GT
-Spanish (Guatemala)
-ISO-8859-1
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: ISO-8859-1
 
 OS Locale:  es_GT.ISO8859-1
-es_GT
-Spanish (Guatemala)
-ISO-8859-1
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: ISO-8859-1
 
 OS Locale:  es_MX
-es_MX
-Spanish (Mexico)
-ISO-8859-1
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: ISO-8859-1
 
 OS Locale:  es_MX.ISO8859-1
-es_MX
-Spanish (Mexico)
-ISO-8859-1
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: ISO-8859-1
+
+OS Locale:  es_MX.UTF-8
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: UTF-8
 
 OS Locale:  es_NI
-es_NI
-Spanish (Nicaragua)
-ISO-8859-1
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: ISO-8859-1
 
 OS Locale:  es_NI.ISO8859-1
-es_NI
-Spanish (Nicaragua)
-ISO-8859-1
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: ISO-8859-1
 
 OS Locale:  es_PA
-es_PA
-Spanish (Panama)
-ISO-8859-1
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: ISO-8859-1
 
 OS Locale:  es_PA.ISO8859-1
-es_PA
-Spanish (Panama)
-ISO-8859-1
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: ISO-8859-1
 
 OS Locale:  es_PE
-es_PE
-Spanish (Peru)
-ISO-8859-1
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: ISO-8859-1
 
 OS Locale:  es_PE.ISO8859-1
-es_PE
-Spanish (Peru)
-ISO-8859-1
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: ISO-8859-1
 
 OS Locale:  es_PY
-es_PY
-Spanish (Paraguay)
-ISO-8859-1
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: ISO-8859-1
 
 OS Locale:  es_PY.ISO8859-1
-es_PY
-Spanish (Paraguay)
-ISO-8859-1
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: ISO-8859-1
 
 OS Locale:  es_SV
-es_SV
-Spanish (El Salvador)
-ISO-8859-1
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: ISO-8859-1
 
 OS Locale:  es_SV.ISO8859-1
-es_SV
-Spanish (El Salvador)
-ISO-8859-1
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: ISO-8859-1
 
 OS Locale:  es_UY
-es_UY
-Spanish (Uruguay)
-ISO-8859-1
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: ISO-8859-1
 
 OS Locale:  es_UY.ISO8859-1
-es_UY
-Spanish (Uruguay)
-ISO-8859-1
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: ISO-8859-1
 
 OS Locale:  es_VE
-es_VE
-Spanish (Venezuela)
-ISO-8859-1
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: ISO-8859-1
 
 OS Locale:  es_VE.ISO8859-1
-es_VE
-Spanish (Venezuela)
-ISO-8859-1
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: ISO-8859-1
 
 OS Locale:  et
-et_EE
-Estonian (Estonia)
-ISO-8859-15
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-15
 
 OS Locale:  et_EE
-et_EE
-Estonian (Estonia)
-ISO-8859-15
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-15
 
 OS Locale:  et_EE.ISO8859-15
-et_EE
-Estonian (Estonia)
-ISO-8859-15
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-15
 
 OS Locale:  fi
-fi_FI
-Finnish (Finland)
-ISO-8859-1
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
 
 OS Locale:  fi.ISO8859-15
-fi_FI
-Finnish (Finland)
-ISO-8859-15
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
 
 OS Locale:  fi_FI
-fi_FI
-Finnish (Finland)
-ISO-8859-1
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
 
 OS Locale:  fi_FI.ISO8859-1
-fi_FI
-Finnish (Finland)
-ISO-8859-1
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
 
 OS Locale:  fi_FI.ISO8859-15
-fi_FI
-Finnish (Finland)
-ISO-8859-15
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
 
 OS Locale:  fi_FI.ISO8859-15@euro
-fi_FI
-Finnish (Finland)
-ISO-8859-15
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
 
 OS Locale:  fi_FI.UTF-8
-fi_FI
-Finnish (Finland)
-UTF-8
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: UTF-8
 
 OS Locale:  fr
-fr_FR
-French (France)
-ISO-8859-1
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
 
 OS Locale:  fr.ISO8859-15
-fr_FR
-French (France)
-ISO-8859-15
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
 
 OS Locale:  fr.UTF-8
-fr_FR
-French (France)
-UTF-8
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: UTF-8
 
 OS Locale:  fr_BE
-fr_BE
-French (Belgium)
-ISO-8859-1
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-1
 
 OS Locale:  fr_BE.ISO8859-1
-fr_BE
-French (Belgium)
-ISO-8859-1
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-1
 
 OS Locale:  fr_BE.ISO8859-15
-fr_BE
-French (Belgium)
-ISO-8859-15
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-15
 
 OS Locale:  fr_BE.ISO8859-15@euro
-fr_BE
-French (Belgium)
-ISO-8859-15
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-15
 
 OS Locale:  fr_BE.UTF-8
-fr_BE
-French (Belgium)
-UTF-8
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: UTF-8
 
 OS Locale:  fr_BE.UTF-8@euro
-fr_BE
-French (Belgium)
-UTF-8
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: UTF-8
 
 OS Locale:  fr_CA
-fr_CA
-French (Canada)
-ISO-8859-1
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: ISO-8859-1
 
 OS Locale:  fr_CA.ISO8859-1
-fr_CA
-French (Canada)
-ISO-8859-1
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CA.UTF-8
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: UTF-8
 
 OS Locale:  fr_CH
-fr_CH
-French (Switzerland)
-ISO-8859-1
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: ISO-8859-1
 
 OS Locale:  fr_CH.ISO8859-1
-fr_CH
-French (Switzerland)
-ISO-8859-1
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: ISO-8859-1
 
 OS Locale:  fr_FR
-fr_FR
-French (France)
-ISO-8859-1
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
 
 OS Locale:  fr_FR.ISO8859-1
-fr_FR
-French (France)
-ISO-8859-1
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
 
 OS Locale:  fr_FR.ISO8859-15
-fr_FR
-French (France)
-ISO-8859-15
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
 
 OS Locale:  fr_FR.ISO8859-15@euro
-fr_FR
-French (France)
-ISO-8859-15
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
 
 OS Locale:  fr_FR.UTF-8
-fr_FR
-French (France)
-UTF-8
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: UTF-8
 
 OS Locale:  fr_FR.UTF-8@euro
-fr_FR
-French (France)
-UTF-8
-
-OS Locale:  geo
-en
-English
-ISO-8859-1
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: UTF-8
 
 OS Locale:  he
-iw_IL
-Hebrew (Israel)
-ISO-8859-8
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
 
 OS Locale:  he_IL
-iw_IL
-Hebrew (Israel)
-ISO-8859-8
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
 
 OS Locale:  he_IL.UTF-8
-iw_IL
-Hebrew (Israel)
-UTF-8
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: UTF-8
 
 OS Locale:  hi_IN.UTF-8
-hi_IN
-Hindi (India)
-UTF-8
+default locale: ID: hi_IN, Name: Hindi (India)
+display locale: ID: hi_IN, Name: Hindi (India)
+format locale: ID: hi_IN, Name: Hindi (India)
+default charset: UTF-8
 
 OS Locale:  hr_HR
-hr_HR
-Croatian (Croatia)
-ISO-8859-2
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
 
 OS Locale:  hr_HR.ISO8859-2
-hr_HR
-Croatian (Croatia)
-ISO-8859-2
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
 
 OS Locale:  hu
-hu_HU
-Hungarian (Hungary)
-ISO-8859-2
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
 
 OS Locale:  hu_HU
-hu_HU
-Hungarian (Hungary)
-ISO-8859-2
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
 
 OS Locale:  hu_HU.ISO8859-2
-hu_HU
-Hungarian (Hungary)
-ISO-8859-2
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
 
 OS Locale:  hu_HU.UTF-8
-hu_HU
-Hungarian (Hungary)
-UTF-8
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: UTF-8
 
 OS Locale:  is_IS
-is_IS
-Icelandic (Iceland)
-ISO-8859-1
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
 
 OS Locale:  is_IS.ISO8859-1
-is_IS
-Icelandic (Iceland)
-ISO-8859-1
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
 
 OS Locale:  iso_8859_1
-en_8859_1
-English (8859_1)
-ISO-8859-1
-
-OS Locale:  iso_8859_13
-en
-English
-ISO-8859-1
-
-OS Locale:  iso_8859_15
-en
-English
-ISO-8859-1
-
-OS Locale:  iso_8859_2
-en
-English
-ISO-8859-1
-
-OS Locale:  iso_8859_5
-en
-English
-ISO-8859-1
-
-OS Locale:  iso_8859_7
-en
-English
-ISO-8859-1
-
-OS Locale:  iso_8859_9
-en
-English
-ISO-8859-1
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: US-ASCII
 
 OS Locale:  it
-it_IT
-Italian (Italy)
-ISO-8859-1
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
 
 OS Locale:  it.ISO8859-15
-it_IT
-Italian (Italy)
-ISO-8859-15
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
 
 OS Locale:  it.UTF-8
-it_IT
-Italian (Italy)
-UTF-8
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: UTF-8
 
 OS Locale:  it_IT
-it_IT
-Italian (Italy)
-ISO-8859-1
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
 
 OS Locale:  it_IT.ISO8859-1
-it_IT
-Italian (Italy)
-ISO-8859-1
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
 
 OS Locale:  it_IT.ISO8859-15
-it_IT
-Italian (Italy)
-ISO-8859-15
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
 
 OS Locale:  it_IT.ISO8859-15@euro
-it_IT
-Italian (Italy)
-ISO-8859-15
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
 
 OS Locale:  it_IT.UTF-8
-it_IT
-Italian (Italy)
-UTF-8
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: UTF-8
 
 OS Locale:  it_IT.UTF-8@euro
-it_IT
-Italian (Italy)
-UTF-8
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: UTF-8
 
 OS Locale:  ja
-ja_JP
-Japanese (Japan)
-x-eucJP-Open
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-eucJP-Open
 
 OS Locale:  ja_JP.PCK
-ja_JP
-Japanese (Japan)
-x-PCK
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-PCK
 
 OS Locale:  ja_JP.UTF-8
-ja_JP
-Japanese (Japan)
-UTF-8
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: UTF-8
 
 OS Locale:  ja_JP.eucJP
-ja_JP
-Japanese (Japan)
-x-eucJP-Open
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-eucJP-Open
 
 OS Locale:  ko
-ko_KR
-Korean (South Korea)
-EUC-KR
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
 
 OS Locale:  ko.UTF-8
-ko_KR
-Korean (South Korea)
-UTF-8
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: UTF-8
 
 OS Locale:  ko_KR.EUC
-ko_KR
-Korean (South Korea)
-EUC-KR
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
 
 OS Locale:  ko_KR.EUC@dict
-ko_KR
-Korean (South Korea)
-EUC-KR
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
 
 OS Locale:  ko_KR.UTF-8
-ko_KR
-Korean (South Korea)
-UTF-8
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: UTF-8
 
 OS Locale:  ko_KR.UTF-8@dict
-ko_KR
-Korean (South Korea)
-UTF-8
-
-OS Locale:  lcttab
-en
-English
-ISO-8859-1
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: UTF-8
 
 OS Locale:  lt
-lt_LT
-Lithuanian (Lithuania)
-ISO-8859-13
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
 
 OS Locale:  lt_LT
-lt_LT
-Lithuanian (Lithuania)
-ISO-8859-13
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
 
 OS Locale:  lt_LT.ISO8859-13
-lt_LT
-Lithuanian (Lithuania)
-ISO-8859-13
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
 
 OS Locale:  lv
-lv_LV
-Latvian (Latvia)
-ISO-8859-13
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
 
 OS Locale:  lv_LV
-lv_LV
-Latvian (Latvia)
-ISO-8859-13
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
 
 OS Locale:  lv_LV.ISO8859-13
-lv_LV
-Latvian (Latvia)
-ISO-8859-13
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
 
 OS Locale:  mk_MK
-mk_MK
-Macedonian (Macedonia)
-ISO-8859-5
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: ISO-8859-5
 
 OS Locale:  mk_MK.ISO8859-5
-mk_MK
-Macedonian (Macedonia)
-ISO-8859-5
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: ISO-8859-5
 
 OS Locale:  nl
-nl_NL
-Dutch (Netherlands)
-ISO-8859-1
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
 
 OS Locale:  nl.ISO8859-15
-nl_NL
-Dutch (Netherlands)
-ISO-8859-15
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
 
 OS Locale:  nl_BE
-nl_BE
-Dutch (Belgium)
-ISO-8859-1
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-1
 
 OS Locale:  nl_BE.ISO8859-1
-nl_BE
-Dutch (Belgium)
-ISO-8859-1
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-1
 
 OS Locale:  nl_BE.ISO8859-15
-nl_BE
-Dutch (Belgium)
-ISO-8859-15
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-15
 
 OS Locale:  nl_BE.ISO8859-15@euro
-nl_BE
-Dutch (Belgium)
-ISO-8859-15
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-15
 
 OS Locale:  nl_NL
-nl_NL
-Dutch (Netherlands)
-ISO-8859-1
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
 
 OS Locale:  nl_NL.ISO8859-1
-nl_NL
-Dutch (Netherlands)
-ISO-8859-1
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
 
 OS Locale:  nl_NL.ISO8859-15
-nl_NL
-Dutch (Netherlands)
-ISO-8859-15
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
 
 OS Locale:  nl_NL.ISO8859-15@euro
-nl_NL
-Dutch (Netherlands)
-ISO-8859-15
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
 
 OS Locale:  no
-no_NO
-Norwegian (Norway)
-ISO-8859-1
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
 
 OS Locale:  no_NO
-no_NO
-Norwegian (Norway)
-ISO-8859-1
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
 
 OS Locale:  no_NO.ISO8859-1@bokmal
-no_NO
-Norwegian (Norway)
-ISO-8859-1
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
 
 OS Locale:  no_NO.ISO8859-1@nynorsk
-no_NO_NY
-Norwegian (Norway,Nynorsk)
-ISO-8859-1
+default locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+display locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+format locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+default charset: ISO-8859-1
 
 OS Locale:  no_NY
-no_NY
-Norwegian (NY)
-ISO-8859-1
+default locale: ID: no_, Name: Norwegian ()
+display locale: ID: no_, Name: Norwegian ()
+format locale: ID: no_, Name: Norwegian ()
+default charset: ISO-8859-1
 
 OS Locale:  nr
-nr
-South Ndebele
-ISO-8859-2
+default locale: ID: nr, Name: South Ndebele
+display locale: ID: nr, Name: South Ndebele
+format locale: ID: nr, Name: South Ndebele
+default charset: ISO-8859-2
 
 OS Locale:  pl
-pl_PL
-Polish (Poland)
-ISO-8859-2
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
 
 OS Locale:  pl.UTF-8
-pl_PL
-Polish (Poland)
-UTF-8
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: UTF-8
 
 OS Locale:  pl_PL
-pl_PL
-Polish (Poland)
-ISO-8859-2
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
 
 OS Locale:  pl_PL.ISO8859-2
-pl_PL
-Polish (Poland)
-ISO-8859-2
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
 
 OS Locale:  pl_PL.UTF-8
-pl_PL
-Polish (Poland)
-UTF-8
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: UTF-8
 
 OS Locale:  pt
-pt_PT
-Portuguese (Portugal)
-ISO-8859-1
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
 
 OS Locale:  pt.ISO8859-15
-pt_PT
-Portuguese (Portugal)
-ISO-8859-15
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
 
 OS Locale:  pt_BR
-pt_BR
-Portuguese (Brazil)
-ISO-8859-1
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: ISO-8859-1
 
 OS Locale:  pt_BR.ISO8859-1
-pt_BR
-Portuguese (Brazil)
-ISO-8859-1
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: ISO-8859-1
 
 OS Locale:  pt_BR.UTF-8
-pt_BR
-Portuguese (Brazil)
-UTF-8
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: UTF-8
 
 OS Locale:  pt_PT
-pt_PT
-Portuguese (Portugal)
-ISO-8859-1
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
 
 OS Locale:  pt_PT.ISO8859-1
-pt_PT
-Portuguese (Portugal)
-ISO-8859-1
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
 
 OS Locale:  pt_PT.ISO8859-15
-pt_PT
-Portuguese (Portugal)
-ISO-8859-15
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
 
 OS Locale:  pt_PT.ISO8859-15@euro
-pt_PT
-Portuguese (Portugal)
-ISO-8859-15
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
 
 OS Locale:  ro_RO
-ro_RO
-Romanian (Romania)
-ISO-8859-2
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
 
 OS Locale:  ro_RO.ISO8859-2
-ro_RO
-Romanian (Romania)
-ISO-8859-2
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
 
 OS Locale:  ru
-ru_RU
-Russian (Russia)
-ISO-8859-5
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
 
 OS Locale:  ru.UTF-8
-ru_RU
-Russian (Russia)
-UTF-8
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: UTF-8
 
 OS Locale:  ru.koi8-r
-ru_RU
-Russian (Russia)
-KOI8-R
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: KOI8-R
 
 OS Locale:  ru_RU
-ru_RU
-Russian (Russia)
-ISO-8859-5
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
 
 OS Locale:  ru_RU.ANSI1251
-ru_RU
-Russian (Russia)
-windows-1251
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: windows-1251
 
 OS Locale:  ru_RU.ISO8859-5
-ru_RU
-Russian (Russia)
-ISO-8859-5
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
 
 OS Locale:  ru_RU.KOI8-R
-ru_RU
-Russian (Russia)
-KOI8-R
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: KOI8-R
 
 OS Locale:  ru_RU.UTF-8
-ru_RU
-Russian (Russia)
-UTF-8
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: UTF-8
 
 OS Locale:  sh_BA
-sr_BA
-Serbian (Bosnia and Herzegovina)
-ISO-8859-2
+default locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+display locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+format locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+default charset: ISO-8859-2
 
 OS Locale:  sh_BA.ISO8859-2@bosnia
-sr_BA
-Serbian (Bosnia and Herzegovina)
-ISO-8859-2
+default locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+display locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+format locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+default charset: ISO-8859-2
 
 OS Locale:  sk_SK
-sk_SK
-Slovak (Slovakia)
-ISO-8859-2
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
 
 OS Locale:  sk_SK.ISO8859-2
-sk_SK
-Slovak (Slovakia)
-ISO-8859-2
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
 
 OS Locale:  sl_SI
-sl_SI
-Slovenian (Slovenia)
-ISO-8859-2
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
 
 OS Locale:  sl_SI.ISO8859-2
-sl_SI
-Slovenian (Slovenia)
-ISO-8859-2
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
 
 OS Locale:  sq_AL
-sq_AL
-Albanian (Albania)
-ISO-8859-2
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: ISO-8859-2
 
 OS Locale:  sq_AL.ISO8859-2
-sq_AL
-Albanian (Albania)
-ISO-8859-2
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: ISO-8859-2
 
 OS Locale:  sr_SP
-sr_SP
-Serbian (SP)
-ISO-8859-5
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: ISO-8859-5
 
 OS Locale:  sr_YU
-sr_CS
-Serbian (Serbia and Montenegro)
-ISO-8859-5
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: ISO-8859-5
 
 OS Locale:  sr_YU.ISO8859-5
-sr_CS
-Serbian (Serbia and Montenegro)
-ISO-8859-5
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: ISO-8859-5
 
 OS Locale:  sv
-sv_SE
-Swedish (Sweden)
-ISO-8859-1
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
 
 OS Locale:  sv.ISO8859-15
-sv_SE
-Swedish (Sweden)
-ISO-8859-15
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-15
 
 OS Locale:  sv.UTF-8
-sv_SE
-Swedish (Sweden)
-UTF-8
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: UTF-8
 
 OS Locale:  sv_SE
-sv_SE
-Swedish (Sweden)
-ISO-8859-1
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
 
 OS Locale:  sv_SE.ISO8859-1
-sv_SE
-Swedish (Sweden)
-ISO-8859-1
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
 
 OS Locale:  sv_SE.ISO8859-15
-sv_SE
-Swedish (Sweden)
-ISO-8859-15
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-15
 
 OS Locale:  sv_SE.ISO8859-15@euro
-sv_SE
-Swedish (Sweden)
-ISO-8859-15
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-15
 
 OS Locale:  sv_SE.UTF-8
-sv_SE
-Swedish (Sweden)
-UTF-8
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: UTF-8
 
 OS Locale:  sv_SE.UTF-8@euro
-sv_SE
-Swedish (Sweden)
-UTF-8
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: UTF-8
 
 OS Locale:  th
-th_TH
-Thai (Thailand)
-TIS-620
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
 
 OS Locale:  th_TH
-th_TH
-Thai (Thailand)
-TIS-620
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
 
 OS Locale:  th_TH.ISO8859-11
-th_TH
-Thai (Thailand)
-TIS-620
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
 
 OS Locale:  th_TH.TIS620
-th_TH
-Thai (Thailand)
-TIS-620
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
 
 OS Locale:  th_TH.UTF-8
-th_TH
-Thai (Thailand)
-UTF-8
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: UTF-8
 
 OS Locale:  tr
-tr_TR
-Turkish (Turkey)
-ISO-8859-9
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
 
 OS Locale:  tr_TR
-tr_TR
-Turkish (Turkey)
-ISO-8859-9
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
 
 OS Locale:  tr_TR.ISO8859-9
-tr_TR
-Turkish (Turkey)
-ISO-8859-9
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
 
 OS Locale:  tr_TR.UTF-8
-tr_TR
-Turkish (Turkey)
-UTF-8
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: UTF-8
 
 OS Locale:  zh
-zh_CN
-Chinese (China)
-GB2312
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
 
 OS Locale:  zh.GBK
-zh_CN
-Chinese (China)
-GBK
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
 
 OS Locale:  zh.UTF-8
-zh_CN
-Chinese (China)
-UTF-8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
 
 OS Locale:  zh_CN.EUC
-zh_CN
-Chinese (China)
-GB2312
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
 
 OS Locale:  zh_CN.EUC@pinyin
-zh_CN
-Chinese (China)
-GB2312
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
 
 OS Locale:  zh_CN.EUC@radical
-zh_CN
-Chinese (China)
-GB2312
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
 
 OS Locale:  zh_CN.EUC@stroke
-zh_CN
-Chinese (China)
-GB2312
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
 
 OS Locale:  zh_CN.GB18030
-zh_CN
-Chinese (China)
-GB18030
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
 
 OS Locale:  zh_CN.GB18030@pinyin
-zh_CN
-Chinese (China)
-GB18030
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
 
 OS Locale:  zh_CN.GB18030@radical
-zh_CN
-Chinese (China)
-GB18030
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
 
 OS Locale:  zh_CN.GB18030@stroke
-zh_CN
-Chinese (China)
-GB18030
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
 
 OS Locale:  zh_CN.GBK
-zh_CN
-Chinese (China)
-GBK
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
 
 OS Locale:  zh_CN.GBK@pinyin
-zh_CN
-Chinese (China)
-GBK
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
 
 OS Locale:  zh_CN.GBK@radical
-zh_CN
-Chinese (China)
-GBK
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
 
 OS Locale:  zh_CN.GBK@stroke
-zh_CN
-Chinese (China)
-GBK
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
 
 OS Locale:  zh_CN.UTF-8
-zh_CN
-Chinese (China)
-UTF-8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
 
 OS Locale:  zh_CN.UTF-8@pinyin
-zh_CN
-Chinese (China)
-UTF-8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
 
 OS Locale:  zh_CN.UTF-8@radical
-zh_CN
-Chinese (China)
-UTF-8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
 
 OS Locale:  zh_CN.UTF-8@stroke
-zh_CN
-Chinese (China)
-UTF-8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
 
 OS Locale:  zh_HK.BIG5HK
-zh_HK
-Chinese (Hong Kong)
-Big5-HKSCS
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-Big5-HKSCS-2001
 
 OS Locale:  zh_HK.BIG5HK@radical
-zh_HK
-Chinese (Hong Kong)
-Big5-HKSCS
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-Big5-HKSCS-2001
 
 OS Locale:  zh_HK.BIG5HK@stroke
-zh_HK
-Chinese (Hong Kong)
-Big5-HKSCS
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-Big5-HKSCS-2001
 
 OS Locale:  zh_HK.UTF-8
-zh_HK
-Chinese (Hong Kong)
-UTF-8
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: UTF-8
 
 OS Locale:  zh_HK.UTF-8@radical
-zh_HK
-Chinese (Hong Kong)
-UTF-8
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: UTF-8
 
 OS Locale:  zh_HK.UTF-8@stroke
-zh_HK
-Chinese (Hong Kong)
-UTF-8
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: UTF-8
 
 OS Locale:  zh_TW
-zh_TW
-Chinese (Taiwan)
-x-EUC-TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
 
 OS Locale:  zh_TW.BIG5
-zh_TW
-Chinese (Taiwan)
-Big5
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
 
 OS Locale:  zh_TW.BIG5@pinyin
-zh_TW
-Chinese (Taiwan)
-Big5
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
 
 OS Locale:  zh_TW.BIG5@radical
-zh_TW
-Chinese (Taiwan)
-Big5
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
 
 OS Locale:  zh_TW.BIG5@stroke
-zh_TW
-Chinese (Taiwan)
-Big5
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
 
 OS Locale:  zh_TW.BIG5@zhuyin
-zh_TW
-Chinese (Taiwan)
-Big5
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
 
 OS Locale:  zh_TW.EUC
-zh_TW
-Chinese (Taiwan)
-x-EUC-TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
 
 OS Locale:  zh_TW.EUC@pinyin
-zh_TW
-Chinese (Taiwan)
-x-EUC-TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
 
 OS Locale:  zh_TW.EUC@radical
-zh_TW
-Chinese (Taiwan)
-x-EUC-TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
 
 OS Locale:  zh_TW.EUC@stroke
-zh_TW
-Chinese (Taiwan)
-x-EUC-TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
 
 OS Locale:  zh_TW.EUC@zhuyin
-zh_TW
-Chinese (Taiwan)
-x-EUC-TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
 
 OS Locale:  zh_TW.UTF-8
-zh_TW
-Chinese (Taiwan)
-UTF-8
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
 
 OS Locale:  zh_TW.UTF-8@pinyin
-zh_TW
-Chinese (Taiwan)
-UTF-8
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
 
 OS Locale:  zh_TW.UTF-8@radical
-zh_TW
-Chinese (Taiwan)
-UTF-8
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
 
 OS Locale:  zh_TW.UTF-8@stroke
-zh_TW
-Chinese (Taiwan)
-UTF-8
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
 
 OS Locale:  zh_TW.UTF-8@zhuyin
-zh_TW
-Chinese (Taiwan)
-UTF-8
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
+
+Testing some typical combinations
+
+
+OS Locale (LC_CTYPE: ja_JP.UTF-8, LC_MESSAGES: zh_CN.UTF-8)
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: UTF-8
+
+OS Locale (LC_CTYPE: zh_CN.UTF-8, LC_MESSAGES: en_US.UTF-8)
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale (LC_CTYPE: C, LC_MESSAGES: zh_CN.UTF-8)
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: en, Name: English
+default charset: US-ASCII
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/data/deflocale.sol10.fmtasdefault	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,1725 @@
+                         Solaris 10 3/05 s10_74L2a SPARC
+
+                      (copyright from `uname -a` goes here)
+
+SunOS deltas4 5.10 Generic_142900-03 sun4u sparc SUNW,Sun-Blade-2500
+Testing all available locales
+
+OS Locale:  C
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: US-ASCII
+
+OS Locale:  POSIX
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: US-ASCII
+
+OS Locale:  ar
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: ISO-8859-6
+
+OS Locale:  ar_EG.UTF-8
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: ar_EG, Name: Arabic (Egypt)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: UTF-8
+
+OS Locale:  ar_SA.UTF-8
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: UTF-8
+
+OS Locale:  bg_BG
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: ISO-8859-5
+
+OS Locale:  bg_BG.ISO8859-5
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: ISO-8859-5
+
+OS Locale:  ca
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  ca_ES
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  ca_ES.ISO8859-1
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  ca_ES.ISO8859-15
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  ca_ES.ISO8859-15@euro
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: ca_ES, Name: Catalan (Spain)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  cs_CZ
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  cs_CZ.ISO8859-2
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  cs_CZ.UTF-8
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: UTF-8
+
+OS Locale:  cs_CZ.UTF-8@euro
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: UTF-8
+
+OS Locale:  cz
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: cs_CZ, Name: Czech (Czech Republic)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: ISO-8859-2
+
+OS Locale:  da
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  da.ISO8859-15
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-15
+
+OS Locale:  da_DK
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  da_DK.ISO8859-1
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-1
+
+OS Locale:  da_DK.ISO8859-15
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-15
+
+OS Locale:  da_DK.ISO8859-15@euro
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: da_DK, Name: Danish (Denmark)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: ISO-8859-15
+
+OS Locale:  de
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  de.ISO8859-15
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
+
+OS Locale:  de.UTF-8
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: UTF-8
+
+OS Locale:  de_AT
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-1
+
+OS Locale:  de_AT.ISO8859-1
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-1
+
+OS Locale:  de_AT.ISO8859-15
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-15
+
+OS Locale:  de_AT.ISO8859-15@euro
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: de_AT, Name: German (Austria)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: ISO-8859-15
+
+OS Locale:  de_CH
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  de_CH.ISO8859-1
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: de_CH, Name: German (Switzerland)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  de_DE
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  de_DE.ISO8859-1
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-1
+
+OS Locale:  de_DE.ISO8859-15
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
+
+OS Locale:  de_DE.ISO8859-15@euro
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: ISO-8859-15
+
+OS Locale:  de_DE.UTF-8
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: UTF-8
+
+OS Locale:  de_DE.UTF-8@euro
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: de_DE, Name: German (Germany)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: UTF-8
+
+OS Locale:  el
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  el.sun_eu_greek
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  el_GR
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  el_GR.ISO8859-7
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  el_GR.ISO8859-7@euro
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: el_GR, Name: Greek (Greece)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: ISO-8859-7
+
+OS Locale:  en_AU
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: ISO-8859-1
+
+OS Locale:  en_AU.ISO8859-1
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: ISO-8859-1
+
+OS Locale:  en_CA
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  en_CA.ISO8859-1
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  en_CA.UTF-8
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: UTF-8
+
+OS Locale:  en_GB
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  en_GB.ISO8859-1
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-1
+
+OS Locale:  en_GB.ISO8859-15
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-15
+
+OS Locale:  en_GB.ISO8859-15@euro
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: ISO-8859-15
+
+OS Locale:  en_IE
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  en_IE.ISO8859-1
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-1
+
+OS Locale:  en_IE.ISO8859-15
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  en_IE.ISO8859-15@euro
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: ISO-8859-15
+
+OS Locale:  en_NZ
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: ISO-8859-1
+
+OS Locale:  en_NZ.ISO8859-1
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: ISO-8859-1
+
+OS Locale:  en_US
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-1
+
+OS Locale:  en_US.ISO8859-1
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-1
+
+OS Locale:  en_US.ISO8859-15
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-15
+
+OS Locale:  en_US.ISO8859-15@euro
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: ISO-8859-15
+
+OS Locale:  en_US.UTF-8
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: UTF-8
+
+OS Locale:  es
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  es.ISO8859-15
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  es.UTF-8
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: UTF-8
+
+OS Locale:  es_AR
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: ISO-8859-1
+
+OS Locale:  es_AR.ISO8859-1
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: es_AR, Name: Spanish (Argentina)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: ISO-8859-1
+
+OS Locale:  es_BO
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: ISO-8859-1
+
+OS Locale:  es_BO.ISO8859-1
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: es_BO, Name: Spanish (Bolivia)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: ISO-8859-1
+
+OS Locale:  es_CL
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: ISO-8859-1
+
+OS Locale:  es_CL.ISO8859-1
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: es_CL, Name: Spanish (Chile)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: ISO-8859-1
+
+OS Locale:  es_CO
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: ISO-8859-1
+
+OS Locale:  es_CO.ISO8859-1
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: es_CO, Name: Spanish (Colombia)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: ISO-8859-1
+
+OS Locale:  es_CR
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: ISO-8859-1
+
+OS Locale:  es_CR.ISO8859-1
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: es_CR, Name: Spanish (Costa Rica)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: ISO-8859-1
+
+OS Locale:  es_EC
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: ISO-8859-1
+
+OS Locale:  es_EC.ISO8859-1
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: es_EC, Name: Spanish (Ecuador)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: ISO-8859-1
+
+OS Locale:  es_ES
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  es_ES.ISO8859-1
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-1
+
+OS Locale:  es_ES.ISO8859-15
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  es_ES.ISO8859-15@euro
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: ISO-8859-15
+
+OS Locale:  es_ES.UTF-8
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: UTF-8
+
+OS Locale:  es_ES.UTF-8@euro
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: es_ES, Name: Spanish (Spain)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: UTF-8
+
+OS Locale:  es_GT
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: ISO-8859-1
+
+OS Locale:  es_GT.ISO8859-1
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: es_GT, Name: Spanish (Guatemala)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: ISO-8859-1
+
+OS Locale:  es_MX
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: ISO-8859-1
+
+OS Locale:  es_MX.ISO8859-1
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: ISO-8859-1
+
+OS Locale:  es_MX.UTF-8
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: es_MX, Name: Spanish (Mexico)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: UTF-8
+
+OS Locale:  es_NI
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: ISO-8859-1
+
+OS Locale:  es_NI.ISO8859-1
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: es_NI, Name: Spanish (Nicaragua)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: ISO-8859-1
+
+OS Locale:  es_PA
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: ISO-8859-1
+
+OS Locale:  es_PA.ISO8859-1
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: es_PA, Name: Spanish (Panama)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: ISO-8859-1
+
+OS Locale:  es_PE
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: ISO-8859-1
+
+OS Locale:  es_PE.ISO8859-1
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: es_PE, Name: Spanish (Peru)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: ISO-8859-1
+
+OS Locale:  es_PY
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_PY.ISO8859-1
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: es_PY, Name: Spanish (Paraguay)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_SV
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: ISO-8859-1
+
+OS Locale:  es_SV.ISO8859-1
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: es_SV, Name: Spanish (El Salvador)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: ISO-8859-1
+
+OS Locale:  es_UY
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_UY.ISO8859-1
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: es_UY, Name: Spanish (Uruguay)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: ISO-8859-1
+
+OS Locale:  es_VE
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: ISO-8859-1
+
+OS Locale:  es_VE.ISO8859-1
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: es_VE, Name: Spanish (Venezuela)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: ISO-8859-1
+
+OS Locale:  et
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-15
+
+OS Locale:  et_EE
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-15
+
+OS Locale:  et_EE.ISO8859-15
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: et_EE, Name: Estonian (Estonia)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: ISO-8859-15
+
+OS Locale:  fi
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fi.ISO8859-15
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  fi_FI
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fi_FI.ISO8859-1
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-1
+
+OS Locale:  fi_FI.ISO8859-15
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  fi_FI.ISO8859-15@euro
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: ISO-8859-15
+
+OS Locale:  fi_FI.UTF-8
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: fi_FI, Name: Finnish (Finland)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: UTF-8
+
+OS Locale:  fr
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fr.ISO8859-15
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
+
+OS Locale:  fr.UTF-8
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: UTF-8
+
+OS Locale:  fr_BE
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  fr_BE.ISO8859-1
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  fr_BE.ISO8859-15
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  fr_BE.ISO8859-15@euro
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  fr_BE.UTF-8
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: UTF-8
+
+OS Locale:  fr_BE.UTF-8@euro
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: fr_BE, Name: French (Belgium)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: UTF-8
+
+OS Locale:  fr_CA
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CA.ISO8859-1
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CA.UTF-8
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: fr_CA, Name: French (Canada)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: UTF-8
+
+OS Locale:  fr_CH
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  fr_CH.ISO8859-1
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: fr_CH, Name: French (Switzerland)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: ISO-8859-1
+
+OS Locale:  fr_FR
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fr_FR.ISO8859-1
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-1
+
+OS Locale:  fr_FR.ISO8859-15
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
+
+OS Locale:  fr_FR.ISO8859-15@euro
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: ISO-8859-15
+
+OS Locale:  fr_FR.UTF-8
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: UTF-8
+
+OS Locale:  fr_FR.UTF-8@euro
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: fr_FR, Name: French (France)
+format locale: ID: fr_FR, Name: French (France)
+default charset: UTF-8
+
+OS Locale:  he
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  he_IL
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: ISO-8859-8
+
+OS Locale:  he_IL.UTF-8
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: iw_IL, Name: Hebrew (Israel)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: UTF-8
+
+OS Locale:  hi_IN.UTF-8
+default locale: ID: hi_IN, Name: Hindi (India)
+display locale: ID: hi_IN, Name: Hindi (India)
+format locale: ID: hi_IN, Name: Hindi (India)
+default charset: UTF-8
+
+OS Locale:  hr_HR
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  hr_HR.ISO8859-2
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: hr_HR, Name: Croatian (Croatia)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: ISO-8859-2
+
+OS Locale:  hu
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hu_HU
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hu_HU.ISO8859-2
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: ISO-8859-2
+
+OS Locale:  hu_HU.UTF-8
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: hu_HU, Name: Hungarian (Hungary)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: UTF-8
+
+OS Locale:  is_IS
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
+
+OS Locale:  is_IS.ISO8859-1
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: is_IS, Name: Icelandic (Iceland)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: ISO-8859-1
+
+OS Locale:  iso_8859_1
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: US-ASCII
+
+OS Locale:  it
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  it.ISO8859-15
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  it.UTF-8
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: UTF-8
+
+OS Locale:  it_IT
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  it_IT.ISO8859-1
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-1
+
+OS Locale:  it_IT.ISO8859-15
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  it_IT.ISO8859-15@euro
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: ISO-8859-15
+
+OS Locale:  it_IT.UTF-8
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: UTF-8
+
+OS Locale:  it_IT.UTF-8@euro
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: it_IT, Name: Italian (Italy)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: UTF-8
+
+OS Locale:  ja
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-eucJP-Open
+
+OS Locale:  ja_JP.PCK
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-PCK
+
+OS Locale:  ja_JP.UTF-8
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: UTF-8
+
+OS Locale:  ja_JP.eucJP
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: x-eucJP-Open
+
+OS Locale:  ko
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
+
+OS Locale:  ko.UTF-8
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: UTF-8
+
+OS Locale:  ko_KR.EUC
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
+
+OS Locale:  ko_KR.EUC@dict
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: EUC-KR
+
+OS Locale:  ko_KR.UTF-8
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: UTF-8
+
+OS Locale:  ko_KR.UTF-8@dict
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: ko_KR, Name: Korean (South Korea)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: UTF-8
+
+OS Locale:  lt
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
+
+OS Locale:  lt_LT
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
+
+OS Locale:  lt_LT.ISO8859-13
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: ISO-8859-13
+
+OS Locale:  lv
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
+
+OS Locale:  lv_LV
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
+
+OS Locale:  lv_LV.ISO8859-13
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: lv_LV, Name: Latvian (Latvia)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: ISO-8859-13
+
+OS Locale:  mk_MK
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: ISO-8859-5
+
+OS Locale:  mk_MK.ISO8859-5
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: mk_MK, Name: Macedonian (Macedonia)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: ISO-8859-5
+
+OS Locale:  nl
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  nl.ISO8859-15
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
+
+OS Locale:  nl_BE
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  nl_BE.ISO8859-1
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-1
+
+OS Locale:  nl_BE.ISO8859-15
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  nl_BE.ISO8859-15@euro
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: nl_BE, Name: Dutch (Belgium)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: ISO-8859-15
+
+OS Locale:  nl_NL
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  nl_NL.ISO8859-1
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-1
+
+OS Locale:  nl_NL.ISO8859-15
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
+
+OS Locale:  nl_NL.ISO8859-15@euro
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: nl_NL, Name: Dutch (Netherlands)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: ISO-8859-15
+
+OS Locale:  no
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  no_NO
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  no_NO.ISO8859-1@bokmal
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: no_NO, Name: Norwegian (Norway)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: ISO-8859-1
+
+OS Locale:  no_NO.ISO8859-1@nynorsk
+default locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+display locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+format locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+default charset: ISO-8859-1
+
+OS Locale:  no_NY
+default locale: ID: no_, Name: Norwegian ()
+display locale: ID: no_, Name: Norwegian ()
+format locale: ID: no_, Name: Norwegian ()
+default charset: ISO-8859-1
+
+OS Locale:  nr
+default locale: ID: nr, Name: South Ndebele
+display locale: ID: nr, Name: South Ndebele
+format locale: ID: nr, Name: South Ndebele
+default charset: ISO-8859-2
+
+OS Locale:  pl
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  pl.UTF-8
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: UTF-8
+
+OS Locale:  pl_PL
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  pl_PL.ISO8859-2
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: ISO-8859-2
+
+OS Locale:  pl_PL.UTF-8
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: pl_PL, Name: Polish (Poland)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: UTF-8
+
+OS Locale:  pt
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt.ISO8859-15
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
+
+OS Locale:  pt_BR
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: ISO-8859-1
+
+OS Locale:  pt_BR.ISO8859-1
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: ISO-8859-1
+
+OS Locale:  pt_BR.UTF-8
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: pt_BR, Name: Portuguese (Brazil)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: UTF-8
+
+OS Locale:  pt_PT
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt_PT.ISO8859-1
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-1
+
+OS Locale:  pt_PT.ISO8859-15
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
+
+OS Locale:  pt_PT.ISO8859-15@euro
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: pt_PT, Name: Portuguese (Portugal)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: ISO-8859-15
+
+OS Locale:  ro_RO
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
+
+OS Locale:  ro_RO.ISO8859-2
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: ro_RO, Name: Romanian (Romania)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: ISO-8859-2
+
+OS Locale:  ru
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  ru.UTF-8
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: UTF-8
+
+OS Locale:  ru.koi8-r
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: KOI8-R
+
+OS Locale:  ru_RU
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  ru_RU.ANSI1251
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: windows-1251
+
+OS Locale:  ru_RU.ISO8859-5
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: ISO-8859-5
+
+OS Locale:  ru_RU.KOI8-R
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: KOI8-R
+
+OS Locale:  ru_RU.UTF-8
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: ru_RU, Name: Russian (Russia)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: UTF-8
+
+OS Locale:  sh_BA
+default locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+display locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+format locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+default charset: ISO-8859-2
+
+OS Locale:  sh_BA.ISO8859-2@bosnia
+default locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+display locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+format locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+default charset: ISO-8859-2
+
+OS Locale:  sk_SK
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
+
+OS Locale:  sk_SK.ISO8859-2
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: sk_SK, Name: Slovak (Slovakia)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: ISO-8859-2
+
+OS Locale:  sl_SI
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  sl_SI.ISO8859-2
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: sl_SI, Name: Slovenian (Slovenia)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: ISO-8859-2
+
+OS Locale:  sq_AL
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: ISO-8859-2
+
+OS Locale:  sq_AL.ISO8859-2
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: sq_AL, Name: Albanian (Albania)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: ISO-8859-2
+
+OS Locale:  sr_SP
+default locale: ID: sr, Name: Serbian
+display locale: ID: sr, Name: Serbian
+format locale: ID: sr, Name: Serbian
+default charset: ISO-8859-5
+
+OS Locale:  sr_YU
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: ISO-8859-5
+
+OS Locale:  sr_YU.ISO8859-5
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: ISO-8859-5
+
+OS Locale:  sv
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  sv.ISO8859-15
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-15
+
+OS Locale:  sv.UTF-8
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: UTF-8
+
+OS Locale:  sv_SE
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  sv_SE.ISO8859-1
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-1
+
+OS Locale:  sv_SE.ISO8859-15
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-15
+
+OS Locale:  sv_SE.ISO8859-15@euro
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: ISO-8859-15
+
+OS Locale:  sv_SE.UTF-8
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: UTF-8
+
+OS Locale:  sv_SE.UTF-8@euro
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: sv_SE, Name: Swedish (Sweden)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: UTF-8
+
+OS Locale:  th
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
+
+OS Locale:  th_TH
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
+
+OS Locale:  th_TH.ISO8859-11
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
+
+OS Locale:  th_TH.TIS620
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: TIS-620
+
+OS Locale:  th_TH.UTF-8
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: th_TH, Name: Thai (Thailand)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: UTF-8
+
+OS Locale:  tr
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  tr_TR
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  tr_TR.ISO8859-9
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: ISO-8859-9
+
+OS Locale:  tr_TR.UTF-8
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: tr_TR, Name: Turkish (Turkey)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: UTF-8
+
+OS Locale:  zh
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh.GBK
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale:  zh.UTF-8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale:  zh_CN.EUC
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh_CN.EUC@pinyin
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh_CN.EUC@radical
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh_CN.EUC@stroke
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB2312
+
+OS Locale:  zh_CN.GB18030
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
+
+OS Locale:  zh_CN.GB18030@pinyin
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
+
+OS Locale:  zh_CN.GB18030@radical
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
+
+OS Locale:  zh_CN.GB18030@stroke
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GB18030
+
+OS Locale:  zh_CN.GBK
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale:  zh_CN.GBK@pinyin
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale:  zh_CN.GBK@radical
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale:  zh_CN.GBK@stroke
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale:  zh_CN.UTF-8
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale:  zh_CN.UTF-8@pinyin
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale:  zh_CN.UTF-8@radical
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale:  zh_CN.UTF-8@stroke
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale:  zh_HK.BIG5HK
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-Big5-HKSCS-2001
+
+OS Locale:  zh_HK.BIG5HK@radical
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-Big5-HKSCS-2001
+
+OS Locale:  zh_HK.BIG5HK@stroke
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-Big5-HKSCS-2001
+
+OS Locale:  zh_HK.UTF-8
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: UTF-8
+
+OS Locale:  zh_HK.UTF-8@radical
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: UTF-8
+
+OS Locale:  zh_HK.UTF-8@stroke
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: zh_HK, Name: Chinese (Hong Kong)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: UTF-8
+
+OS Locale:  zh_TW
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
+
+OS Locale:  zh_TW.BIG5
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
+
+OS Locale:  zh_TW.BIG5@pinyin
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
+
+OS Locale:  zh_TW.BIG5@radical
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
+
+OS Locale:  zh_TW.BIG5@stroke
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
+
+OS Locale:  zh_TW.BIG5@zhuyin
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-Big5-Solaris
+
+OS Locale:  zh_TW.EUC
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
+
+OS Locale:  zh_TW.EUC@pinyin
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
+
+OS Locale:  zh_TW.EUC@radical
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
+
+OS Locale:  zh_TW.EUC@stroke
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
+
+OS Locale:  zh_TW.EUC@zhuyin
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-EUC-TW
+
+OS Locale:  zh_TW.UTF-8
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
+
+OS Locale:  zh_TW.UTF-8@pinyin
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
+
+OS Locale:  zh_TW.UTF-8@radical
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
+
+OS Locale:  zh_TW.UTF-8@stroke
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
+
+OS Locale:  zh_TW.UTF-8@zhuyin
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: zh_TW, Name: Chinese (Taiwan)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: UTF-8
+
+Testing some typical combinations
+
+
+OS Locale (LC_CTYPE: ja_JP.UTF-8, LC_MESSAGES: zh_CN.UTF-8)
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: UTF-8
+
+OS Locale (LC_CTYPE: zh_CN.UTF-8, LC_MESSAGES: en_US.UTF-8)
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: UTF-8
+
+OS Locale (LC_CTYPE: C, LC_MESSAGES: zh_CN.UTF-8)
+default locale: ID: en, Name: English
+display locale: ID: zh_CN, Name: Chinese (China)
+format locale: ID: en, Name: English
+default charset: US-ASCII
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/data/deflocale.win7	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,1494 @@
+# OSVersionInfo
+# MajorVersion: 6
+# MinorVersion: 1
+# BuildNumber: 7600
+# CSDVersion: 
+
+
+OS Locale (lcid: 7f, name: ): Invariant Language (Invariant Country) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 401, name: ar-SA): Arabic (Saudi Arabia) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: windows-1252
+
+OS Locale (lcid: 402, name: bg-BG): Bulgarian (Bulgaria) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: windows-1252
+
+OS Locale (lcid: 403, name: ca-ES): Catalan (Spain) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: windows-1252
+
+OS Locale (lcid: 404, name: zh-TW): Chinese (Traditional) (Taiwan) - 950
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: windows-1252
+
+OS Locale (lcid: 405, name: cs-CZ): Czech (Czech Republic) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: windows-1252
+
+OS Locale (lcid: 406, name: da-DK): Danish (Denmark) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: windows-1252
+
+OS Locale (lcid: 407, name: de-DE): German (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: windows-1252
+
+OS Locale (lcid: 408, name: el-GR): Greek (Greece) - 1253
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: windows-1252
+
+OS Locale (lcid: 409, name: en-US): English (United States) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 40b, name: fi-FI): Finnish (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: windows-1252
+
+OS Locale (lcid: 40c, name: fr-FR): French (France) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_FR, Name: French (France)
+default charset: windows-1252
+
+OS Locale (lcid: 40d, name: he-IL): Hebrew (Israel) - 1255
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: windows-1252
+
+OS Locale (lcid: 40e, name: hu-HU): Hungarian (Hungary) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: windows-1252
+
+OS Locale (lcid: 40f, name: is-IS): Icelandic (Iceland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: windows-1252
+
+OS Locale (lcid: 410, name: it-IT): Italian (Italy) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: windows-1252
+
+OS Locale (lcid: 411, name: ja-JP): Japanese (Japan) - 932
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: windows-1252
+
+OS Locale (lcid: 412, name: ko-KR): Korean (Korea) - 949
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: windows-1252
+
+OS Locale (lcid: 413, name: nl-NL): Dutch (Netherlands) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: windows-1252
+
+OS Locale (lcid: 414, name: nb-NO): Norwegian (Bokmål) (Norway) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: windows-1252
+
+OS Locale (lcid: 415, name: pl-PL): Polish (Poland) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: windows-1252
+
+OS Locale (lcid: 416, name: pt-BR): Portuguese (Brazil) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: windows-1252
+
+OS Locale (lcid: 417, name: rm-CH): Romansh (Switzerland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: rm_CH, Name: Raeto-Romance (Switzerland)
+default charset: windows-1252
+
+OS Locale (lcid: 418, name: ro-RO): Romanian (Romania) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: windows-1252
+
+OS Locale (lcid: 419, name: ru-RU): Russian (Russia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: windows-1252
+
+OS Locale (lcid: 41a, name: hr-HR): Croatian (Croatia) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: windows-1252
+
+OS Locale (lcid: 41b, name: sk-SK): Slovak (Slovakia) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: windows-1252
+
+OS Locale (lcid: 41c, name: sq-AL): Albanian (Albania) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: windows-1252
+
+OS Locale (lcid: 41d, name: sv-SE): Swedish (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: windows-1252
+
+OS Locale (lcid: 41e, name: th-TH): Thai (Thailand) - 874
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: windows-1252
+
+OS Locale (lcid: 41f, name: tr-TR): Turkish (Turkey) - 1254
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: windows-1252
+
+OS Locale (lcid: 420, name: ur-PK): Urdu (Islamic Republic of Pakistan) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ur_PK, Name: Urdu (Pakistan)
+default charset: windows-1252
+
+OS Locale (lcid: 421, name: id-ID): Indonesian (Indonesia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: in_ID, Name: Indonesian (Indonesia)
+default charset: windows-1252
+
+OS Locale (lcid: 422, name: uk-UA): Ukrainian (Ukraine) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+default charset: windows-1252
+
+OS Locale (lcid: 423, name: be-BY): Belarusian (Belarus) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: windows-1252
+
+OS Locale (lcid: 424, name: sl-SI): Slovenian (Slovenia) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: windows-1252
+
+OS Locale (lcid: 425, name: et-EE): Estonian (Estonia) - 1257
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: windows-1252
+
+OS Locale (lcid: 426, name: lv-LV): Latvian (Latvia) - 1257
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: windows-1252
+
+OS Locale (lcid: 427, name: lt-LT): Lithuanian (Lithuania) - 1257
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: windows-1252
+
+OS Locale (lcid: 428, name: tg-Cyrl-TJ): Tajik (Cyrillic) (Tajikistan) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: windows-1252
+
+OS Locale (lcid: 428, name: tg-Cyrl): Tajik (Cyrillic) (Tajikistan) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: windows-1252
+
+OS Locale (lcid: 429, name: fa-IR): Persian (Iran) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fa_IR, Name: Persian (Iran)
+default charset: windows-1252
+
+OS Locale (lcid: 42a, name: vi-VN): Vietnamese (Vietnam) - 1258
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+default charset: windows-1252
+
+OS Locale (lcid: 42b, name: hy-AM): Armenian (Armenia) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hy_AM, Name: Armenian (Armenia)
+default charset: windows-1252
+
+OS Locale (lcid: 42c, name: az-Latn-AZ): Azeri (Latin) (Azerbaijan) - 1254
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: windows-1252
+
+OS Locale (lcid: 42c, name: az-Latn): Azeri (Latin) (Azerbaijan) - 1254
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: windows-1252
+
+OS Locale (lcid: 42d, name: eu-ES): Basque (Spain) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: windows-1252
+
+OS Locale (lcid: 42e, name: hsb-DE): Upper Sorbian (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 42e, name: hsb): Upper Sorbian (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 42f, name: mk-MK): Macedonian (FYROM) (Macedonia (FYROM)) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: windows-1252
+
+OS Locale (lcid: 432, name: tn-ZA): Setswana (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tn_ZA, Name: Tswana (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 434, name: xh-ZA): isiXhosa (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: xh_ZA, Name: Xhosa (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 435, name: zu-ZA): isiZulu (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zu_ZA, Name: Zulu (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 436, name: af-ZA): Afrikaans (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: af_ZA, Name: Afrikaans (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 437, name: ka-GE): Georgian (Georgia) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ka_GE, Name: Georgian (Georgia)
+default charset: windows-1252
+
+OS Locale (lcid: 438, name: fo-FO): Faroese (Faroe Islands) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+default charset: windows-1252
+
+OS Locale (lcid: 439, name: hi-IN): Hindi (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hi_IN, Name: Hindi (India)
+default charset: windows-1252
+
+OS Locale (lcid: 43a, name: mt-MT): Maltese (Malta) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mt_MT, Name: Maltese (Malta)
+default charset: windows-1252
+
+OS Locale (lcid: 43b, name: se-NO): Sami (Northern) (Norway) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: se_NO, Name: Northern Sami (Norway)
+default charset: windows-1252
+
+OS Locale (lcid: 43e, name: ms-MY): Malay (Malaysia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ms_MY, Name: Malay (Malaysia)
+default charset: windows-1252
+
+OS Locale (lcid: 43f, name: kk-KZ): Kazakh (Kazakhstan) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+default charset: windows-1252
+
+OS Locale (lcid: 440, name: ky-KG): Kyrgyz (Kyrgyzstan) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+default charset: windows-1252
+
+OS Locale (lcid: 441, name: sw-KE): Kiswahili (Kenya) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sw_KE, Name: Swahili (Kenya)
+default charset: windows-1252
+
+OS Locale (lcid: 442, name: tk-TM): Turkmen (Turkmenistan) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tk_TM, Name: Turkmen (Turkmenistan)
+default charset: windows-1252
+
+OS Locale (lcid: 443, name: uz-Latn): Uzbek (Latin) (Uzbekistan) - 1254
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: windows-1252
+
+OS Locale (lcid: 443, name: uz-Latn-UZ): Uzbek (Latin) (Uzbekistan) - 1254
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: windows-1252
+
+OS Locale (lcid: 444, name: tt-RU): Tatar (Russia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tt_RU, Name: Tatar (Russia)
+default charset: windows-1252
+
+OS Locale (lcid: 445, name: bn-IN): Bengali (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bn_IN, Name: Bengali (India)
+default charset: windows-1252
+
+OS Locale (lcid: 446, name: pa-IN): Punjabi (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: pa_IN, Name: Panjabi (India)
+default charset: windows-1252
+
+OS Locale (lcid: 447, name: gu-IN): Gujarati (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: gu_IN, Name: Gujarati (India)
+default charset: windows-1252
+
+OS Locale (lcid: 448, name: or-IN): Oriya (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: or_IN, Name: Oriya (India)
+default charset: windows-1252
+
+OS Locale (lcid: 449, name: ta-IN): Tamil (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ta_IN, Name: Tamil (India)
+default charset: windows-1252
+
+OS Locale (lcid: 44a, name: te-IN): Telugu (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: te_IN, Name: Telugu (India)
+default charset: windows-1252
+
+OS Locale (lcid: 44b, name: kn-IN): Kannada (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: kn_IN, Name: Kannada (India)
+default charset: windows-1252
+
+OS Locale (lcid: 44c, name: ml-IN): Malayalam (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ml_IN, Name: Malayalam (India)
+default charset: windows-1252
+
+OS Locale (lcid: 44d, name: as-IN): Assamese (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: as_IN, Name: Assamese (India)
+default charset: windows-1252
+
+OS Locale (lcid: 44e, name: mr-IN): Marathi (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mr_IN, Name: Marathi (India)
+default charset: windows-1252
+
+OS Locale (lcid: 44f, name: sa-IN): Sanskrit (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sa_IN, Name: Sanskrit (India)
+default charset: windows-1252
+
+OS Locale (lcid: 450, name: mn-MN): Mongolian (Cyrillic) (Mongolia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mn_MN, Name: Mongolian (Mongolia)
+default charset: windows-1252
+
+OS Locale (lcid: 450, name: mn-Cyrl): Mongolian (Cyrillic) (Mongolia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mn_MN, Name: Mongolian (Mongolia)
+default charset: windows-1252
+
+OS Locale (lcid: 451, name: bo-CN): Tibetan (People's Republic of China) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bo_CN, Name: Tibetan (China)
+default charset: windows-1252
+
+OS Locale (lcid: 452, name: cy-GB): Welsh (United Kingdom) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: cy_GB, Name: Welsh (United Kingdom)
+default charset: windows-1252
+
+OS Locale (lcid: 453, name: km-KH): Khmer (Cambodia) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: km_KH, Name: Khmer (Cambodia)
+default charset: windows-1252
+
+OS Locale (lcid: 454, name: lo-LA): Lao (Lao P.D.R.) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: lo_LA, Name: Lao (Laos)
+default charset: windows-1252
+
+OS Locale (lcid: 456, name: gl-ES): Galician (Spain) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: windows-1252
+
+OS Locale (lcid: 457, name: kok-IN): Konkani (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 457, name: kok): Konkani (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 45a, name: syr): Syriac (Syria) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 45a, name: syr-SY): Syriac (Syria) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 45b, name: si-LK): Sinhala (Sri Lanka) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+default charset: windows-1252
+
+OS Locale (lcid: 45d, name: iu-Cans-CA): Inuktitut (Syllabics) (Canada) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iu_CA, Name: Inuktitut (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: 45d, name: iu-Cans): Inuktitut (Syllabics) (Canada) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iu_CA, Name: Inuktitut (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: 45e, name: am-ET): Amharic (Ethiopia) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: am_ET, Name: Amharic (Ethiopia)
+default charset: windows-1252
+
+OS Locale (lcid: 461, name: ne-NP): Nepali (Nepal) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ne_NP, Name: Nepali (Nepal)
+default charset: windows-1252
+
+OS Locale (lcid: 462, name: fy-NL): Frisian (Netherlands) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fy_NL, Name: Frisian (Netherlands)
+default charset: windows-1252
+
+OS Locale (lcid: 463, name: ps-AF): Pashto (Afghanistan) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ps_AF, Name: Pushto (Afghanistan)
+default charset: windows-1252
+
+OS Locale (lcid: 464, name: fil-PH): Filipino (Philippines) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 464, name: fil): Filipino (Philippines) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 465, name: dv-MV): Divehi (Maldives) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: dv_MV, Name: Divehi (Maldives)
+default charset: windows-1252
+
+OS Locale (lcid: 468, name: ha-Latn-NG): Hausa (Latin) (Nigeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ha_NG, Name: Hausa (Nigeria)
+default charset: windows-1252
+
+OS Locale (lcid: 468, name: ha-Latn): Hausa (Latin) (Nigeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ha_NG, Name: Hausa (Nigeria)
+default charset: windows-1252
+
+OS Locale (lcid: 46a, name: yo-NG): Yoruba (Nigeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: yo_NG, Name: Yoruba (Nigeria)
+default charset: windows-1252
+
+OS Locale (lcid: 46b, name: quz): Quechua (Bolivia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 46b, name: quz-BO): Quechua (Bolivia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 46c, name: nso): Sesotho sa Leboa (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 46c, name: nso-ZA): Sesotho sa Leboa (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 46d, name: ba-RU): Bashkir (Russia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ba_RU, Name: Bashkir (Russia)
+default charset: windows-1252
+
+OS Locale (lcid: 46e, name: lb-LU): Luxembourgish (Luxembourg) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: lb_LU, Name: Luxembourgish (Luxembourg)
+default charset: windows-1252
+
+OS Locale (lcid: 46f, name: kl-GL): Greenlandic (Greenland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: kl_GL, Name: Greenlandic (Greenland)
+default charset: windows-1252
+
+OS Locale (lcid: 470, name: ig-NG): Igbo (Nigeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ig_NG, Name: Igbo (Nigeria)
+default charset: windows-1252
+
+OS Locale (lcid: 478, name: ii-CN): Yi (People's Republic of China) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ii_CN, Name: Sichuan Yi (China)
+default charset: windows-1252
+
+OS Locale (lcid: 47a, name: arn): Mapudungun (Chile) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 47a, name: arn-CL): Mapudungun (Chile) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 47c, name: moh): Mohawk (Canada) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 47c, name: moh-CA): Mohawk (Canada) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 47e, name: br-FR): Breton (France) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: windows-1252
+
+OS Locale (lcid: 480, name: ug-CN): Uyghur (People's Republic of China) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ug_CN, Name: Uighur (China)
+default charset: windows-1252
+
+OS Locale (lcid: 481, name: mi-NZ): Maori (New Zealand) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mi_NZ, Name: Maori (New Zealand)
+default charset: windows-1252
+
+OS Locale (lcid: 482, name: oc-FR): Occitan (France) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: oc_FR, Name: Occitan (France)
+default charset: windows-1252
+
+OS Locale (lcid: 483, name: co-FR): Corsican (France) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: co_FR, Name: Corsican (France)
+default charset: windows-1252
+
+OS Locale (lcid: 484, name: gsw): Alsatian (France) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 484, name: gsw-FR): Alsatian (France) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 485, name: sah): Yakut (Russia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 485, name: sah-RU): Yakut (Russia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 486, name: qut): K'iche (Guatemala) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 486, name: qut-GT): K'iche (Guatemala) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 487, name: rw-RW): Kinyarwanda (Rwanda) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+default charset: windows-1252
+
+OS Locale (lcid: 488, name: wo-SN): Wolof (Senegal) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: wo_SN, Name: Wolof (Senegal)
+default charset: windows-1252
+
+OS Locale (lcid: 48c, name: prs): Dari (Afghanistan) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 48c, name: prs-AF): Dari (Afghanistan) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 491, name: gd-GB): Scottish Gaelic (United Kingdom) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+default charset: windows-1252
+
+OS Locale (lcid: 801, name: ar-IQ): Arabic (Iraq) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_IQ, Name: Arabic (Iraq)
+default charset: windows-1252
+
+OS Locale (lcid: 804, name: zh-Hans): Chinese (Simplified) (People's Republic of China) - 936
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: windows-1252
+
+OS Locale (lcid: 804, name: zh-CN): Chinese (Simplified) (People's Republic of China) - 936
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: windows-1252
+
+OS Locale (lcid: 807, name: de-CH): German (Switzerland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: windows-1252
+
+OS Locale (lcid: 809, name: en-GB): English (United Kingdom) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 80a, name: es-MX): Spanish (Mexico) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: windows-1252
+
+OS Locale (lcid: 80c, name: fr-BE): French (Belgium) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: windows-1252
+
+OS Locale (lcid: 810, name: it-CH): Italian (Switzerland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: it_CH, Name: Italian (Switzerland)
+default charset: windows-1252
+
+OS Locale (lcid: 813, name: nl-BE): Dutch (Belgium) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: windows-1252
+
+OS Locale (lcid: 814, name: nn-NO): Norwegian (Nynorsk) (Norway) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+default charset: windows-1252
+
+OS Locale (lcid: 816, name: pt-PT): Portuguese (Portugal) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: windows-1252
+
+OS Locale (lcid: 81a, name: sr-Latn-CS): Serbian (Latin) (Serbia and Montenegro (Former)) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: windows-1252
+
+OS Locale (lcid: 81d, name: sv-FI): Swedish (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: windows-1252
+
+OS Locale (lcid: 82c, name: az-Cyrl-AZ): Azeri (Cyrillic) (Azerbaijan) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: windows-1252
+
+OS Locale (lcid: 82c, name: az-Cyrl): Azeri (Cyrillic) (Azerbaijan) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: windows-1252
+
+OS Locale (lcid: 82e, name: dsb): Lower Sorbian (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 82e, name: dsb-DE): Lower Sorbian (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 83b, name: se-SE): Sami (Northern) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: se_SE, Name: Northern Sami (Sweden)
+default charset: windows-1252
+
+OS Locale (lcid: 83c, name: ga-IE): Irish (Ireland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: windows-1252
+
+OS Locale (lcid: 83e, name: ms-BN): Malay (Brunei Darussalam) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ms_BN, Name: Malay (Brunei)
+default charset: windows-1252
+
+OS Locale (lcid: 843, name: uz-Cyrl-UZ): Uzbek (Cyrillic) (Uzbekistan) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: windows-1252
+
+OS Locale (lcid: 843, name: uz-Cyrl): Uzbek (Cyrillic) (Uzbekistan) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: windows-1252
+
+OS Locale (lcid: 845, name: bn-BD): Bengali (Bangladesh) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bn_BD, Name: Bengali (Bangladesh)
+default charset: windows-1252
+
+OS Locale (lcid: 850, name: mn-Mong-CN): Mongolian (Traditional Mongolian) (People's Republic of China) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mn_CN, Name: Mongolian (China)
+default charset: windows-1252
+
+OS Locale (lcid: 850, name: mn-Mong): Mongolian (Traditional Mongolian) (People's Republic of China) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mn_CN, Name: Mongolian (China)
+default charset: windows-1252
+
+OS Locale (lcid: 85d, name: iu-Latn): Inuktitut (Latin) (Canada) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iu_CA, Name: Inuktitut (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: 85d, name: iu-Latn-CA): Inuktitut (Latin) (Canada) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iu_CA, Name: Inuktitut (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: 85f, name: tzm): Tamazight (Latin) (Algeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 85f, name: tzm-Latn-DZ): Tamazight (Latin) (Algeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 85f, name: tzm-Latn): Tamazight (Latin) (Algeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 86b, name: quz-EC): Quechua (Ecuador) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: c01, name: ar-EG): Arabic (Egypt) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: windows-1252
+
+OS Locale (lcid: c04, name: zh-HK): Chinese (Traditional) (Hong Kong S.A.R.) - 950
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-MS950-HKSCS
+
+OS Locale (lcid: c04, name: zh-Hant): Chinese (Traditional) (Hong Kong S.A.R.) - 950
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: windows-1252
+
+OS Locale (lcid: c07, name: de-AT): German (Austria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: windows-1252
+
+OS Locale (lcid: c09, name: en-AU): English (Australia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: c0a, name: es-ES): Spanish (Spain) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: windows-1252
+
+OS Locale (lcid: c0c, name: fr-CA): French (Canada) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: c1a, name: sr-Cyrl-CS): Serbian (Cyrillic) (Serbia and Montenegro (Former)) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: windows-1252
+
+OS Locale (lcid: c3b, name: se-FI): Sami (Northern) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: se_FI, Name: Northern Sami (Finland)
+default charset: windows-1252
+
+OS Locale (lcid: c6b, name: quz-PE): Quechua (Peru) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1001, name: ar-LY): Arabic (Libya) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_LY, Name: Arabic (Libya)
+default charset: windows-1252
+
+OS Locale (lcid: 1004, name: zh-SG): Chinese (Simplified) (Singapore) - 936
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: windows-1252
+
+OS Locale (lcid: 1007, name: de-LU): German (Luxembourg) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: windows-1252
+
+OS Locale (lcid: 1009, name: en-CA): English (Canada) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 100a, name: es-GT): Spanish (Guatemala) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: windows-1252
+
+OS Locale (lcid: 100c, name: fr-CH): French (Switzerland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: windows-1252
+
+OS Locale (lcid: 101a, name: hr-BA): Croatian (Latin) (Bosnia and Herzegovina) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hr_BA, Name: Croatian (Bosnia and Herzegovina)
+default charset: windows-1252
+
+OS Locale (lcid: 103b, name: smj-NO): Sami (Lule) (Norway) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1401, name: ar-DZ): Arabic (Algeria) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_DZ, Name: Arabic (Algeria)
+default charset: windows-1252
+
+OS Locale (lcid: 1404, name: zh-MO): Chinese (Traditional) (Macao S.A.R.) - 950
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_MO, Name: Chinese (Macao)
+default charset: windows-1252
+
+OS Locale (lcid: 1407, name: de-LI): German (Liechtenstein) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_LI, Name: German (Liechtenstein)
+default charset: windows-1252
+
+OS Locale (lcid: 1409, name: en-NZ): English (New Zealand) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 140a, name: es-CR): Spanish (Costa Rica) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: windows-1252
+
+OS Locale (lcid: 140c, name: fr-LU): French (Luxembourg) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: windows-1252
+
+OS Locale (lcid: 141a, name: bs-Latn): Bosnian (Latin) (Bosnia and Herzegovina) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: windows-1252
+
+OS Locale (lcid: 141a, name: bs-Latn-BA): Bosnian (Latin) (Bosnia and Herzegovina) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: windows-1252
+
+OS Locale (lcid: 143b, name: smj-SE): Sami (Lule) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 143b, name: smj): Sami (Lule) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1801, name: ar-MA): Arabic (Morocco) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_MA, Name: Arabic (Morocco)
+default charset: windows-1252
+
+OS Locale (lcid: 1809, name: en-IE): English (Ireland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 180a, name: es-PA): Spanish (Panama) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: windows-1252
+
+OS Locale (lcid: 180c, name: fr-MC): French (Principality of Monaco) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_MC, Name: French (Monaco)
+default charset: windows-1252
+
+OS Locale (lcid: 181a, name: sr-Latn-BA): Serbian (Latin) (Bosnia and Herzegovina) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+default charset: windows-1252
+
+OS Locale (lcid: 183b, name: sma-NO): Sami (Southern) (Norway) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1c01, name: ar-TN): Arabic (Tunisia) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_TN, Name: Arabic (Tunisia)
+default charset: windows-1252
+
+OS Locale (lcid: 1c09, name: en-ZA): English (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1c0a, name: es-DO): Spanish (Dominican Republic) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_DO, Name: Spanish (Dominican Republic)
+default charset: windows-1252
+
+OS Locale (lcid: 1c1a, name: sr-Cyrl-BA): Serbian (Cyrillic) (Bosnia and Herzegovina) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+default charset: windows-1252
+
+OS Locale (lcid: 1c3b, name: sma): Sami (Southern) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1c3b, name: sma-SE): Sami (Southern) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 2001, name: ar-OM): Arabic (Oman) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_OM, Name: Arabic (Oman)
+default charset: windows-1252
+
+OS Locale (lcid: 2009, name: en-JM): English (Jamaica) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 200a, name: es-VE): Spanish (Bolivarian Republic of Venezuela) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: windows-1252
+
+OS Locale (lcid: 201a, name: bs-Cyrl-BA): Bosnian (Cyrillic) (Bosnia and Herzegovina) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: windows-1252
+
+OS Locale (lcid: 201a, name: bs-Cyrl): Bosnian (Cyrillic) (Bosnia and Herzegovina) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: windows-1252
+
+OS Locale (lcid: 203b, name: sms-FI): Sami (Skolt) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 203b, name: sms): Sami (Skolt) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 2401, name: ar-YE): Arabic (Yemen) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_YE, Name: Arabic (Yemen)
+default charset: windows-1252
+
+OS Locale (lcid: 2409, name: en-029): English (Caribbean) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 240a, name: es-CO): Spanish (Colombia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: windows-1252
+
+OS Locale (lcid: 241a, name: sr-Latn-RS): Serbian (Latin) (Serbia) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_RS, Name: Serbian (Serbia)
+default charset: windows-1252
+
+OS Locale (lcid: 241a, name: sr-Latn): Serbian (Latin) (Serbia) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_RS, Name: Serbian (Serbia)
+default charset: windows-1252
+
+OS Locale (lcid: 243b, name: smn): Sami (Inari) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 243b, name: smn-FI): Sami (Inari) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 2801, name: ar-SY): Arabic (Syria) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_SY, Name: Arabic (Syria)
+default charset: windows-1252
+
+OS Locale (lcid: 2809, name: en-BZ): English (Belize) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 280a, name: es-PE): Spanish (Peru) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: windows-1252
+
+OS Locale (lcid: 281a, name: sr-Cyrl-RS): Serbian (Cyrillic) (Serbia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_RS, Name: Serbian (Serbia)
+default charset: windows-1252
+
+OS Locale (lcid: 281a, name: sr-Cyrl): Serbian (Cyrillic) (Serbia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_RS, Name: Serbian (Serbia)
+default charset: windows-1252
+
+OS Locale (lcid: 2c01, name: ar-JO): Arabic (Jordan) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_JO, Name: Arabic (Jordan)
+default charset: windows-1252
+
+OS Locale (lcid: 2c09, name: en-TT): English (Trinidad and Tobago) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 2c0a, name: es-AR): Spanish (Argentina) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: windows-1252
+
+OS Locale (lcid: 2c1a, name: sr-Latn-ME): Serbian (Latin) (Montenegro) - 1250
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_ME, Name: Serbian (Montenegro)
+default charset: windows-1252
+
+OS Locale (lcid: 3001, name: ar-LB): Arabic (Lebanon) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_LB, Name: Arabic (Lebanon)
+default charset: windows-1252
+
+OS Locale (lcid: 3009, name: en-ZW): English (Zimbabwe) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 300a, name: es-EC): Spanish (Ecuador) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: windows-1252
+
+OS Locale (lcid: 301a, name: sr-Cyrl-ME): Serbian (Cyrillic) (Montenegro) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_ME, Name: Serbian (Montenegro)
+default charset: windows-1252
+
+OS Locale (lcid: 3401, name: ar-KW): Arabic (Kuwait) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_KW, Name: Arabic (Kuwait)
+default charset: windows-1252
+
+OS Locale (lcid: 3409, name: en-PH): English (Republic of the Philippines) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 340a, name: es-CL): Spanish (Chile) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: windows-1252
+
+OS Locale (lcid: 3801, name: ar-AE): Arabic (U.A.E.) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+default charset: windows-1252
+
+OS Locale (lcid: 380a, name: es-UY): Spanish (Uruguay) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: windows-1252
+
+OS Locale (lcid: 3c01, name: ar-BH): Arabic (Bahrain) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_BH, Name: Arabic (Bahrain)
+default charset: windows-1252
+
+OS Locale (lcid: 3c0a, name: es-PY): Spanish (Paraguay) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: windows-1252
+
+OS Locale (lcid: 4001, name: ar-QA): Arabic (Qatar) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_QA, Name: Arabic (Qatar)
+default charset: windows-1252
+
+OS Locale (lcid: 4009, name: en-IN): English (India) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 400a, name: es-BO): Spanish (Bolivia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: windows-1252
+
+OS Locale (lcid: 4409, name: en-MY): English (Malaysia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 440a, name: es-SV): Spanish (El Salvador) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: windows-1252
+
+OS Locale (lcid: 4809, name: en-SG): English (Singapore) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 480a, name: es-HN): Spanish (Honduras) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_HN, Name: Spanish (Honduras)
+default charset: windows-1252
+
+OS Locale (lcid: 4c0a, name: es-NI): Spanish (Nicaragua) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: windows-1252
+
+OS Locale (lcid: 500a, name: es-PR): Spanish (Puerto Rico) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_PR, Name: Spanish (Puerto Rico)
+default charset: windows-1252
+
+OS Locale (lcid: 540a, name: es-US): Spanish (United States) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es, Name: Spanish
+default charset: windows-1252
+
+OS UI Language (name: en-US)
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS UI Language (name: ja-JP)
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/data/deflocale.win7.fmtasdefault	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,1494 @@
+# OSVersionInfo
+# MajorVersion: 6
+# MinorVersion: 1
+# BuildNumber: 7600
+# CSDVersion: 
+
+
+OS Locale (lcid: 7f, name: ): Invariant Language (Invariant Country) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 401, name: ar-SA): Arabic (Saudi Arabia) - 1256
+default locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_SA, Name: Arabic (Saudi Arabia)
+default charset: windows-1256
+
+OS Locale (lcid: 402, name: bg-BG): Bulgarian (Bulgaria) - 1251
+default locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bg_BG, Name: Bulgarian (Bulgaria)
+default charset: windows-1251
+
+OS Locale (lcid: 403, name: ca-ES): Catalan (Spain) - 1252
+default locale: ID: ca_ES, Name: Catalan (Spain)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ca_ES, Name: Catalan (Spain)
+default charset: windows-1252
+
+OS Locale (lcid: 404, name: zh-TW): Chinese (Traditional) (Taiwan) - 950
+default locale: ID: zh_TW, Name: Chinese (Taiwan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_TW, Name: Chinese (Taiwan)
+default charset: x-windows-950
+
+OS Locale (lcid: 405, name: cs-CZ): Czech (Czech Republic) - 1250
+default locale: ID: cs_CZ, Name: Czech (Czech Republic)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: cs_CZ, Name: Czech (Czech Republic)
+default charset: windows-1250
+
+OS Locale (lcid: 406, name: da-DK): Danish (Denmark) - 1252
+default locale: ID: da_DK, Name: Danish (Denmark)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: da_DK, Name: Danish (Denmark)
+default charset: windows-1252
+
+OS Locale (lcid: 407, name: de-DE): German (Germany) - 1252
+default locale: ID: de_DE, Name: German (Germany)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_DE, Name: German (Germany)
+default charset: windows-1252
+
+OS Locale (lcid: 408, name: el-GR): Greek (Greece) - 1253
+default locale: ID: el_GR, Name: Greek (Greece)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: el_GR, Name: Greek (Greece)
+default charset: windows-1253
+
+OS Locale (lcid: 409, name: en-US): English (United States) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 40b, name: fi-FI): Finnish (Finland) - 1252
+default locale: ID: fi_FI, Name: Finnish (Finland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fi_FI, Name: Finnish (Finland)
+default charset: windows-1252
+
+OS Locale (lcid: 40c, name: fr-FR): French (France) - 1252
+default locale: ID: fr_FR, Name: French (France)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_FR, Name: French (France)
+default charset: windows-1252
+
+OS Locale (lcid: 40d, name: he-IL): Hebrew (Israel) - 1255
+default locale: ID: iw_IL, Name: Hebrew (Israel)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iw_IL, Name: Hebrew (Israel)
+default charset: windows-1255
+
+OS Locale (lcid: 40e, name: hu-HU): Hungarian (Hungary) - 1250
+default locale: ID: hu_HU, Name: Hungarian (Hungary)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hu_HU, Name: Hungarian (Hungary)
+default charset: windows-1250
+
+OS Locale (lcid: 40f, name: is-IS): Icelandic (Iceland) - 1252
+default locale: ID: is_IS, Name: Icelandic (Iceland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: is_IS, Name: Icelandic (Iceland)
+default charset: windows-1252
+
+OS Locale (lcid: 410, name: it-IT): Italian (Italy) - 1252
+default locale: ID: it_IT, Name: Italian (Italy)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: it_IT, Name: Italian (Italy)
+default charset: windows-1252
+
+OS Locale (lcid: 411, name: ja-JP): Japanese (Japan) - 932
+default locale: ID: ja_JP, Name: Japanese (Japan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ja_JP, Name: Japanese (Japan)
+default charset: windows-31j
+
+OS Locale (lcid: 412, name: ko-KR): Korean (Korea) - 949
+default locale: ID: ko_KR, Name: Korean (South Korea)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ko_KR, Name: Korean (South Korea)
+default charset: x-windows-949
+
+OS Locale (lcid: 413, name: nl-NL): Dutch (Netherlands) - 1252
+default locale: ID: nl_NL, Name: Dutch (Netherlands)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: nl_NL, Name: Dutch (Netherlands)
+default charset: windows-1252
+
+OS Locale (lcid: 414, name: nb-NO): Norwegian (Bokmål) (Norway) - 1252
+default locale: ID: no_NO, Name: Norwegian (Norway)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: no_NO, Name: Norwegian (Norway)
+default charset: windows-1252
+
+OS Locale (lcid: 415, name: pl-PL): Polish (Poland) - 1250
+default locale: ID: pl_PL, Name: Polish (Poland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: pl_PL, Name: Polish (Poland)
+default charset: windows-1250
+
+OS Locale (lcid: 416, name: pt-BR): Portuguese (Brazil) - 1252
+default locale: ID: pt_BR, Name: Portuguese (Brazil)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: pt_BR, Name: Portuguese (Brazil)
+default charset: windows-1252
+
+OS Locale (lcid: 417, name: rm-CH): Romansh (Switzerland) - 1252
+default locale: ID: rm_CH, Name: Raeto-Romance (Switzerland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: rm_CH, Name: Raeto-Romance (Switzerland)
+default charset: windows-1252
+
+OS Locale (lcid: 418, name: ro-RO): Romanian (Romania) - 1250
+default locale: ID: ro_RO, Name: Romanian (Romania)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ro_RO, Name: Romanian (Romania)
+default charset: windows-1250
+
+OS Locale (lcid: 419, name: ru-RU): Russian (Russia) - 1251
+default locale: ID: ru_RU, Name: Russian (Russia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ru_RU, Name: Russian (Russia)
+default charset: windows-1251
+
+OS Locale (lcid: 41a, name: hr-HR): Croatian (Croatia) - 1250
+default locale: ID: hr_HR, Name: Croatian (Croatia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hr_HR, Name: Croatian (Croatia)
+default charset: windows-1250
+
+OS Locale (lcid: 41b, name: sk-SK): Slovak (Slovakia) - 1250
+default locale: ID: sk_SK, Name: Slovak (Slovakia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sk_SK, Name: Slovak (Slovakia)
+default charset: windows-1250
+
+OS Locale (lcid: 41c, name: sq-AL): Albanian (Albania) - 1250
+default locale: ID: sq_AL, Name: Albanian (Albania)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sq_AL, Name: Albanian (Albania)
+default charset: windows-1250
+
+OS Locale (lcid: 41d, name: sv-SE): Swedish (Sweden) - 1252
+default locale: ID: sv_SE, Name: Swedish (Sweden)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sv_SE, Name: Swedish (Sweden)
+default charset: windows-1252
+
+OS Locale (lcid: 41e, name: th-TH): Thai (Thailand) - 874
+default locale: ID: th_TH, Name: Thai (Thailand)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: th_TH, Name: Thai (Thailand)
+default charset: x-windows-874
+
+OS Locale (lcid: 41f, name: tr-TR): Turkish (Turkey) - 1254
+default locale: ID: tr_TR, Name: Turkish (Turkey)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tr_TR, Name: Turkish (Turkey)
+default charset: windows-1254
+
+OS Locale (lcid: 420, name: ur-PK): Urdu (Islamic Republic of Pakistan) - 1256
+default locale: ID: ur_PK, Name: Urdu (Pakistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ur_PK, Name: Urdu (Pakistan)
+default charset: windows-1256
+
+OS Locale (lcid: 421, name: id-ID): Indonesian (Indonesia) - 1252
+default locale: ID: in_ID, Name: Indonesian (Indonesia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: in_ID, Name: Indonesian (Indonesia)
+default charset: windows-1252
+
+OS Locale (lcid: 422, name: uk-UA): Ukrainian (Ukraine) - 1251
+default locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uk_UA, Name: Ukrainian (Ukraine)
+default charset: windows-1251
+
+OS Locale (lcid: 423, name: be-BY): Belarusian (Belarus) - 1251
+default locale: ID: be_BY, Name: Belarusian (Belarus)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: be_BY, Name: Belarusian (Belarus)
+default charset: windows-1251
+
+OS Locale (lcid: 424, name: sl-SI): Slovenian (Slovenia) - 1250
+default locale: ID: sl_SI, Name: Slovenian (Slovenia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sl_SI, Name: Slovenian (Slovenia)
+default charset: windows-1250
+
+OS Locale (lcid: 425, name: et-EE): Estonian (Estonia) - 1257
+default locale: ID: et_EE, Name: Estonian (Estonia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: et_EE, Name: Estonian (Estonia)
+default charset: windows-1257
+
+OS Locale (lcid: 426, name: lv-LV): Latvian (Latvia) - 1257
+default locale: ID: lv_LV, Name: Latvian (Latvia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: lv_LV, Name: Latvian (Latvia)
+default charset: windows-1257
+
+OS Locale (lcid: 427, name: lt-LT): Lithuanian (Lithuania) - 1257
+default locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: lt_LT, Name: Lithuanian (Lithuania)
+default charset: windows-1257
+
+OS Locale (lcid: 428, name: tg-Cyrl-TJ): Tajik (Cyrillic) (Tajikistan) - 1251
+default locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: windows-1251
+
+OS Locale (lcid: 428, name: tg-Cyrl): Tajik (Cyrillic) (Tajikistan) - 1251
+default locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tg_TJ, Name: Tajik (Tajikistan)
+default charset: windows-1251
+
+OS Locale (lcid: 429, name: fa-IR): Persian (Iran) - 1256
+default locale: ID: fa_IR, Name: Persian (Iran)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fa_IR, Name: Persian (Iran)
+default charset: windows-1256
+
+OS Locale (lcid: 42a, name: vi-VN): Vietnamese (Vietnam) - 1258
+default locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: vi_VN, Name: Vietnamese (Vietnam)
+default charset: windows-1258
+
+OS Locale (lcid: 42b, name: hy-AM): Armenian (Armenia) - 0
+default locale: ID: hy_AM, Name: Armenian (Armenia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hy_AM, Name: Armenian (Armenia)
+default charset: UTF-8
+
+OS Locale (lcid: 42c, name: az-Latn-AZ): Azeri (Latin) (Azerbaijan) - 1254
+default locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: windows-1254
+
+OS Locale (lcid: 42c, name: az-Latn): Azeri (Latin) (Azerbaijan) - 1254
+default locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: windows-1254
+
+OS Locale (lcid: 42d, name: eu-ES): Basque (Spain) - 1252
+default locale: ID: eu_ES, Name: Basque (Spain)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: eu_ES, Name: Basque (Spain)
+default charset: windows-1252
+
+OS Locale (lcid: 42e, name: hsb-DE): Upper Sorbian (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 42e, name: hsb): Upper Sorbian (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 42f, name: mk-MK): Macedonian (FYROM) (Macedonia (FYROM)) - 1251
+default locale: ID: mk_MK, Name: Macedonian (Macedonia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mk_MK, Name: Macedonian (Macedonia)
+default charset: windows-1251
+
+OS Locale (lcid: 432, name: tn-ZA): Setswana (South Africa) - 1252
+default locale: ID: tn_ZA, Name: Tswana (South Africa)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tn_ZA, Name: Tswana (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 434, name: xh-ZA): isiXhosa (South Africa) - 1252
+default locale: ID: xh_ZA, Name: Xhosa (South Africa)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: xh_ZA, Name: Xhosa (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 435, name: zu-ZA): isiZulu (South Africa) - 1252
+default locale: ID: zu_ZA, Name: Zulu (South Africa)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zu_ZA, Name: Zulu (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 436, name: af-ZA): Afrikaans (South Africa) - 1252
+default locale: ID: af_ZA, Name: Afrikaans (South Africa)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: af_ZA, Name: Afrikaans (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 437, name: ka-GE): Georgian (Georgia) - 0
+default locale: ID: ka_GE, Name: Georgian (Georgia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ka_GE, Name: Georgian (Georgia)
+default charset: UTF-8
+
+OS Locale (lcid: 438, name: fo-FO): Faroese (Faroe Islands) - 1252
+default locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fo_FO, Name: Faroese (Faroe Islands)
+default charset: windows-1252
+
+OS Locale (lcid: 439, name: hi-IN): Hindi (India) - 0
+default locale: ID: hi_IN, Name: Hindi (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hi_IN, Name: Hindi (India)
+default charset: UTF-8
+
+OS Locale (lcid: 43a, name: mt-MT): Maltese (Malta) - 0
+default locale: ID: mt_MT, Name: Maltese (Malta)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mt_MT, Name: Maltese (Malta)
+default charset: UTF-8
+
+OS Locale (lcid: 43b, name: se-NO): Sami (Northern) (Norway) - 1252
+default locale: ID: se_NO, Name: Northern Sami (Norway)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: se_NO, Name: Northern Sami (Norway)
+default charset: windows-1252
+
+OS Locale (lcid: 43e, name: ms-MY): Malay (Malaysia) - 1252
+default locale: ID: ms_MY, Name: Malay (Malaysia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ms_MY, Name: Malay (Malaysia)
+default charset: windows-1252
+
+OS Locale (lcid: 43f, name: kk-KZ): Kazakh (Kazakhstan) - 0
+default locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: kk_KZ, Name: Kazakh (Kazakhstan)
+default charset: UTF-8
+
+OS Locale (lcid: 440, name: ky-KG): Kyrgyz (Kyrgyzstan) - 1251
+default locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ky_KG, Name: Kirghiz (Kyrgyzstan)
+default charset: windows-1251
+
+OS Locale (lcid: 441, name: sw-KE): Kiswahili (Kenya) - 1252
+default locale: ID: sw_KE, Name: Swahili (Kenya)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sw_KE, Name: Swahili (Kenya)
+default charset: windows-1252
+
+OS Locale (lcid: 442, name: tk-TM): Turkmen (Turkmenistan) - 1250
+default locale: ID: tk_TM, Name: Turkmen (Turkmenistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tk_TM, Name: Turkmen (Turkmenistan)
+default charset: windows-1250
+
+OS Locale (lcid: 443, name: uz-Latn): Uzbek (Latin) (Uzbekistan) - 1254
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: windows-1254
+
+OS Locale (lcid: 443, name: uz-Latn-UZ): Uzbek (Latin) (Uzbekistan) - 1254
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: windows-1254
+
+OS Locale (lcid: 444, name: tt-RU): Tatar (Russia) - 1251
+default locale: ID: tt_RU, Name: Tatar (Russia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: tt_RU, Name: Tatar (Russia)
+default charset: windows-1251
+
+OS Locale (lcid: 445, name: bn-IN): Bengali (India) - 0
+default locale: ID: bn_IN, Name: Bengali (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bn_IN, Name: Bengali (India)
+default charset: UTF-8
+
+OS Locale (lcid: 446, name: pa-IN): Punjabi (India) - 0
+default locale: ID: pa_IN, Name: Panjabi (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: pa_IN, Name: Panjabi (India)
+default charset: UTF-8
+
+OS Locale (lcid: 447, name: gu-IN): Gujarati (India) - 0
+default locale: ID: gu_IN, Name: Gujarati (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: gu_IN, Name: Gujarati (India)
+default charset: UTF-8
+
+OS Locale (lcid: 448, name: or-IN): Oriya (India) - 0
+default locale: ID: or_IN, Name: Oriya (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: or_IN, Name: Oriya (India)
+default charset: UTF-8
+
+OS Locale (lcid: 449, name: ta-IN): Tamil (India) - 0
+default locale: ID: ta_IN, Name: Tamil (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ta_IN, Name: Tamil (India)
+default charset: UTF-8
+
+OS Locale (lcid: 44a, name: te-IN): Telugu (India) - 0
+default locale: ID: te_IN, Name: Telugu (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: te_IN, Name: Telugu (India)
+default charset: UTF-8
+
+OS Locale (lcid: 44b, name: kn-IN): Kannada (India) - 0
+default locale: ID: kn_IN, Name: Kannada (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: kn_IN, Name: Kannada (India)
+default charset: UTF-8
+
+OS Locale (lcid: 44c, name: ml-IN): Malayalam (India) - 0
+default locale: ID: ml_IN, Name: Malayalam (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ml_IN, Name: Malayalam (India)
+default charset: UTF-8
+
+OS Locale (lcid: 44d, name: as-IN): Assamese (India) - 0
+default locale: ID: as_IN, Name: Assamese (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: as_IN, Name: Assamese (India)
+default charset: UTF-8
+
+OS Locale (lcid: 44e, name: mr-IN): Marathi (India) - 0
+default locale: ID: mr_IN, Name: Marathi (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mr_IN, Name: Marathi (India)
+default charset: UTF-8
+
+OS Locale (lcid: 44f, name: sa-IN): Sanskrit (India) - 0
+default locale: ID: sa_IN, Name: Sanskrit (India)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sa_IN, Name: Sanskrit (India)
+default charset: UTF-8
+
+OS Locale (lcid: 450, name: mn-MN): Mongolian (Cyrillic) (Mongolia) - 1251
+default locale: ID: mn_MN, Name: Mongolian (Mongolia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mn_MN, Name: Mongolian (Mongolia)
+default charset: windows-1251
+
+OS Locale (lcid: 450, name: mn-Cyrl): Mongolian (Cyrillic) (Mongolia) - 1251
+default locale: ID: mn_MN, Name: Mongolian (Mongolia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mn_MN, Name: Mongolian (Mongolia)
+default charset: windows-1251
+
+OS Locale (lcid: 451, name: bo-CN): Tibetan (People's Republic of China) - 0
+default locale: ID: bo_CN, Name: Tibetan (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bo_CN, Name: Tibetan (China)
+default charset: UTF-8
+
+OS Locale (lcid: 452, name: cy-GB): Welsh (United Kingdom) - 1252
+default locale: ID: cy_GB, Name: Welsh (United Kingdom)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: cy_GB, Name: Welsh (United Kingdom)
+default charset: windows-1252
+
+OS Locale (lcid: 453, name: km-KH): Khmer (Cambodia) - 0
+default locale: ID: km_KH, Name: Khmer (Cambodia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: km_KH, Name: Khmer (Cambodia)
+default charset: UTF-8
+
+OS Locale (lcid: 454, name: lo-LA): Lao (Lao P.D.R.) - 0
+default locale: ID: lo_LA, Name: Lao (Laos)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: lo_LA, Name: Lao (Laos)
+default charset: UTF-8
+
+OS Locale (lcid: 456, name: gl-ES): Galician (Spain) - 1252
+default locale: ID: gl_ES, Name: Gallegan (Spain)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: gl_ES, Name: Gallegan (Spain)
+default charset: windows-1252
+
+OS Locale (lcid: 457, name: kok-IN): Konkani (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: UTF-8
+
+OS Locale (lcid: 457, name: kok): Konkani (India) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: UTF-8
+
+OS Locale (lcid: 45a, name: syr): Syriac (Syria) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: UTF-8
+
+OS Locale (lcid: 45a, name: syr-SY): Syriac (Syria) - 0
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: UTF-8
+
+OS Locale (lcid: 45b, name: si-LK): Sinhala (Sri Lanka) - 0
+default locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: si_LK, Name: Sinhalese (Sri Lanka)
+default charset: UTF-8
+
+OS Locale (lcid: 45d, name: iu-Cans-CA): Inuktitut (Syllabics) (Canada) - 0
+default locale: ID: iu_CA, Name: Inuktitut (Canada)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iu_CA, Name: Inuktitut (Canada)
+default charset: UTF-8
+
+OS Locale (lcid: 45d, name: iu-Cans): Inuktitut (Syllabics) (Canada) - 0
+default locale: ID: iu_CA, Name: Inuktitut (Canada)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iu_CA, Name: Inuktitut (Canada)
+default charset: UTF-8
+
+OS Locale (lcid: 45e, name: am-ET): Amharic (Ethiopia) - 0
+default locale: ID: am_ET, Name: Amharic (Ethiopia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: am_ET, Name: Amharic (Ethiopia)
+default charset: UTF-8
+
+OS Locale (lcid: 461, name: ne-NP): Nepali (Nepal) - 0
+default locale: ID: ne_NP, Name: Nepali (Nepal)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ne_NP, Name: Nepali (Nepal)
+default charset: UTF-8
+
+OS Locale (lcid: 462, name: fy-NL): Frisian (Netherlands) - 1252
+default locale: ID: fy_NL, Name: Frisian (Netherlands)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fy_NL, Name: Frisian (Netherlands)
+default charset: windows-1252
+
+OS Locale (lcid: 463, name: ps-AF): Pashto (Afghanistan) - 0
+default locale: ID: ps_AF, Name: Pushto (Afghanistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ps_AF, Name: Pushto (Afghanistan)
+default charset: UTF-8
+
+OS Locale (lcid: 464, name: fil-PH): Filipino (Philippines) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 464, name: fil): Filipino (Philippines) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 465, name: dv-MV): Divehi (Maldives) - 0
+default locale: ID: dv_MV, Name: Divehi (Maldives)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: dv_MV, Name: Divehi (Maldives)
+default charset: UTF-8
+
+OS Locale (lcid: 468, name: ha-Latn-NG): Hausa (Latin) (Nigeria) - 1252
+default locale: ID: ha_NG, Name: Hausa (Nigeria)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ha_NG, Name: Hausa (Nigeria)
+default charset: windows-1252
+
+OS Locale (lcid: 468, name: ha-Latn): Hausa (Latin) (Nigeria) - 1252
+default locale: ID: ha_NG, Name: Hausa (Nigeria)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ha_NG, Name: Hausa (Nigeria)
+default charset: windows-1252
+
+OS Locale (lcid: 46a, name: yo-NG): Yoruba (Nigeria) - 1252
+default locale: ID: yo_NG, Name: Yoruba (Nigeria)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: yo_NG, Name: Yoruba (Nigeria)
+default charset: windows-1252
+
+OS Locale (lcid: 46b, name: quz): Quechua (Bolivia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 46b, name: quz-BO): Quechua (Bolivia) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 46c, name: nso): Sesotho sa Leboa (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 46c, name: nso-ZA): Sesotho sa Leboa (South Africa) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 46d, name: ba-RU): Bashkir (Russia) - 1251
+default locale: ID: ba_RU, Name: Bashkir (Russia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ba_RU, Name: Bashkir (Russia)
+default charset: windows-1251
+
+OS Locale (lcid: 46e, name: lb-LU): Luxembourgish (Luxembourg) - 1252
+default locale: ID: lb_LU, Name: Luxembourgish (Luxembourg)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: lb_LU, Name: Luxembourgish (Luxembourg)
+default charset: windows-1252
+
+OS Locale (lcid: 46f, name: kl-GL): Greenlandic (Greenland) - 1252
+default locale: ID: kl_GL, Name: Greenlandic (Greenland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: kl_GL, Name: Greenlandic (Greenland)
+default charset: windows-1252
+
+OS Locale (lcid: 470, name: ig-NG): Igbo (Nigeria) - 1252
+default locale: ID: ig_NG, Name: Igbo (Nigeria)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ig_NG, Name: Igbo (Nigeria)
+default charset: windows-1252
+
+OS Locale (lcid: 478, name: ii-CN): Yi (People's Republic of China) - 0
+default locale: ID: ii_CN, Name: Sichuan Yi (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ii_CN, Name: Sichuan Yi (China)
+default charset: UTF-8
+
+OS Locale (lcid: 47a, name: arn): Mapudungun (Chile) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 47a, name: arn-CL): Mapudungun (Chile) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 47c, name: moh): Mohawk (Canada) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 47c, name: moh-CA): Mohawk (Canada) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 47e, name: br-FR): Breton (France) - 1252
+default locale: ID: br_FR, Name: Breton (France)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: br_FR, Name: Breton (France)
+default charset: windows-1252
+
+OS Locale (lcid: 480, name: ug-CN): Uyghur (People's Republic of China) - 1256
+default locale: ID: ug_CN, Name: Uighur (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ug_CN, Name: Uighur (China)
+default charset: windows-1256
+
+OS Locale (lcid: 481, name: mi-NZ): Maori (New Zealand) - 0
+default locale: ID: mi_NZ, Name: Maori (New Zealand)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mi_NZ, Name: Maori (New Zealand)
+default charset: UTF-8
+
+OS Locale (lcid: 482, name: oc-FR): Occitan (France) - 1252
+default locale: ID: oc_FR, Name: Occitan (France)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: oc_FR, Name: Occitan (France)
+default charset: windows-1252
+
+OS Locale (lcid: 483, name: co-FR): Corsican (France) - 1252
+default locale: ID: co_FR, Name: Corsican (France)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: co_FR, Name: Corsican (France)
+default charset: windows-1252
+
+OS Locale (lcid: 484, name: gsw): Alsatian (France) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 484, name: gsw-FR): Alsatian (France) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 485, name: sah): Yakut (Russia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1251
+
+OS Locale (lcid: 485, name: sah-RU): Yakut (Russia) - 1251
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1251
+
+OS Locale (lcid: 486, name: qut): K'iche (Guatemala) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 486, name: qut-GT): K'iche (Guatemala) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 487, name: rw-RW): Kinyarwanda (Rwanda) - 1252
+default locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: rw_RW, Name: Kinyarwanda (Rwanda)
+default charset: windows-1252
+
+OS Locale (lcid: 488, name: wo-SN): Wolof (Senegal) - 1252
+default locale: ID: wo_SN, Name: Wolof (Senegal)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: wo_SN, Name: Wolof (Senegal)
+default charset: windows-1252
+
+OS Locale (lcid: 48c, name: prs): Dari (Afghanistan) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1256
+
+OS Locale (lcid: 48c, name: prs-AF): Dari (Afghanistan) - 1256
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1256
+
+OS Locale (lcid: 491, name: gd-GB): Scottish Gaelic (United Kingdom) - 1252
+default locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: gd_GB, Name: Scottish Gaelic (United Kingdom)
+default charset: windows-1252
+
+OS Locale (lcid: 801, name: ar-IQ): Arabic (Iraq) - 1256
+default locale: ID: ar_IQ, Name: Arabic (Iraq)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_IQ, Name: Arabic (Iraq)
+default charset: windows-1256
+
+OS Locale (lcid: 804, name: zh-Hans): Chinese (Simplified) (People's Republic of China) - 936
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale (lcid: 804, name: zh-CN): Chinese (Simplified) (People's Republic of China) - 936
+default locale: ID: zh_CN, Name: Chinese (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_CN, Name: Chinese (China)
+default charset: GBK
+
+OS Locale (lcid: 807, name: de-CH): German (Switzerland) - 1252
+default locale: ID: de_CH, Name: German (Switzerland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_CH, Name: German (Switzerland)
+default charset: windows-1252
+
+OS Locale (lcid: 809, name: en-GB): English (United Kingdom) - 1252
+default locale: ID: en_GB, Name: English (United Kingdom)
+display locale: ID: en_GB, Name: English (United Kingdom)
+format locale: ID: en_GB, Name: English (United Kingdom)
+default charset: windows-1252
+
+OS Locale (lcid: 80a, name: es-MX): Spanish (Mexico) - 1252
+default locale: ID: es_MX, Name: Spanish (Mexico)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_MX, Name: Spanish (Mexico)
+default charset: windows-1252
+
+OS Locale (lcid: 80c, name: fr-BE): French (Belgium) - 1252
+default locale: ID: fr_BE, Name: French (Belgium)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_BE, Name: French (Belgium)
+default charset: windows-1252
+
+OS Locale (lcid: 810, name: it-CH): Italian (Switzerland) - 1252
+default locale: ID: it_CH, Name: Italian (Switzerland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: it_CH, Name: Italian (Switzerland)
+default charset: windows-1252
+
+OS Locale (lcid: 813, name: nl-BE): Dutch (Belgium) - 1252
+default locale: ID: nl_BE, Name: Dutch (Belgium)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: nl_BE, Name: Dutch (Belgium)
+default charset: windows-1252
+
+OS Locale (lcid: 814, name: nn-NO): Norwegian (Nynorsk) (Norway) - 1252
+default locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: no_NO_NY, Name: Norwegian (Norway,Nynorsk)
+default charset: windows-1252
+
+OS Locale (lcid: 816, name: pt-PT): Portuguese (Portugal) - 1252
+default locale: ID: pt_PT, Name: Portuguese (Portugal)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: pt_PT, Name: Portuguese (Portugal)
+default charset: windows-1252
+
+OS Locale (lcid: 81a, name: sr-Latn-CS): Serbian (Latin) (Serbia and Montenegro (Former)) - 1250
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: windows-1250
+
+OS Locale (lcid: 81d, name: sv-FI): Swedish (Finland) - 1252
+default locale: ID: sv_FI, Name: Swedish (Finland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sv_FI, Name: Swedish (Finland)
+default charset: windows-1252
+
+OS Locale (lcid: 82c, name: az-Cyrl-AZ): Azeri (Cyrillic) (Azerbaijan) - 1251
+default locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: windows-1251
+
+OS Locale (lcid: 82c, name: az-Cyrl): Azeri (Cyrillic) (Azerbaijan) - 1251
+default locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: az_AZ, Name: Azerbaijani (Azerbaijan)
+default charset: windows-1251
+
+OS Locale (lcid: 82e, name: dsb): Lower Sorbian (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 82e, name: dsb-DE): Lower Sorbian (Germany) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 83b, name: se-SE): Sami (Northern) (Sweden) - 1252
+default locale: ID: se_SE, Name: Northern Sami (Sweden)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: se_SE, Name: Northern Sami (Sweden)
+default charset: windows-1252
+
+OS Locale (lcid: 83c, name: ga-IE): Irish (Ireland) - 1252
+default locale: ID: ga_IE, Name: Irish (Ireland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ga_IE, Name: Irish (Ireland)
+default charset: windows-1252
+
+OS Locale (lcid: 83e, name: ms-BN): Malay (Brunei Darussalam) - 1252
+default locale: ID: ms_BN, Name: Malay (Brunei)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ms_BN, Name: Malay (Brunei)
+default charset: windows-1252
+
+OS Locale (lcid: 843, name: uz-Cyrl-UZ): Uzbek (Cyrillic) (Uzbekistan) - 1251
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: windows-1251
+
+OS Locale (lcid: 843, name: uz-Cyrl): Uzbek (Cyrillic) (Uzbekistan) - 1251
+default locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: uz_UZ, Name: Uzbek (Uzbekistan)
+default charset: windows-1251
+
+OS Locale (lcid: 845, name: bn-BD): Bengali (Bangladesh) - 0
+default locale: ID: bn_BD, Name: Bengali (Bangladesh)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bn_BD, Name: Bengali (Bangladesh)
+default charset: UTF-8
+
+OS Locale (lcid: 850, name: mn-Mong-CN): Mongolian (Traditional Mongolian) (People's Republic of China) - 0
+default locale: ID: mn_CN, Name: Mongolian (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mn_CN, Name: Mongolian (China)
+default charset: UTF-8
+
+OS Locale (lcid: 850, name: mn-Mong): Mongolian (Traditional Mongolian) (People's Republic of China) - 0
+default locale: ID: mn_CN, Name: Mongolian (China)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: mn_CN, Name: Mongolian (China)
+default charset: UTF-8
+
+OS Locale (lcid: 85d, name: iu-Latn): Inuktitut (Latin) (Canada) - 1252
+default locale: ID: iu_CA, Name: Inuktitut (Canada)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iu_CA, Name: Inuktitut (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: 85d, name: iu-Latn-CA): Inuktitut (Latin) (Canada) - 1252
+default locale: ID: iu_CA, Name: Inuktitut (Canada)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: iu_CA, Name: Inuktitut (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: 85f, name: tzm): Tamazight (Latin) (Algeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 85f, name: tzm-Latn-DZ): Tamazight (Latin) (Algeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 85f, name: tzm-Latn): Tamazight (Latin) (Algeria) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 86b, name: quz-EC): Quechua (Ecuador) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: c01, name: ar-EG): Arabic (Egypt) - 1256
+default locale: ID: ar_EG, Name: Arabic (Egypt)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_EG, Name: Arabic (Egypt)
+default charset: windows-1256
+
+OS Locale (lcid: c04, name: zh-HK): Chinese (Traditional) (Hong Kong S.A.R.) - 950
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-MS950-HKSCS
+
+OS Locale (lcid: c04, name: zh-Hant): Chinese (Traditional) (Hong Kong S.A.R.) - 950
+default locale: ID: zh_HK, Name: Chinese (Hong Kong)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_HK, Name: Chinese (Hong Kong)
+default charset: x-windows-950
+
+OS Locale (lcid: c07, name: de-AT): German (Austria) - 1252
+default locale: ID: de_AT, Name: German (Austria)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_AT, Name: German (Austria)
+default charset: windows-1252
+
+OS Locale (lcid: c09, name: en-AU): English (Australia) - 1252
+default locale: ID: en_AU, Name: English (Australia)
+display locale: ID: en_AU, Name: English (Australia)
+format locale: ID: en_AU, Name: English (Australia)
+default charset: windows-1252
+
+OS Locale (lcid: c0a, name: es-ES): Spanish (Spain) - 1252
+default locale: ID: es_ES, Name: Spanish (Spain)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_ES, Name: Spanish (Spain)
+default charset: windows-1252
+
+OS Locale (lcid: c0c, name: fr-CA): French (Canada) - 1252
+default locale: ID: fr_CA, Name: French (Canada)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_CA, Name: French (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: c1a, name: sr-Cyrl-CS): Serbian (Cyrillic) (Serbia and Montenegro (Former)) - 1251
+default locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_CS, Name: Serbian (Serbia and Montenegro)
+default charset: windows-1251
+
+OS Locale (lcid: c3b, name: se-FI): Sami (Northern) (Finland) - 1252
+default locale: ID: se_FI, Name: Northern Sami (Finland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: se_FI, Name: Northern Sami (Finland)
+default charset: windows-1252
+
+OS Locale (lcid: c6b, name: quz-PE): Quechua (Peru) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1001, name: ar-LY): Arabic (Libya) - 1256
+default locale: ID: ar_LY, Name: Arabic (Libya)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_LY, Name: Arabic (Libya)
+default charset: windows-1256
+
+OS Locale (lcid: 1004, name: zh-SG): Chinese (Simplified) (Singapore) - 936
+default locale: ID: zh_SG, Name: Chinese (Singapore)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_SG, Name: Chinese (Singapore)
+default charset: GBK
+
+OS Locale (lcid: 1007, name: de-LU): German (Luxembourg) - 1252
+default locale: ID: de_LU, Name: German (Luxembourg)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_LU, Name: German (Luxembourg)
+default charset: windows-1252
+
+OS Locale (lcid: 1009, name: en-CA): English (Canada) - 1252
+default locale: ID: en_CA, Name: English (Canada)
+display locale: ID: en_CA, Name: English (Canada)
+format locale: ID: en_CA, Name: English (Canada)
+default charset: windows-1252
+
+OS Locale (lcid: 100a, name: es-GT): Spanish (Guatemala) - 1252
+default locale: ID: es_GT, Name: Spanish (Guatemala)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_GT, Name: Spanish (Guatemala)
+default charset: windows-1252
+
+OS Locale (lcid: 100c, name: fr-CH): French (Switzerland) - 1252
+default locale: ID: fr_CH, Name: French (Switzerland)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_CH, Name: French (Switzerland)
+default charset: windows-1252
+
+OS Locale (lcid: 101a, name: hr-BA): Croatian (Latin) (Bosnia and Herzegovina) - 1250
+default locale: ID: hr_BA, Name: Croatian (Bosnia and Herzegovina)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: hr_BA, Name: Croatian (Bosnia and Herzegovina)
+default charset: windows-1250
+
+OS Locale (lcid: 103b, name: smj-NO): Sami (Lule) (Norway) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1401, name: ar-DZ): Arabic (Algeria) - 1256
+default locale: ID: ar_DZ, Name: Arabic (Algeria)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_DZ, Name: Arabic (Algeria)
+default charset: windows-1256
+
+OS Locale (lcid: 1404, name: zh-MO): Chinese (Traditional) (Macao S.A.R.) - 950
+default locale: ID: zh_MO, Name: Chinese (Macao)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: zh_MO, Name: Chinese (Macao)
+default charset: x-windows-950
+
+OS Locale (lcid: 1407, name: de-LI): German (Liechtenstein) - 1252
+default locale: ID: de_LI, Name: German (Liechtenstein)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: de_LI, Name: German (Liechtenstein)
+default charset: windows-1252
+
+OS Locale (lcid: 1409, name: en-NZ): English (New Zealand) - 1252
+default locale: ID: en_NZ, Name: English (New Zealand)
+display locale: ID: en_NZ, Name: English (New Zealand)
+format locale: ID: en_NZ, Name: English (New Zealand)
+default charset: windows-1252
+
+OS Locale (lcid: 140a, name: es-CR): Spanish (Costa Rica) - 1252
+default locale: ID: es_CR, Name: Spanish (Costa Rica)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_CR, Name: Spanish (Costa Rica)
+default charset: windows-1252
+
+OS Locale (lcid: 140c, name: fr-LU): French (Luxembourg) - 1252
+default locale: ID: fr_LU, Name: French (Luxembourg)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_LU, Name: French (Luxembourg)
+default charset: windows-1252
+
+OS Locale (lcid: 141a, name: bs-Latn): Bosnian (Latin) (Bosnia and Herzegovina) - 1250
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: windows-1250
+
+OS Locale (lcid: 141a, name: bs-Latn-BA): Bosnian (Latin) (Bosnia and Herzegovina) - 1250
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: windows-1250
+
+OS Locale (lcid: 143b, name: smj-SE): Sami (Lule) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 143b, name: smj): Sami (Lule) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1801, name: ar-MA): Arabic (Morocco) - 1256
+default locale: ID: ar_MA, Name: Arabic (Morocco)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_MA, Name: Arabic (Morocco)
+default charset: windows-1256
+
+OS Locale (lcid: 1809, name: en-IE): English (Ireland) - 1252
+default locale: ID: en_IE, Name: English (Ireland)
+display locale: ID: en_IE, Name: English (Ireland)
+format locale: ID: en_IE, Name: English (Ireland)
+default charset: windows-1252
+
+OS Locale (lcid: 180a, name: es-PA): Spanish (Panama) - 1252
+default locale: ID: es_PA, Name: Spanish (Panama)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_PA, Name: Spanish (Panama)
+default charset: windows-1252
+
+OS Locale (lcid: 180c, name: fr-MC): French (Principality of Monaco) - 1252
+default locale: ID: fr_MC, Name: French (Monaco)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: fr_MC, Name: French (Monaco)
+default charset: windows-1252
+
+OS Locale (lcid: 181a, name: sr-Latn-BA): Serbian (Latin) (Bosnia and Herzegovina) - 1250
+default locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+default charset: windows-1250
+
+OS Locale (lcid: 183b, name: sma-NO): Sami (Southern) (Norway) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1c01, name: ar-TN): Arabic (Tunisia) - 1256
+default locale: ID: ar_TN, Name: Arabic (Tunisia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_TN, Name: Arabic (Tunisia)
+default charset: windows-1256
+
+OS Locale (lcid: 1c09, name: en-ZA): English (South Africa) - 1252
+default locale: ID: en_ZA, Name: English (South Africa)
+display locale: ID: en_ZA, Name: English (South Africa)
+format locale: ID: en_ZA, Name: English (South Africa)
+default charset: windows-1252
+
+OS Locale (lcid: 1c0a, name: es-DO): Spanish (Dominican Republic) - 1252
+default locale: ID: es_DO, Name: Spanish (Dominican Republic)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_DO, Name: Spanish (Dominican Republic)
+default charset: windows-1252
+
+OS Locale (lcid: 1c1a, name: sr-Cyrl-BA): Serbian (Cyrillic) (Bosnia and Herzegovina) - 1251
+default locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_BA, Name: Serbian (Bosnia and Herzegovina)
+default charset: windows-1251
+
+OS Locale (lcid: 1c3b, name: sma): Sami (Southern) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 1c3b, name: sma-SE): Sami (Southern) (Sweden) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 2001, name: ar-OM): Arabic (Oman) - 1256
+default locale: ID: ar_OM, Name: Arabic (Oman)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_OM, Name: Arabic (Oman)
+default charset: windows-1256
+
+OS Locale (lcid: 2009, name: en-JM): English (Jamaica) - 1252
+default locale: ID: en_JM, Name: English (Jamaica)
+display locale: ID: en_JM, Name: English (Jamaica)
+format locale: ID: en_JM, Name: English (Jamaica)
+default charset: windows-1252
+
+OS Locale (lcid: 200a, name: es-VE): Spanish (Bolivarian Republic of Venezuela) - 1252
+default locale: ID: es_VE, Name: Spanish (Venezuela)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_VE, Name: Spanish (Venezuela)
+default charset: windows-1252
+
+OS Locale (lcid: 201a, name: bs-Cyrl-BA): Bosnian (Cyrillic) (Bosnia and Herzegovina) - 1251
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: windows-1251
+
+OS Locale (lcid: 201a, name: bs-Cyrl): Bosnian (Cyrillic) (Bosnia and Herzegovina) - 1251
+default locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: bs_BA, Name: Bosnian (Bosnia and Herzegovina)
+default charset: windows-1251
+
+OS Locale (lcid: 203b, name: sms-FI): Sami (Skolt) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 203b, name: sms): Sami (Skolt) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 2401, name: ar-YE): Arabic (Yemen) - 1256
+default locale: ID: ar_YE, Name: Arabic (Yemen)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_YE, Name: Arabic (Yemen)
+default charset: windows-1256
+
+OS Locale (lcid: 2409, name: en-029): English (Caribbean) - 1252
+default locale: ID: en, Name: English
+display locale: ID: en, Name: English
+format locale: ID: en, Name: English
+default charset: windows-1252
+
+OS Locale (lcid: 240a, name: es-CO): Spanish (Colombia) - 1252
+default locale: ID: es_CO, Name: Spanish (Colombia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_CO, Name: Spanish (Colombia)
+default charset: windows-1252
+
+OS Locale (lcid: 241a, name: sr-Latn-RS): Serbian (Latin) (Serbia) - 1250
+default locale: ID: sr_RS, Name: Serbian (Serbia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_RS, Name: Serbian (Serbia)
+default charset: windows-1250
+
+OS Locale (lcid: 241a, name: sr-Latn): Serbian (Latin) (Serbia) - 1250
+default locale: ID: sr_RS, Name: Serbian (Serbia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_RS, Name: Serbian (Serbia)
+default charset: windows-1250
+
+OS Locale (lcid: 243b, name: smn): Sami (Inari) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 243b, name: smn-FI): Sami (Inari) (Finland) - 1252
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS Locale (lcid: 2801, name: ar-SY): Arabic (Syria) - 1256
+default locale: ID: ar_SY, Name: Arabic (Syria)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_SY, Name: Arabic (Syria)
+default charset: windows-1256
+
+OS Locale (lcid: 2809, name: en-BZ): English (Belize) - 1252
+default locale: ID: en_BZ, Name: English (Belize)
+display locale: ID: en_BZ, Name: English (Belize)
+format locale: ID: en_BZ, Name: English (Belize)
+default charset: windows-1252
+
+OS Locale (lcid: 280a, name: es-PE): Spanish (Peru) - 1252
+default locale: ID: es_PE, Name: Spanish (Peru)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_PE, Name: Spanish (Peru)
+default charset: windows-1252
+
+OS Locale (lcid: 281a, name: sr-Cyrl-RS): Serbian (Cyrillic) (Serbia) - 1251
+default locale: ID: sr_RS, Name: Serbian (Serbia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_RS, Name: Serbian (Serbia)
+default charset: windows-1251
+
+OS Locale (lcid: 281a, name: sr-Cyrl): Serbian (Cyrillic) (Serbia) - 1251
+default locale: ID: sr_RS, Name: Serbian (Serbia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_RS, Name: Serbian (Serbia)
+default charset: windows-1251
+
+OS Locale (lcid: 2c01, name: ar-JO): Arabic (Jordan) - 1256
+default locale: ID: ar_JO, Name: Arabic (Jordan)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_JO, Name: Arabic (Jordan)
+default charset: windows-1256
+
+OS Locale (lcid: 2c09, name: en-TT): English (Trinidad and Tobago) - 1252
+default locale: ID: en_TT, Name: English (Trinidad and Tobago)
+display locale: ID: en_TT, Name: English (Trinidad and Tobago)
+format locale: ID: en_TT, Name: English (Trinidad and Tobago)
+default charset: windows-1252
+
+OS Locale (lcid: 2c0a, name: es-AR): Spanish (Argentina) - 1252
+default locale: ID: es_AR, Name: Spanish (Argentina)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_AR, Name: Spanish (Argentina)
+default charset: windows-1252
+
+OS Locale (lcid: 2c1a, name: sr-Latn-ME): Serbian (Latin) (Montenegro) - 1250
+default locale: ID: sr_ME, Name: Serbian (Montenegro)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_ME, Name: Serbian (Montenegro)
+default charset: windows-1250
+
+OS Locale (lcid: 3001, name: ar-LB): Arabic (Lebanon) - 1256
+default locale: ID: ar_LB, Name: Arabic (Lebanon)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_LB, Name: Arabic (Lebanon)
+default charset: windows-1256
+
+OS Locale (lcid: 3009, name: en-ZW): English (Zimbabwe) - 1252
+default locale: ID: en_ZW, Name: English (Zimbabwe)
+display locale: ID: en_ZW, Name: English (Zimbabwe)
+format locale: ID: en_ZW, Name: English (Zimbabwe)
+default charset: windows-1252
+
+OS Locale (lcid: 300a, name: es-EC): Spanish (Ecuador) - 1252
+default locale: ID: es_EC, Name: Spanish (Ecuador)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_EC, Name: Spanish (Ecuador)
+default charset: windows-1252
+
+OS Locale (lcid: 301a, name: sr-Cyrl-ME): Serbian (Cyrillic) (Montenegro) - 1251
+default locale: ID: sr_ME, Name: Serbian (Montenegro)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: sr_ME, Name: Serbian (Montenegro)
+default charset: windows-1251
+
+OS Locale (lcid: 3401, name: ar-KW): Arabic (Kuwait) - 1256
+default locale: ID: ar_KW, Name: Arabic (Kuwait)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_KW, Name: Arabic (Kuwait)
+default charset: windows-1256
+
+OS Locale (lcid: 3409, name: en-PH): English (Republic of the Philippines) - 1252
+default locale: ID: en_PH, Name: English (Philippines)
+display locale: ID: en_PH, Name: English (Philippines)
+format locale: ID: en_PH, Name: English (Philippines)
+default charset: windows-1252
+
+OS Locale (lcid: 340a, name: es-CL): Spanish (Chile) - 1252
+default locale: ID: es_CL, Name: Spanish (Chile)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_CL, Name: Spanish (Chile)
+default charset: windows-1252
+
+OS Locale (lcid: 3801, name: ar-AE): Arabic (U.A.E.) - 1256
+default locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_AE, Name: Arabic (United Arab Emirates)
+default charset: windows-1256
+
+OS Locale (lcid: 380a, name: es-UY): Spanish (Uruguay) - 1252
+default locale: ID: es_UY, Name: Spanish (Uruguay)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_UY, Name: Spanish (Uruguay)
+default charset: windows-1252
+
+OS Locale (lcid: 3c01, name: ar-BH): Arabic (Bahrain) - 1256
+default locale: ID: ar_BH, Name: Arabic (Bahrain)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_BH, Name: Arabic (Bahrain)
+default charset: windows-1256
+
+OS Locale (lcid: 3c0a, name: es-PY): Spanish (Paraguay) - 1252
+default locale: ID: es_PY, Name: Spanish (Paraguay)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_PY, Name: Spanish (Paraguay)
+default charset: windows-1252
+
+OS Locale (lcid: 4001, name: ar-QA): Arabic (Qatar) - 1256
+default locale: ID: ar_QA, Name: Arabic (Qatar)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: ar_QA, Name: Arabic (Qatar)
+default charset: windows-1256
+
+OS Locale (lcid: 4009, name: en-IN): English (India) - 1252
+default locale: ID: en_IN, Name: English (India)
+display locale: ID: en_IN, Name: English (India)
+format locale: ID: en_IN, Name: English (India)
+default charset: windows-1252
+
+OS Locale (lcid: 400a, name: es-BO): Spanish (Bolivia) - 1252
+default locale: ID: es_BO, Name: Spanish (Bolivia)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_BO, Name: Spanish (Bolivia)
+default charset: windows-1252
+
+OS Locale (lcid: 4409, name: en-MY): English (Malaysia) - 1252
+default locale: ID: en_MY, Name: English (Malaysia)
+display locale: ID: en_MY, Name: English (Malaysia)
+format locale: ID: en_MY, Name: English (Malaysia)
+default charset: windows-1252
+
+OS Locale (lcid: 440a, name: es-SV): Spanish (El Salvador) - 1252
+default locale: ID: es_SV, Name: Spanish (El Salvador)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_SV, Name: Spanish (El Salvador)
+default charset: windows-1252
+
+OS Locale (lcid: 4809, name: en-SG): English (Singapore) - 1252
+default locale: ID: en_SG, Name: English (Singapore)
+display locale: ID: en_SG, Name: English (Singapore)
+format locale: ID: en_SG, Name: English (Singapore)
+default charset: windows-1252
+
+OS Locale (lcid: 480a, name: es-HN): Spanish (Honduras) - 1252
+default locale: ID: es_HN, Name: Spanish (Honduras)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_HN, Name: Spanish (Honduras)
+default charset: windows-1252
+
+OS Locale (lcid: 4c0a, name: es-NI): Spanish (Nicaragua) - 1252
+default locale: ID: es_NI, Name: Spanish (Nicaragua)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_NI, Name: Spanish (Nicaragua)
+default charset: windows-1252
+
+OS Locale (lcid: 500a, name: es-PR): Spanish (Puerto Rico) - 1252
+default locale: ID: es_PR, Name: Spanish (Puerto Rico)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: es_PR, Name: Spanish (Puerto Rico)
+default charset: windows-1252
+
+OS Locale (lcid: 540a, name: es-US): Spanish (United States) - 1252
+default locale: ID: es_US, Name: Spanish (United States)
+display locale: ID: en, Name: English
+format locale: ID: es_US, Name: Spanish (United States)
+default charset: windows-1252
+
+OS UI Language (name: en-US)
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: en_US, Name: English (United States)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
+
+OS UI Language (name: ja-JP)
+default locale: ID: en_US, Name: English (United States)
+display locale: ID: ja_JP, Name: Japanese (Japan)
+format locale: ID: en_US, Name: English (United States)
+default charset: windows-1252
--- a/test/java/util/Locale/data/deflocale.winvista	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1031 +0,0 @@
-# OSVersionInfo
-# MajorVersion: 6
-# MinorVersion: 0
-# BuildNumber: 5456
-# CSDVersion: Service Pack 0 v. 
-
-
-OS Locale (lcid: 401): Arabic (Saudi Arabia) - 1256
-ar_SA
-Arabic (Saudi Arabia)
-windows-1256
-
-OS Locale (lcid: 402): Bulgarian (Bulgaria) - 1251
-bg_BG
-Bulgarian (Bulgaria)
-windows-1251
-
-OS Locale (lcid: 403): Catalan (Spain) - 1252
-ca_ES
-Catalan (Spain)
-windows-1252
-
-OS Locale (lcid: 404): Chinese (Taiwan) - 950
-zh_TW
-Chinese (Taiwan)
-x-windows-950
-
-OS Locale (lcid: 405): Czech (Czech Republic) - 1250
-cs_CZ
-Czech (Czech Republic)
-windows-1250
-
-OS Locale (lcid: 406): Danish (Denmark) - 1252
-da_DK
-Danish (Denmark)
-windows-1252
-
-OS Locale (lcid: 407): German (Germany) - 1252
-de_DE
-German (Germany)
-windows-1252
-
-OS Locale (lcid: 408): Greek (Greece) - 1253
-el_GR
-Greek (Greece)
-windows-1253
-
-OS Locale (lcid: 409): English (United States) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 40b): Finnish (Finland) - 1252
-fi_FI
-Finnish (Finland)
-windows-1252
-
-OS Locale (lcid: 40c): French (France) - 1252
-fr_FR
-French (France)
-windows-1252
-
-OS Locale (lcid: 40d): Hebrew (Israel) - 1255
-iw_IL
-Hebrew (Israel)
-windows-1255
-
-OS Locale (lcid: 40e): Hungarian (Hungary) - 1250
-hu_HU
-Hungarian (Hungary)
-windows-1250
-
-OS Locale (lcid: 40f): Icelandic (Iceland) - 1252
-is_IS
-Icelandic (Iceland)
-windows-1252
-
-OS Locale (lcid: 410): Italian (Italy) - 1252
-it_IT
-Italian (Italy)
-windows-1252
-
-OS Locale (lcid: 411): Japanese (Japan) - 932
-ja_JP
-Japanese (Japan)
-windows-31j
-
-OS Locale (lcid: 412): Korean (Korea) - 949
-ko_KR
-Korean (South Korea)
-x-windows-949
-
-OS Locale (lcid: 413): Dutch (Netherlands) - 1252
-nl_NL
-Dutch (Netherlands)
-windows-1252
-
-OS Locale (lcid: 414): Norwegian (Bokmål) (Norway) - 1252
-no_NO
-Norwegian (Norway)
-windows-1252
-
-OS Locale (lcid: 415): Polish (Poland) - 1250
-pl_PL
-Polish (Poland)
-windows-1250
-
-OS Locale (lcid: 416): Portuguese (Brazil) - 1252
-pt_BR
-Portuguese (Brazil)
-windows-1252
-
-OS Locale (lcid: 417): Romansh (Switzerland) - 1252
-rm_CH
-Raeto-Romance (Switzerland)
-windows-1252
-
-OS Locale (lcid: 418): Romanian (Romania) - 1250
-ro_RO
-Romanian (Romania)
-windows-1250
-
-OS Locale (lcid: 419): Russian (Russia) - 1251
-ru_RU
-Russian (Russia)
-windows-1251
-
-OS Locale (lcid: 41a): Croatian (Croatia) - 1250
-hr_HR
-Croatian (Croatia)
-windows-1250
-
-OS Locale (lcid: 41b): Slovak (Slovakia) - 1250
-sk_SK
-Slovak (Slovakia)
-windows-1250
-
-OS Locale (lcid: 41c): Albanian (Albania) - 1250
-sq_AL
-Albanian (Albania)
-windows-1250
-
-OS Locale (lcid: 41d): Swedish (Sweden) - 1252
-sv_SE
-Swedish (Sweden)
-windows-1252
-
-OS Locale (lcid: 41e): Thai (Thailand) - 874
-th_TH
-Thai (Thailand)
-x-windows-874
-
-OS Locale (lcid: 41f): Turkish (Turkey) - 1254
-tr_TR
-Turkish (Turkey)
-windows-1254
-
-OS Locale (lcid: 420): Urdu (Islamic Republic of Pakistan) - 0
-ur_PK
-Urdu (Pakistan)
-windows-1256
-
-OS Locale (lcid: 421): Indonesian (Indonesia) - 1252
-in_ID
-Indonesian (Indonesia)
-windows-1252
-
-OS Locale (lcid: 422): Ukrainian (Ukraine) - 1251
-uk_UA
-Ukrainian (Ukraine)
-windows-1251
-
-OS Locale (lcid: 423): Belarusian (Belarus) - 1251
-be_BY
-Belarusian (Belarus)
-windows-1251
-
-OS Locale (lcid: 424): Slovenian (Slovenia) - 1250
-sl_SI
-Slovenian (Slovenia)
-windows-1250
-
-OS Locale (lcid: 425): Estonian (Estonia) - 1257
-et_EE
-Estonian (Estonia)
-windows-1257
-
-OS Locale (lcid: 426): Latvian (Latvia) - 1257
-lv_LV
-Latvian (Latvia)
-windows-1257
-
-OS Locale (lcid: 427): Lithuanian (Lithuania) - 1257
-lt_LT
-Lithuanian (Lithuania)
-windows-1257
-
-OS Locale (lcid: 428): Tajik (Cyrillic) (Tajikistan) - 1251
-tg_TJ
-Tajik (Tajikistan)
-windows-1251
-
-OS Locale (lcid: 429): Persian (Iran) - 1256
-fa_IR
-Persian (Iran)
-windows-1256
-
-OS Locale (lcid: 42a): Vietnamese (Vietnam) - 1258
-vi_VN
-Vietnamese (Vietnam)
-windows-1258
-
-OS Locale (lcid: 42b): Armenian (Armenia) - 0
-hy_AM
-Armenian (Armenia)
-UTF-8
-
-OS Locale (lcid: 42c): Azeri (Latin) (Azerbaijan) - 1254
-az_AZ
-Azerbaijani (Azerbaijan)
-windows-1254
-
-OS Locale (lcid: 42d): Basque (Spain) - 1252
-eu_ES
-Basque (Spain)
-windows-1252
-
-OS Locale (lcid: 42e): Upper Sorbian (Germany) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 42f): Macedonian (FYROM) (Macedonia (FYROM)) - 1251
-mk_MK
-Macedonian (Macedonia)
-windows-1251
-
-OS Locale (lcid: 432): Setswana (South Africa) - 1252
-tn_ZA
-Tswana (South Africa)
-windows-1252
-
-OS Locale (lcid: 434): isiXhosa (South Africa) - 1252
-xh_ZA
-Xhosa (South Africa)
-windows-1252
-
-OS Locale (lcid: 435): isiZulu (South Africa) - 1252
-zu_ZA
-Zulu (South Africa)
-windows-1252
-
-OS Locale (lcid: 436): Afrikaans (South Africa) - 1252
-af_ZA
-Afrikaans (South Africa)
-windows-1252
-
-OS Locale (lcid: 437): Georgian (Georgia) - 0
-ka_GE
-Georgian (Georgia)
-UTF-8
-
-OS Locale (lcid: 438): Faroese (Faroe Islands) - 1252
-fo_FO
-Faroese (Faroe Islands)
-windows-1252
-
-OS Locale (lcid: 439): Hindi (India) - 0
-hi_IN
-Hindi (India)
-UTF-8
-
-OS Locale (lcid: 43a): Maltese (Malta) - 0
-mt_MT
-Maltese (Malta)
-UTF-8
-
-OS Locale (lcid: 43b): Sami (Northern) (Norway) - 1252
-se_NO
-Northern Sami (Norway)
-windows-1252
-
-OS Locale (lcid: 43e): Malay (Malaysia) - 1252
-ms_MY
-Malay (Malaysia)
-windows-1252
-
-OS Locale (lcid: 43f): Kazakh (Kazakhstan) - 0
-kk_KZ
-Kazakh (Kazakhstan)
-windows-1251
-
-OS Locale (lcid: 440): Kyrgyz (Kyrgyzstan) - 1251
-ky_KG
-Kirghiz (Kyrgyzstan)
-windows-1251
-
-OS Locale (lcid: 441): Kiswahili (Kenya) - 1252
-sw_KE
-Swahili (Kenya)
-windows-1252
-
-OS Locale (lcid: 442): Turkmen (Turkmenistan) - 1250
-tk_TM
-Turkmen (Turkmenistan)
-windows-1250
-
-OS Locale (lcid: 443): Uzbek (Latin) (Uzbekistan) - 1254
-uz_UZ
-Uzbek (Uzbekistan)
-windows-1254
-
-OS Locale (lcid: 444): Tatar (Russia) - 1251
-tt_RU
-Tatar (Russia)
-windows-1251
-
-OS Locale (lcid: 445): Bengali (India) - 0
-bn_IN
-Bengali (India)
-UTF-8
-
-OS Locale (lcid: 446): Punjabi (India) - 0
-pa_IN
-Panjabi (India)
-UTF-8
-
-OS Locale (lcid: 447): Gujarati (India) - 0
-gu_IN
-Gujarati (India)
-UTF-8
-
-OS Locale (lcid: 448): Oriya (India) - 0
-or_IN
-Oriya (India)
-UTF-8
-
-OS Locale (lcid: 449): Tamil (India) - 0
-ta_IN
-Tamil (India)
-UTF-8
-
-OS Locale (lcid: 44a): Telugu (India) - 0
-te_IN
-Telugu (India)
-UTF-8
-
-OS Locale (lcid: 44b): Kannada (India) - 0
-kn_IN
-Kannada (India)
-UTF-8
-
-OS Locale (lcid: 44c): Malayalam (India) - 0
-ml_IN
-Malayalam (India)
-UTF-8
-
-OS Locale (lcid: 44d): Assamese (India) - 0
-as_IN
-Assamese (India)
-UTF-8
-
-OS Locale (lcid: 44e): Marathi (India) - 0
-mr_IN
-Marathi (India)
-UTF-8
-
-OS Locale (lcid: 44f): Sanskrit (India) - 0
-sa_IN
-Sanskrit (India)
-UTF-8
-
-OS Locale (lcid: 450): Mongolian (Cyrillic) (Mongolia) - 1251
-mn_MN
-Mongolian (Mongolia)
-windows-1251
-
-OS Locale (lcid: 451): Tibetan (People's Republic of China) - 0
-bo_CN
-Tibetan (China)
-UTF-8
-
-OS Locale (lcid: 452): Welsh (United Kingdom) - 1252
-cy_GB
-Welsh (United Kingdom)
-windows-1252
-
-OS Locale (lcid: 453): Khmer (Cambodia) - 0
-km_KH
-Khmer (Cambodia)
-UTF-8
-
-OS Locale (lcid: 454): Lao (Lao P.D.R.) - 0
-lo_LA
-Lao (Laos)
-UTF-8
-
-OS Locale (lcid: 456): Galician (Spain) - 1252
-gl_ES
-Gallegan (Spain)
-windows-1252
-
-OS Locale (lcid: 457): Konkani (India) - 0
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 45a): Syriac (Syria) - 0
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 45b): Sinhala (Sri Lanka) - 0
-si_LK
-Sinhalese (Sri Lanka)
-UTF-8
-
-OS Locale (lcid: 45d): Inuktitut (Canada) - 0
-iu_CA
-Inuktitut (Canada)
-UTF-8
-
-OS Locale (lcid: 45e): Amharic (Ethiopia) - 0
-am_ET
-Amharic (Ethiopia)
-UTF-8
-
-OS Locale (lcid: 461): Nepali (Nepal) - 0
-ne_NP
-Nepali (Nepal)
-UTF-8
-
-OS Locale (lcid: 462): Frisian (Netherlands) - 1252
-fy_NL
-Frisian (Netherlands)
-windows-1252
-
-OS Locale (lcid: 463): Pashto (Afghanistan) - 0
-ps_AF
-Pushto (Afghanistan)
-windows-1256
-
-OS Locale (lcid: 464): Filipino (Philippines) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 465): Divehi (Maldives) - 0
-dv_MV
-Divehi (Maldives)
-UTF-8
-
-OS Locale (lcid: 468): Hausa (Latin) (Nigeria) - 1252
-ha_NG
-Hausa (Nigeria)
-windows-1252
-
-OS Locale (lcid: 46a): Yoruba (Nigeria) - 1252
-yo_NG
-Yoruba (Nigeria)
-windows-1252
-
-OS Locale (lcid: 46b): Quechua (Bolivia) - 1252
-qu_BO
-Quechua (Bolivia)
-windows-1252
-
-OS Locale (lcid: 46c): Sesotho sa Leboa (South Africa) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 46d): Bashkir (Russia) - 1251
-ba_RU
-Bashkir (Russia)
-windows-1251
-
-OS Locale (lcid: 46e): Luxembourgish (Luxembourg) - 1252
-lb_LU
-Luxembourgish (Luxembourg)
-windows-1252
-
-OS Locale (lcid: 46f): Greenlandic (Greenland) - 1252
-kl_GL
-Greenlandic (Greenland)
-windows-1252
-
-OS Locale (lcid: 470): Igbo (Nigeria) - 1252
-ig_NG
-Igbo (Nigeria)
-windows-1252
-
-OS Locale (lcid: 478): Yi (People's Republic of China) - 0
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 47a): Mapudungun (Chile) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 47c): Mohawk (Canada) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 47e): Breton (France) - 1252
-br_FR
-Breton (France)
-windows-1252
-
-OS Locale (lcid: 480): Uighur (People's Republic of China) - 1256
-ug_CN
-Uighur (China)
-windows-1256
-
-OS Locale (lcid: 481): Maori (New Zealand) - 0
-mi_NZ
-Maori (New Zealand)
-UTF-8
-
-OS Locale (lcid: 482): Occitan (France) - 1252
-oc_FR
-Occitan (France)
-windows-1252
-
-OS Locale (lcid: 483): Corsican (France) - 1252
-co_FR
-Corsican (France)
-windows-1252
-
-OS Locale (lcid: 484): Alsatian (France) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 485): Yakut (Russia) - 1251
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 486): K'iche (Guatemala) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 487): Kinyarwanda (Rwanda) - 1252
-rw_RW
-Kinyarwanda (Rwanda)
-windows-1252
-
-OS Locale (lcid: 488): Wolof (Senegal) - 1252
-wo_SN
-Wolof (Senegal)
-windows-1252
-
-OS Locale (lcid: 48c): Dari (Afghanistan) - 1256
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 801): Arabic (Iraq) - 1256
-ar_IQ
-Arabic (Iraq)
-windows-1256
-
-OS Locale (lcid: 804): Chinese (People's Republic of China) - 936
-zh_CN
-Chinese (China)
-GBK
-
-OS Locale (lcid: 807): German (Switzerland) - 1252
-de_CH
-German (Switzerland)
-windows-1252
-
-OS Locale (lcid: 809): English (United Kingdom) - 1252
-en_GB
-English (United Kingdom)
-windows-1252
-
-OS Locale (lcid: 80a): Spanish (Mexico) - 1252
-es_MX
-Spanish (Mexico)
-windows-1252
-
-OS Locale (lcid: 80c): French (Belgium) - 1252
-fr_BE
-French (Belgium)
-windows-1252
-
-OS Locale (lcid: 810): Italian (Switzerland) - 1252
-it_CH
-Italian (Switzerland)
-windows-1252
-
-OS Locale (lcid: 813): Dutch (Belgium) - 1252
-nl_BE
-Dutch (Belgium)
-windows-1252
-
-OS Locale (lcid: 814): Norwegian (Nynorsk) (Norway) - 1252
-no_NO_NY
-Norwegian (Norway,Nynorsk)
-windows-1252
-
-OS Locale (lcid: 816): Portuguese (Portugal) - 1252
-pt_PT
-Portuguese (Portugal)
-windows-1252
-
-OS Locale (lcid: 81a): Serbian (Latin) (Serbia and Montenegro) - 1250
-sr_CS
-Serbian (Serbia and Montenegro)
-windows-1250
-
-OS Locale (lcid: 81d): Swedish (Finland) - 1252
-sv_FI
-Swedish (Finland)
-windows-1252
-
-OS Locale (lcid: 82c): Azeri (Cyrillic) (Azerbaijan) - 1251
-az_AZ
-Azerbaijani (Azerbaijan)
-windows-1251
-
-OS Locale (lcid: 82e): Lower Sorbian (Germany) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 83b): Sami (Northern) (Sweden) - 1252
-se_SE
-Northern Sami (Sweden)
-windows-1252
-
-OS Locale (lcid: 83c): Irish (Ireland) - 1252
-ga_IE
-Irish (Ireland)
-windows-1252
-
-OS Locale (lcid: 83e): Malay (Brunei Darussalam) - 1252
-ms_BN
-Malay (Brunei)
-windows-1252
-
-OS Locale (lcid: 843): Uzbek (Cyrillic) (Uzbekistan) - 1251
-uz_UZ
-Uzbek (Uzbekistan)
-windows-1251
-
-OS Locale (lcid: 845): Bengali (Bangladesh) - 0
-bn_BD
-Bengali (Bangladesh)
-UTF-8
-
-OS Locale (lcid: 850): Mongolian (Traditional Mongolian) (People's Republic of China) - 0
-mn_CN
-Mongolian (China)
-UTF-8
-
-OS Locale (lcid: 85d): Inuktitut (Latin) (Canada) - 1252
-iu_CA
-Inuktitut (Canada)
-windows-1252
-
-OS Locale (lcid: 85f): Tamazight (Latin) (Algeria) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 86b): Quechua (Ecuador) - 1252
-qu_EC
-Quechua (Ecuador)
-windows-1252
-
-OS Locale (lcid: c01): Arabic (Egypt) - 1256
-ar_EG
-Arabic (Egypt)
-windows-1256
-
-OS Locale (lcid: c04): Chinese (Hong Kong S.A.R.) - 950
-zh_HK
-Chinese (Hong Kong)
-x-windows-950
-
-OS Locale (lcid: c07): German (Austria) - 1252
-de_AT
-German (Austria)
-windows-1252
-
-OS Locale (lcid: c09): English (Australia) - 1252
-en_AU
-English (Australia)
-windows-1252
-
-OS Locale (lcid: c0a): Spanish (Spain) - 1252
-es_ES
-Spanish (Spain)
-windows-1252
-
-OS Locale (lcid: c0c): French (Canada) - 1252
-fr_CA
-French (Canada)
-windows-1252
-
-OS Locale (lcid: c1a): Serbian (Cyrillic) (Serbia and Montenegro) - 1251
-sr_CS
-Serbian (Serbia and Montenegro)
-windows-1251
-
-OS Locale (lcid: c3b): Sami (Northern) (Finland) - 1252
-se_FI
-Northern Sami (Finland)
-windows-1252
-
-OS Locale (lcid: c6b): Quechua (Peru) - 1252
-qu_PE
-Quechua (Peru)
-windows-1252
-
-OS Locale (lcid: 1001): Arabic (Libya) - 1256
-ar_LY
-Arabic (Libya)
-windows-1256
-
-OS Locale (lcid: 1004): Chinese (Singapore) - 936
-zh_SG
-Chinese (Singapore)
-GBK
-
-OS Locale (lcid: 1007): German (Luxembourg) - 1252
-de_LU
-German (Luxembourg)
-windows-1252
-
-OS Locale (lcid: 1009): English (Canada) - 1252
-en_CA
-English (Canada)
-windows-1252
-
-OS Locale (lcid: 100a): Spanish (Guatemala) - 1252
-es_GT
-Spanish (Guatemala)
-windows-1252
-
-OS Locale (lcid: 100c): French (Switzerland) - 1252
-fr_CH
-French (Switzerland)
-windows-1252
-
-OS Locale (lcid: 101a): Croatian (Latin) (Bosnia and Herzegovina) - 1250
-hr_BA
-Croatian (Bosnia and Herzegovina)
-windows-1250
-
-OS Locale (lcid: 103b): Sami (Lule) (Norway) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 1401): Arabic (Algeria) - 1256
-ar_DZ
-Arabic (Algeria)
-windows-1256
-
-OS Locale (lcid: 1404): Chinese (Macao S.A.R.) - 950
-zh_MO
-Chinese (Macao)
-x-windows-950
-
-OS Locale (lcid: 1407): German (Liechtenstein) - 1252
-de_LI
-German (Liechtenstein)
-windows-1252
-
-OS Locale (lcid: 1409): English (New Zealand) - 1252
-en_NZ
-English (New Zealand)
-windows-1252
-
-OS Locale (lcid: 140a): Spanish (Costa Rica) - 1252
-es_CR
-Spanish (Costa Rica)
-windows-1252
-
-OS Locale (lcid: 140c): French (Luxembourg) - 1252
-fr_LU
-French (Luxembourg)
-windows-1252
-
-OS Locale (lcid: 141a): Bosnian (Latin) (Bosnia and Herzegovina) - 1250
-bs_BA
-Bosnian (Bosnia and Herzegovina)
-windows-1250
-
-OS Locale (lcid: 143b): Sami (Lule) (Sweden) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 1801): Arabic (Morocco) - 1256
-ar_MA
-Arabic (Morocco)
-windows-1256
-
-OS Locale (lcid: 1809): English (Ireland) - 1252
-en_IE
-English (Ireland)
-windows-1252
-
-OS Locale (lcid: 180a): Spanish (Panama) - 1252
-es_PA
-Spanish (Panama)
-windows-1252
-
-OS Locale (lcid: 180c): French (Principality of Monaco) - 1252
-fr_MC
-French (Monaco)
-windows-1252
-
-OS Locale (lcid: 181a): Serbian (Latin) (Bosnia and Herzegovina) - 1250
-sr_BA
-Serbian (Bosnia and Herzegovina)
-windows-1250
-
-OS Locale (lcid: 183b): Sami (Southern) (Norway) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 1c01): Arabic (Tunisia) - 1256
-ar_TN
-Arabic (Tunisia)
-windows-1256
-
-OS Locale (lcid: 1c09): English (South Africa) - 1252
-en_ZA
-English (South Africa)
-windows-1252
-
-OS Locale (lcid: 1c0a): Spanish (Dominican Republic) - 1252
-es_DO
-Spanish (Dominican Republic)
-windows-1252
-
-OS Locale (lcid: 1c1a): Serbian (Cyrillic) (Bosnia and Herzegovina) - 1251
-sr_BA
-Serbian (Bosnia and Herzegovina)
-windows-1251
-
-OS Locale (lcid: 1c3b): Sami (Southern) (Sweden) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 2001): Arabic (Oman) - 1256
-ar_OM
-Arabic (Oman)
-windows-1256
-
-OS Locale (lcid: 2009): English (Jamaica) - 1252
-en_JM
-English (Jamaica)
-windows-1252
-
-OS Locale (lcid: 200a): Spanish (Venezuela) - 1252
-es_VE
-Spanish (Venezuela)
-windows-1252
-
-OS Locale (lcid: 201a): Bosnian (Cyrillic) (Bosnia and Herzegovina) - 1251
-bs_BA
-Bosnian (Bosnia and Herzegovina)
-windows-1250
-
-OS Locale (lcid: 203b): Sami (Skolt) (Finland) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 2401): Arabic (Yemen) - 1256
-ar_YE
-Arabic (Yemen)
-windows-1256
-
-OS Locale (lcid: 2409): English (Caribbean) - 1252
-en
-English
-windows-1252
-
-OS Locale (lcid: 240a): Spanish (Colombia) - 1252
-es_CO
-Spanish (Colombia)
-windows-1252
-
-OS Locale (lcid: 243b): Sami (Inari) (Finland) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 2801): Arabic (Syria) - 1256
-ar_SY
-Arabic (Syria)
-windows-1256
-
-OS Locale (lcid: 2809): English (Belize) - 1252
-en_BZ
-English (Belize)
-windows-1252
-
-OS Locale (lcid: 280a): Spanish (Peru) - 1252
-es_PE
-Spanish (Peru)
-windows-1252
-
-OS Locale (lcid: 2c01): Arabic (Jordan) - 1256
-ar_JO
-Arabic (Jordan)
-windows-1256
-
-OS Locale (lcid: 2c09): English (Trinidad and Tobago) - 1252
-en_TT
-English (Trinidad and Tobago)
-windows-1252
-
-OS Locale (lcid: 2c0a): Spanish (Argentina) - 1252
-es_AR
-Spanish (Argentina)
-windows-1252
-
-OS Locale (lcid: 3001): Arabic (Lebanon) - 1256
-ar_LB
-Arabic (Lebanon)
-windows-1256
-
-OS Locale (lcid: 3009): English (Zimbabwe) - 1252
-en_ZW
-English (Zimbabwe)
-windows-1252
-
-OS Locale (lcid: 300a): Spanish (Ecuador) - 1252
-es_EC
-Spanish (Ecuador)
-windows-1252
-
-OS Locale (lcid: 3401): Arabic (Kuwait) - 1256
-ar_KW
-Arabic (Kuwait)
-windows-1256
-
-OS Locale (lcid: 3409): English (Republic of the Philippines) - 1252
-en_PH
-English (Philippines)
-windows-1252
-
-OS Locale (lcid: 340a): Spanish (Chile) - 1252
-es_CL
-Spanish (Chile)
-windows-1252
-
-OS Locale (lcid: 3801): Arabic (U.A.E.) - 1256
-ar_AE
-Arabic (United Arab Emirates)
-windows-1256
-
-OS Locale (lcid: 380a): Spanish (Uruguay) - 1252
-es_UY
-Spanish (Uruguay)
-windows-1252
-
-OS Locale (lcid: 3c01): Arabic (Bahrain) - 1256
-ar_BH
-Arabic (Bahrain)
-windows-1256
-
-OS Locale (lcid: 3c0a): Spanish (Paraguay) - 1252
-es_PY
-Spanish (Paraguay)
-windows-1252
-
-OS Locale (lcid: 4001): Arabic (Qatar) - 1256
-ar_QA
-Arabic (Qatar)
-windows-1256
-
-OS Locale (lcid: 4009): English (India) - 1252
-en_IN
-English (India)
-windows-1252
-
-OS Locale (lcid: 400a): Spanish (Bolivia) - 1252
-es_BO
-Spanish (Bolivia)
-windows-1252
-
-OS Locale (lcid: 4409): English (Malaysia) - 1252
-en_MY
-English (Malaysia)
-windows-1252
-
-OS Locale (lcid: 440a): Spanish (El Salvador) - 1252
-es_SV
-Spanish (El Salvador)
-windows-1252
-
-OS Locale (lcid: 4809): English (Singapore) - 1252
-en_SG
-English (Singapore)
-windows-1252
-
-OS Locale (lcid: 480a): Spanish (Honduras) - 1252
-es_HN
-Spanish (Honduras)
-windows-1252
-
-OS Locale (lcid: 4c0a): Spanish (Nicaragua) - 1252
-es_NI
-Spanish (Nicaragua)
-windows-1252
-
-OS Locale (lcid: 500a): Spanish (Puerto Rico) - 1252
-es_PR
-Spanish (Puerto Rico)
-windows-1252
-
-OS Locale (lcid: 540a): Spanish (United States) - 1252
-es_US
-Spanish (United States)
-windows-1252
--- a/test/java/util/Locale/data/deflocale.winxp	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,861 +0,0 @@
-# OSVersionInfo
-# MajorVersion: 5
-# MinorVersion: 1
-# BuildNumber: 2600
-# CSDVersion: Service Pack 2
-
-
-OS Locale (lcid: 401): Arabic (Saudi Arabia) - 1256
-ar_SA
-Arabic (Saudi Arabia)
-windows-1256
-
-OS Locale (lcid: 402): Bulgarian (Bulgaria) - 1251
-bg_BG
-Bulgarian (Bulgaria)
-windows-1251
-
-OS Locale (lcid: 403): Catalan (Spain) - 1252
-ca_ES
-Catalan (Spain)
-windows-1252
-
-OS Locale (lcid: 404): Chinese (Taiwan) - 950
-zh_TW
-Chinese (Taiwan)
-x-windows-950
-
-OS Locale (lcid: 405): Czech (Czech Republic) - 1250
-cs_CZ
-Czech (Czech Republic)
-windows-1250
-
-OS Locale (lcid: 406): Danish (Denmark) - 1252
-da_DK
-Danish (Denmark)
-windows-1252
-
-OS Locale (lcid: 407): German (Germany) - 1252
-de_DE
-German (Germany)
-windows-1252
-
-OS Locale (lcid: 408): Greek (Greece) - 1253
-el_GR
-Greek (Greece)
-windows-1253
-
-OS Locale (lcid: 409): English (United States) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 40a): Spanish (Spain) - 1252
-es_ES
-Spanish (Spain)
-windows-1252
-
-OS Locale (lcid: 40b): Finnish (Finland) - 1252
-fi_FI
-Finnish (Finland)
-windows-1252
-
-OS Locale (lcid: 40c): French (France) - 1252
-fr_FR
-French (France)
-windows-1252
-
-OS Locale (lcid: 40d): Hebrew (Israel) - 1255
-iw_IL
-Hebrew (Israel)
-windows-1255
-
-OS Locale (lcid: 40e): Hungarian (Hungary) - 1250
-hu_HU
-Hungarian (Hungary)
-windows-1250
-
-OS Locale (lcid: 40f): Icelandic (Iceland) - 1252
-is_IS
-Icelandic (Iceland)
-windows-1252
-
-OS Locale (lcid: 410): Italian (Italy) - 1252
-it_IT
-Italian (Italy)
-windows-1252
-
-OS Locale (lcid: 411): Japanese (Japan) - 932
-ja_JP
-Japanese (Japan)
-windows-31j
-
-OS Locale (lcid: 412): Korean (Korea) - 949
-ko_KR
-Korean (South Korea)
-x-windows-949
-
-OS Locale (lcid: 413): Dutch (Netherlands) - 1252
-nl_NL
-Dutch (Netherlands)
-windows-1252
-
-OS Locale (lcid: 414): Norwegian (Bokmål) (Norway) - 1252
-no_NO
-Norwegian (Norway)
-windows-1252
-
-OS Locale (lcid: 415): Polish (Poland) - 1250
-pl_PL
-Polish (Poland)
-windows-1250
-
-OS Locale (lcid: 416): Portuguese (Brazil) - 1252
-pt_BR
-Portuguese (Brazil)
-windows-1252
-
-OS Locale (lcid: 417): Romansh (Switzerland) - 1252
-rm_CH
-Raeto-Romance (Switzerland)
-windows-1252
-
-OS Locale (lcid: 418): Romanian (Romania) - 1250
-ro_RO
-Romanian (Romania)
-windows-1250
-
-OS Locale (lcid: 419): Russian (Russia) - 1251
-ru_RU
-Russian (Russia)
-windows-1251
-
-OS Locale (lcid: 41a): Croatian (Croatia) - 1250
-hr_HR
-Croatian (Croatia)
-windows-1250
-
-OS Locale (lcid: 41b): Slovak (Slovakia) - 1250
-sk_SK
-Slovak (Slovakia)
-windows-1250
-
-OS Locale (lcid: 41c): Albanian (Albania) - 1250
-sq_AL
-Albanian (Albania)
-windows-1250
-
-OS Locale (lcid: 41d): Swedish (Sweden) - 1252
-sv_SE
-Swedish (Sweden)
-windows-1252
-
-OS Locale (lcid: 41e): Thai (Thailand) - 874
-th_TH
-Thai (Thailand)
-x-windows-874
-
-OS Locale (lcid: 41f): Turkish (Turkey) - 1254
-tr_TR
-Turkish (Turkey)
-windows-1254
-
-OS Locale (lcid: 420): Urdu (Islamic Republic of Pakistan) - 1256
-ur_PK
-Urdu (Pakistan)
-windows-1256
-
-OS Locale (lcid: 421): Indonesian (Indonesia) - 1252
-in_ID
-Indonesian (Indonesia)
-windows-1252
-
-OS Locale (lcid: 422): Ukrainian (Ukraine) - 1251
-uk_UA
-Ukrainian (Ukraine)
-windows-1251
-
-OS Locale (lcid: 423): Belarusian (Belarus) - 1251
-be_BY
-Belarusian (Belarus)
-windows-1251
-
-OS Locale (lcid: 424): Slovenian (Slovenia) - 1250
-sl_SI
-Slovenian (Slovenia)
-windows-1250
-
-OS Locale (lcid: 425): Estonian (Estonia) - 1257
-et_EE
-Estonian (Estonia)
-windows-1257
-
-OS Locale (lcid: 426): Latvian (Latvia) - 1257
-lv_LV
-Latvian (Latvia)
-windows-1257
-
-OS Locale (lcid: 427): Lithuanian (Lithuania) - 1257
-lt_LT
-Lithuanian (Lithuania)
-windows-1257
-
-OS Locale (lcid: 429): Farsi (Iran) - 1256
-fa_IR
-Persian (Iran)
-windows-1256
-
-OS Locale (lcid: 42a): Vietnamese (Viet Nam) - 1258
-vi_VN
-Vietnamese (Vietnam)
-windows-1258
-
-OS Locale (lcid: 42b): Armenian (Armenia) - 0
-hy_AM
-Armenian (Armenia)
-UTF-8
-
-OS Locale (lcid: 42c): Azeri (Latin) (Azerbaijan) - 1254
-az_AZ
-Azerbaijani (Azerbaijan)
-windows-1254
-
-OS Locale (lcid: 42d): Basque (Spain) - 1252
-eu_ES
-Basque (Spain)
-windows-1252
-
-OS Locale (lcid: 42f): FYRO Macedonian (Former Yugoslav Republic of Macedonia) - 1251
-mk_MK
-Macedonian (Macedonia)
-windows-1251
-
-OS Locale (lcid: 432): Tswana (South Africa) - 1252
-tn_ZA
-Tswana (South Africa)
-windows-1252
-
-OS Locale (lcid: 434): Xhosa (South Africa) - 1252
-xh_ZA
-Xhosa (South Africa)
-windows-1252
-
-OS Locale (lcid: 435): Zulu (South Africa) - 1252
-zu_ZA
-Zulu (South Africa)
-windows-1252
-
-OS Locale (lcid: 436): Afrikaans (South Africa) - 1252
-af_ZA
-Afrikaans (South Africa)
-windows-1252
-
-OS Locale (lcid: 437): Georgian (Georgia) - 0
-ka_GE
-Georgian (Georgia)
-UTF-8
-
-OS Locale (lcid: 438): Faroese (Faroe Islands) - 1252
-fo_FO
-Faroese (Faroe Islands)
-windows-1252
-
-OS Locale (lcid: 439): Hindi (India) - 0
-hi_IN
-Hindi (India)
-UTF-8
-
-OS Locale (lcid: 43a): Maltese (Malta) - 0
-mt_MT
-Maltese (Malta)
-UTF-8
-
-OS Locale (lcid: 43b): Sami (Northern) (Norway) - 1252
-se_NO
-Northern Sami (Norway)
-windows-1252
-
-OS Locale (lcid: 43e): Malay (Malaysia) - 1252
-ms_MY
-Malay (Malaysia)
-windows-1252
-
-OS Locale (lcid: 43f): Kazakh (Kazakhstan) - 1251
-kk_KZ
-Kazakh (Kazakhstan)
-windows-1251
-
-OS Locale (lcid: 440): Kyrgyz (Kyrgyzstan) - 1251
-ky_KG
-Kirghiz (Kyrgyzstan)
-windows-1251
-
-OS Locale (lcid: 441): Swahili (Kenya) - 1252
-sw_KE
-Swahili (Kenya)
-windows-1252
-
-OS Locale (lcid: 443): Uzbek (Latin) (Uzbekistan) - 1254
-uz_UZ
-Uzbek (Uzbekistan)
-windows-1254
-
-OS Locale (lcid: 444): Tatar (Russia) - 1251
-tt_RU
-Tatar (Russia)
-windows-1251
-
-OS Locale (lcid: 445): Bengali (India) - 0
-bn_IN
-Bengali (India)
-UTF-8
-
-OS Locale (lcid: 446): Punjabi (India) - 0
-pa_IN
-Panjabi (India)
-UTF-8
-
-OS Locale (lcid: 447): Gujarati (India) - 0
-gu_IN
-Gujarati (India)
-UTF-8
-
-OS Locale (lcid: 449): Tamil (India) - 0
-ta_IN
-Tamil (India)
-UTF-8
-
-OS Locale (lcid: 44a): Telugu (India) - 0
-te_IN
-Telugu (India)
-UTF-8
-
-OS Locale (lcid: 44b): Kannada (India) - 0
-kn_IN
-Kannada (India)
-UTF-8
-
-OS Locale (lcid: 44c): Malayalam (India) - 0
-ml_IN
-Malayalam (India)
-UTF-8
-
-OS Locale (lcid: 44e): Marathi (India) - 0
-mr_IN
-Marathi (India)
-UTF-8
-
-OS Locale (lcid: 44f): Sanskrit (India) - 0
-sa_IN
-Sanskrit (India)
-UTF-8
-
-OS Locale (lcid: 450): Mongolian (Mongolia) - 1251
-mn_MN
-Mongolian (Mongolia)
-windows-1251
-
-OS Locale (lcid: 452): Welsh (United Kingdom) - 1252
-cy_GB
-Welsh (United Kingdom)
-windows-1252
-
-OS Locale (lcid: 456): Galician (Spain) - 1252
-gl_ES
-Gallegan (Spain)
-windows-1252
-
-OS Locale (lcid: 457): Konkani (India) - 0
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 45a): Syriac (Syria) - 0
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 461): Nepali (Nepal) - 0
-ne_NP
-Nepali (Nepal)
-UTF-8
-
-OS Locale (lcid: 462): Frisian (Netherlands) - 1252
-fy_NL
-Frisian (Netherlands)
-windows-1252
-
-OS Locale (lcid: 463): Pashto (Afghanistan) - 1256
-ps_AF
-Pushto (Afghanistan)
-windows-1256
-
-OS Locale (lcid: 464): Filipino (Philippines) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 465): Divehi (Maldives) - 0
-dv_MV
-Divehi (Maldives)
-UTF-8
-
-OS Locale (lcid: 46b): Quechua (Bolivia) - 1252
-qu_BO
-Quechua (Bolivia)
-windows-1252
-
-OS Locale (lcid: 46c): Northern Sotho (South Africa) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 46e): Luxembourgish (Luxembourg) - 1252
-lb_LU
-Luxembourgish (Luxembourg)
-windows-1252
-
-OS Locale (lcid: 47a): Mapudungun (Chile) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 47c): Mohawk (Canada) - 1252
-en_US
-English (United States)
-windows-1252
-
-OS Locale (lcid: 481): Maori (New Zealand) - 0
-mi_NZ
-Maori (New Zealand)
-UTF-8
-
-OS Locale (lcid: 801): Arabic (Iraq) - 1256
-ar_IQ
-Arabic (Iraq)
-windows-1256
-
-OS Locale (lcid: 804): Chinese (People's Republic of China) - 936
-zh_CN
-Chinese (China)
-GBK
-
-OS Locale (lcid: 807): German (Switzerland) - 1252
-de_CH
-German (Switzerland)
-windows-1252
-
-OS Locale (lcid: 809): English (United Kingdom) - 1252
-en_GB
-English (United Kingdom)
-windows-1252
-
-OS Locale (lcid: 80a): Spanish (Mexico) - 1252
-es_MX
-Spanish (Mexico)
-windows-1252
-
-OS Locale (lcid: 80c): French (Belgium) - 1252
-fr_BE
-French (Belgium)
-windows-1252
-
-OS Locale (lcid: 810): Italian (Switzerland) - 1252
-it_CH
-Italian (Switzerland)
-windows-1252
-
-OS Locale (lcid: 813): Dutch (Belgium) - 1252
-nl_BE
-Dutch (Belgium)
-windows-1252
-
-OS Locale (lcid: 814): Norwegian (Nynorsk) (Norway) - 1252
-no_NO_NY
-Norwegian (Norway,Nynorsk)
-windows-1252
-
-OS Locale (lcid: 816): Portuguese (Portugal) - 1252
-pt_PT
-Portuguese (Portugal)
-windows-1252
-
-OS Locale (lcid: 81a): Serbian (Latin) (Serbia and Montenegro) - 1250
-sr_CS
-Serbian (Serbia and Montenegro)
-windows-1250
-
-OS Locale (lcid: 81d): Swedish (Finland) - 1252
-sv_FI
-Swedish (Finland)
-windows-1252
-
-OS Locale (lcid: 82c): Azeri (Cyrillic) (Azerbaijan) - 1251
-az_AZ
-Azerbaijani (Azerbaijan)
-windows-1251
-
-OS Locale (lcid: 83b): Sami (Northern) (Sweden) - 1252
-se_SE
-Northern Sami (Sweden)
-windows-1252
-
-OS Locale (lcid: 83c): Irish (Ireland) - 1252
-ga_IE
-Irish (Ireland)
-windows-1252
-
-OS Locale (lcid: 83e): Malay (Brunei Darussalam) - 1252
-ms_BN
-Malay (Brunei)
-windows-1252
-
-OS Locale (lcid: 843): Uzbek (Cyrillic) (Uzbekistan) - 1251
-uz_UZ
-Uzbek (Uzbekistan)
-windows-1251
-
-OS Locale (lcid: 85d): Inuktitut (Latin) (Canada) - 1252
-iu_CA
-Inuktitut (Canada)
-windows-1252
-
-OS Locale (lcid: 86b): Quechua (Ecuador) - 1252
-qu_EC
-Quechua (Ecuador)
-windows-1252
-
-OS Locale (lcid: c01): Arabic (Egypt) - 1256
-ar_EG
-Arabic (Egypt)
-windows-1256
-
-OS Locale (lcid: c04): Chinese (Hong Kong S.A.R.) - 950
-zh_HK
-Chinese (Hong Kong)
-x-windows-950
-
-OS Locale (lcid: c07): German (Austria) - 1252
-de_AT
-German (Austria)
-windows-1252
-
-OS Locale (lcid: c09): English (Australia) - 1252
-en_AU
-English (Australia)
-windows-1252
-
-OS Locale (lcid: c0a): Spanish (Spain) - 1252
-es_ES
-Spanish (Spain)
-windows-1252
-
-OS Locale (lcid: c0c): French (Canada) - 1252
-fr_CA
-French (Canada)
-windows-1252
-
-OS Locale (lcid: c1a): Serbian (Cyrillic) (Serbia and Montenegro) - 1251
-sr_CS
-Serbian (Serbia and Montenegro)
-windows-1251
-
-OS Locale (lcid: c3b): Sami (Northern) (Finland) - 1252
-se_FI
-Northern Sami (Finland)
-windows-1252
-
-OS Locale (lcid: c6b): Quechua (Peru) - 1252
-qu_PE
-Quechua (Peru)
-windows-1252
-
-OS Locale (lcid: 1001): Arabic (Libya) - 1256
-ar_LY
-Arabic (Libya)
-windows-1256
-
-OS Locale (lcid: 1004): Chinese (Singapore) - 936
-zh_SG
-Chinese (Singapore)
-GBK
-
-OS Locale (lcid: 1007): German (Luxembourg) - 1252
-de_LU
-German (Luxembourg)
-windows-1252
-
-OS Locale (lcid: 1009): English (Canada) - 1252
-en_CA
-English (Canada)
-windows-1252
-
-OS Locale (lcid: 100a): Spanish (Guatemala) - 1252
-es_GT
-Spanish (Guatemala)
-windows-1252
-
-OS Locale (lcid: 100c): French (Switzerland) - 1252
-fr_CH
-French (Switzerland)
-windows-1252
-
-OS Locale (lcid: 101a): Croatian (Bosnia and Herzegovina) - 1250
-hr_BA
-Croatian (Bosnia and Herzegovina)
-windows-1250
-
-OS Locale (lcid: 103b): Sami (Lule) (Norway) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 1401): Arabic (Algeria) - 1256
-ar_DZ
-Arabic (Algeria)
-windows-1256
-
-OS Locale (lcid: 1404): Chinese (Macau S.A.R.) - 950
-zh_MO
-Chinese (Macao)
-x-windows-950
-
-OS Locale (lcid: 1407): German (Liechtenstein) - 1252
-de_LI
-German (Liechtenstein)
-windows-1252
-
-OS Locale (lcid: 1409): English (New Zealand) - 1252
-en_NZ
-English (New Zealand)
-windows-1252
-
-OS Locale (lcid: 140a): Spanish (Costa Rica) - 1252
-es_CR
-Spanish (Costa Rica)
-windows-1252
-
-OS Locale (lcid: 140c): French (Luxembourg) - 1252
-fr_LU
-French (Luxembourg)
-windows-1252
-
-OS Locale (lcid: 141a): Bosnian (Bosnia and Herzegovina) - 1250
-bs_BA
-Bosnian (Bosnia and Herzegovina)
-windows-1250
-
-OS Locale (lcid: 143b): Sami (Lule) (Sweden) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 1801): Arabic (Morocco) - 1256
-ar_MA
-Arabic (Morocco)
-windows-1256
-
-OS Locale (lcid: 1809): English (Ireland) - 1252
-en_IE
-English (Ireland)
-windows-1252
-
-OS Locale (lcid: 180a): Spanish (Panama) - 1252
-es_PA
-Spanish (Panama)
-windows-1252
-
-OS Locale (lcid: 180c): French (Principality of Monaco) - 1252
-fr_MC
-French (Monaco)
-windows-1252
-
-OS Locale (lcid: 181a): Serbian (Latin) (Bosnia and Herzegovina) - 1250
-sr_BA
-Serbian (Bosnia and Herzegovina)
-windows-1250
-
-OS Locale (lcid: 183b): Sami (Southern) (Norway) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 1c01): Arabic (Tunisia) - 1256
-ar_TN
-Arabic (Tunisia)
-windows-1256
-
-OS Locale (lcid: 1c09): English (South Africa) - 1252
-en_ZA
-English (South Africa)
-windows-1252
-
-OS Locale (lcid: 1c0a): Spanish (Dominican Republic) - 1252
-es_DO
-Spanish (Dominican Republic)
-windows-1252
-
-OS Locale (lcid: 1c1a): Serbian (Cyrillic) (Bosnia and Herzegovina) - 1251
-sr_BA
-Serbian (Bosnia and Herzegovina)
-windows-1251
-
-OS Locale (lcid: 1c3b): Sami (Southern) (Sweden) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 2001): Arabic (Oman) - 1256
-ar_OM
-Arabic (Oman)
-windows-1256
-
-OS Locale (lcid: 2009): English (Jamaica) - 1252
-en_JM
-English (Jamaica)
-windows-1252
-
-OS Locale (lcid: 200a): Spanish (Venezuela) - 1252
-es_VE
-Spanish (Venezuela)
-windows-1252
-
-OS Locale (lcid: 201a): Bosnian (Cyrillic) (Bosnia and Herzegovina) - 1250
-bs_BA
-Bosnian (Bosnia and Herzegovina)
-windows-1250
-
-OS Locale (lcid: 203b): Sami (Skolt) (Finland) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 2401): Arabic (Yemen) - 1256
-ar_YE
-Arabic (Yemen)
-windows-1256
-
-OS Locale (lcid: 2409): English (Caribbean) - 1252
-en
-English
-windows-1252
-
-OS Locale (lcid: 240a): Spanish (Colombia) - 1252
-es_CO
-Spanish (Colombia)
-windows-1252
-
-OS Locale (lcid: 243b): Sami (Inari) (Finland) - 1252
-se
-Northern Sami
-windows-1252
-
-OS Locale (lcid: 2801): Arabic (Syria) - 1256
-ar_SY
-Arabic (Syria)
-windows-1256
-
-OS Locale (lcid: 2809): English (Belize) - 1252
-en_BZ
-English (Belize)
-windows-1252
-
-OS Locale (lcid: 280a): Spanish (Peru) - 1252
-es_PE
-Spanish (Peru)
-windows-1252
-
-OS Locale (lcid: 2c01): Arabic (Jordan) - 1256
-ar_JO
-Arabic (Jordan)
-windows-1256
-
-OS Locale (lcid: 2c09): English (Trinidad and Tobago) - 1252
-en_TT
-English (Trinidad and Tobago)
-windows-1252
-
-OS Locale (lcid: 2c0a): Spanish (Argentina) - 1252
-es_AR
-Spanish (Argentina)
-windows-1252
-
-OS Locale (lcid: 3001): Arabic (Lebanon) - 1256
-ar_LB
-Arabic (Lebanon)
-windows-1256
-
-OS Locale (lcid: 3009): English (Zimbabwe) - 1252
-en_ZW
-English (Zimbabwe)
-windows-1252
-
-OS Locale (lcid: 300a): Spanish (Ecuador) - 1252
-es_EC
-Spanish (Ecuador)
-windows-1252
-
-OS Locale (lcid: 3401): Arabic (Kuwait) - 1256
-ar_KW
-Arabic (Kuwait)
-windows-1256
-
-OS Locale (lcid: 3409): English (Republic of the Philippines) - 1252
-en_PH
-English (Philippines)
-windows-1252
-
-OS Locale (lcid: 340a): Spanish (Chile) - 1252
-es_CL
-Spanish (Chile)
-windows-1252
-
-OS Locale (lcid: 3801): Arabic (U.A.E.) - 1256
-ar_AE
-Arabic (United Arab Emirates)
-windows-1256
-
-OS Locale (lcid: 380a): Spanish (Uruguay) - 1252
-es_UY
-Spanish (Uruguay)
-windows-1252
-
-OS Locale (lcid: 3c01): Arabic (Bahrain) - 1256
-ar_BH
-Arabic (Bahrain)
-windows-1256
-
-OS Locale (lcid: 3c0a): Spanish (Paraguay) - 1252
-es_PY
-Spanish (Paraguay)
-windows-1252
-
-OS Locale (lcid: 4001): Arabic (Qatar) - 1256
-ar_QA
-Arabic (Qatar)
-windows-1256
-
-OS Locale (lcid: 400a): Spanish (Bolivia) - 1252
-es_BO
-Spanish (Bolivia)
-windows-1252
-
-OS Locale (lcid: 440a): Spanish (El Salvador) - 1252
-es_SV
-Spanish (El Salvador)
-windows-1252
-
-OS Locale (lcid: 480a): Spanish (Honduras) - 1252
-es_HN
-Spanish (Honduras)
-windows-1252
-
-OS Locale (lcid: 4c0a): Spanish (Nicaragua) - 1252
-es_NI
-Spanish (Nicaragua)
-windows-1252
-
-OS Locale (lcid: 500a): Spanish (Puerto Rico) - 1252
-es_PR
-Spanish (Puerto Rico)
-windows-1252
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Locale/icuLocales.txt	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,292 @@
+af
+af-NA
+af-ZA
+am
+am-ET
+ar
+ar-AE
+ar-BH
+ar-DZ
+ar-EG
+ar-IQ
+ar-JO
+ar-KW
+ar-LB
+ar-LY
+ar-MA
+ar-OM
+ar-QA
+ar-SA
+ar-SD
+ar-SY
+ar-TN
+ar-YE
+as
+as-IN
+az
+az-Cyrl
+az-Cyrl-AZ
+az-Latn
+az-Latn-AZ
+be
+be-BY
+bg
+bg-BG
+bn
+bn-BD
+bn-IN
+bo
+bo-CN
+bo-IN
+ca
+ca-ES
+cs
+cs-CZ
+cy
+cy-GB
+da
+da-DK
+de
+de-AT
+de-BE
+de-CH
+de-DE
+de-LI
+de-LU
+el
+el-CY
+el-GR
+en
+en-AU
+en-BE
+en-BW
+en-BZ
+en-CA
+en-GB
+en-HK
+en-IE
+en-IN
+en-JM
+en-MH
+en-MT
+en-NA
+en-NZ
+en-PH
+en-PK
+en-SG
+en-TT
+en-US
+en-US-posix
+en-VI
+en-ZA
+en-ZW
+eo
+es
+es-AR
+es-BO
+es-CL
+es-CO
+es-CR
+es-DO
+es-EC
+es-ES
+es-GT
+es-HN
+es-MX
+es-NI
+es-PA
+es-PE
+es-PR
+es-PY
+es-SV
+es-US
+es-UY
+es-VE
+et
+et-EE
+eu
+eu-ES
+fa
+fa-AF
+fa-IR
+fi
+fi-FI
+fo
+fo-FO
+fr
+fr-BE
+fr-CA
+fr-CH
+fr-FR
+fr-LU
+fr-MC
+fr-SN
+ga
+ga-IE
+gl
+gl-ES
+gsw
+gsw-CH
+gu
+gu-IN
+gv
+gv-GB
+ha
+ha-Latn
+ha-Latn-GH
+ha-Latn-NE
+ha-Latn-NG
+haw
+haw-US
+he
+he-IL
+hi
+hi-IN
+hr
+hr-HR
+hu
+hu-HU
+hy
+hy-AM
+hy-AM-revised
+id
+id-ID
+ii
+ii-CN
+is
+is-IS
+it
+it-CH
+it-IT
+ja
+ja-JP
+ka
+ka-GE
+kk
+kk-Cyrl
+kk-Cyrl-KZ
+kl
+kl-GL
+km
+km-KH
+kn
+kn-IN
+ko
+ko-KR
+kok
+kok-IN
+kw
+kw-GB
+lt
+lt-LT
+lv
+lv-LV
+mk
+mk-MK
+ml
+ml-IN
+mr
+mr-IN
+ms
+ms-BN
+ms-MY
+mt
+mt-MT
+nb
+nb-NO
+ne
+ne-IN
+ne-NP
+nl
+nl-BE
+nl-NL
+nn
+nn-NO
+om
+om-ET
+om-KE
+or
+or-IN
+pa
+pa-Arab
+pa-Arab-PK
+pa-Guru
+pa-Guru-IN
+pl
+pl-PL
+ps
+ps-AF
+pt
+pt-BR
+pt-PT
+ro
+ro-MD
+ro-RO
+ru
+ru-RU
+ru-UA
+si
+si-LK
+sk
+sk-SK
+sl
+sl-SI
+so
+so-DJ
+so-ET
+so-KE
+so-SO
+sq
+sq-AL
+sr
+sr-Cyrl
+sr-Cyrl-BA
+sr-Cyrl-ME
+sr-Cyrl-RS
+sr-Latn
+sr-Latn-BA
+sr-Latn-ME
+sr-Latn-RS
+sv
+sv-FI
+sv-SE
+sw
+sw-KE
+sw-TZ
+ta
+ta-IN
+te
+te-IN
+th
+th-TH
+ti
+ti-ER
+ti-ET
+tr
+tr-TR
+uk
+uk-UA
+ur
+ur-IN
+ur-PK
+uz
+uz-Arab
+uz-Arab-AF
+uz-Cyrl
+uz-Cyrl-UZ
+uz-Latn
+uz-Latn-UZ
+vi
+vi-VN
+zh
+zh-Hans
+zh-Hans-CN
+zh-Hans-HK
+zh-Hans-MO
+zh-Hans-SG
+zh-Hant
+zh-Hant-HK
+zh-Hant-MO
+zh-Hant-TW
+zu
+zu-ZA
Binary file test/java/util/Locale/serialized/java6locale_ROOT has changed
Binary file test/java/util/Locale/serialized/java6locale__US has changed
Binary file test/java/util/Locale/serialized/java6locale___Java has changed
Binary file test/java/util/Locale/serialized/java6locale_en has changed
Binary file test/java/util/Locale/serialized/java6locale_en_US has changed
Binary file test/java/util/Locale/serialized/java6locale_en_US_Java has changed
Binary file test/java/util/Locale/serialized/java6locale_iw_IL has changed
Binary file test/java/util/Locale/serialized/java6locale_ja_JP_JP has changed
Binary file test/java/util/Locale/serialized/java6locale_no_NO_NY has changed
Binary file test/java/util/Locale/serialized/java6locale_th_TH_TH has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/TimeZone/Bug6912560.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 6912560
+ * @run main/othervm Bug6912560
+ * @summary Make sure that file path canonicalization in
+ * sun.util.calendar.ZoneInfoFile works with the default security
+ * manager.
+ */
+
+import java.io.File;
+import java.util.*;
+
+public class Bug6912560 {
+    public static void main(String[] args) {
+        // set the user.timezone property
+        String tzname = "Asia/Tokyo";
+        System.setProperty("user.timezone", tzname);
+
+        System.setSecurityManager(new SecurityManager());
+        TimeZone tz = TimeZone.getDefault();
+        if (!tzname.equals(tz.getID())) {
+            throw new RuntimeException("got " + tz.getID()
+                                       + ", expected " + tzname);
+        }
+    }
+}
--- a/test/java/util/concurrent/forkjoin/Integrate.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/java/util/concurrent/forkjoin/Integrate.java	Fri Sep 24 16:41:32 2010 -0700
@@ -206,7 +206,7 @@
             q.fork();
             ar = recEval(c, r, fc, fr, ar);
             if (!q.tryUnfork()) {
-                q.quietlyHelpJoin();
+                q.quietlyJoin();
                 return ar + q.area;
             }
             return ar + recEval(l, c, fl, fc, al);
@@ -254,7 +254,7 @@
                 (q = new DQuad(l, c, al)).fork();
             ar = recEval(c, r, fc, fr, ar);
             if (q != null && !q.tryUnfork()) {
-                q.quietlyHelpJoin();
+                q.quietlyJoin();
                 return ar + q.area;
             }
             return ar + recEval(l, c, fl, fc, al);
--- a/test/javax/imageio/CachePremissionsTest/CachePermissionsTest.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/javax/imageio/CachePremissionsTest/CachePermissionsTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -50,9 +50,9 @@
  *           -Djava.security.debug=access can be used to verify file permissions.
  *
  * @run     main CachePermissionsTest true
- * @run     main/othervm/policy=w.policy CachePermissionsTest false
- * @run     main/othervm/policy=rw.policy CachePermissionsTest false
- * @run     main/othervm/policy=rwd.policy CachePermissionsTest true
+ * @run     main/othervm CachePermissionsTest false w.policy
+ * @run     main/othervm CachePermissionsTest false rw.policy
+ * @run     main/othervm CachePermissionsTest true rwd.policy
  */
 
 import java.io.File;
@@ -73,6 +73,17 @@
 
         System.out.println("java.io.tmpdir is " + System.getProperty("java.io.tmpdir"));
 
+        if (args.length > 1) {
+            String testsrc = System.getProperty("test.src", ".");
+            String policy = testsrc + File.separator + args[1];
+
+            System.out.println("Policy file: " + policy);
+            System.setProperty("java.security.policy", policy);
+
+            System.out.println("Install security manager...");
+            System.setSecurityManager(new SecurityManager());
+        }
+
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
         try {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/AudioFloatFormatConverter/SkipTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ @summary Test skip method returned from AudioFloatFormatConverter.getAudioInputStream */
+
+import java.io.ByteArrayInputStream;
+
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
+
+import com.sun.media.sound.AudioFloatFormatConverter;
+
+public class SkipTest {
+
+    public static void main(String[] args) throws Exception {
+        AudioFloatFormatConverter converter = new AudioFloatFormatConverter();
+        byte[] data = { 10, 20, 30, 40, 30, 20, 10 };
+        AudioFormat format = new AudioFormat(8000, 8, 1, true, false);
+        AudioFormat format2 = new AudioFormat(16000, 8, 1, true, false);
+        AudioInputStream ais = new AudioInputStream(new ByteArrayInputStream(
+                data), format, data.length);
+        AudioInputStream ais2 = converter.getAudioInputStream(format2, ais);
+        byte[] data2 = new byte[30];
+        int ret = ais2.read(data2, 0, data2.length);
+        ais.reset();
+        AudioInputStream ais3 = converter.getAudioInputStream(format2, ais);
+        byte[] data3 = new byte[100];
+        ais3.skip(7);
+        int ret2 = ais3.read(data3, 7, data3.length);
+        if (ret2 != ret - 7)
+            throw new Exception("Skip doesn't work correctly (" + ret2 + " != "
+                    + (ret - 7) + ")");
+        for (int i = 7; i < ret2 + 7; i++) {
+            if (data3[i] != data2[i])
+                throw new Exception("Skip doesn't work correctly (" + data3[i]
+                        + " != " + data2[i] + ")");
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/ModelByteBufferWavetable/OpenStream.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ @summary Test AudioFloatInputStream.getFrameLength() returned from
+ ModelByteBufferWavetable openStream method */
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+
+import javax.sound.sampled.*;
+
+import com.sun.media.sound.*;
+
+public class OpenStream {
+
+    static float[] testarray;
+
+    static byte[] test_byte_array;
+
+    static byte[] test_byte_array_8ext;
+
+    static AudioFormat format = new AudioFormat(44100, 16, 1, true, false);
+
+    static AudioFormat format24 = new AudioFormat(44100, 24, 1, true, false);
+
+    static ModelByteBuffer buffer;
+
+    static ModelByteBuffer buffer_wave;
+
+    static ModelByteBuffer buffer8;
+
+    static ModelByteBuffer buffer16_8;
+
+    static ModelByteBuffer buffer24;
+
+    static File test_file;
+
+    static ModelByteBuffer buffer_wave_ondisk;
+
+    static void setUp() throws Exception {
+        testarray = new float[1024];
+        for (int i = 0; i < 1024; i++) {
+            double ii = i / 1024.0;
+            ii = ii * ii;
+            testarray[i] = (float) Math.sin(10 * ii * 2 * Math.PI);
+            testarray[i] += (float) Math.sin(1.731 + 2 * ii * 2 * Math.PI);
+            testarray[i] += (float) Math.sin(0.231 + 6.3 * ii * 2 * Math.PI);
+            testarray[i] *= 0.3;
+        }
+        test_byte_array = new byte[testarray.length * 2];
+        AudioFloatConverter.getConverter(format).toByteArray(testarray,
+                test_byte_array);
+        buffer = new ModelByteBuffer(test_byte_array);
+
+        byte[] test_byte_array2 = new byte[testarray.length * 3];
+        buffer24 = new ModelByteBuffer(test_byte_array2);
+        test_byte_array_8ext = new byte[testarray.length];
+        byte[] test_byte_array_8_16 = new byte[testarray.length * 2];
+        AudioFloatConverter.getConverter(format24).toByteArray(testarray,
+                test_byte_array2);
+        int ix = 0;
+        int x = 0;
+        for (int i = 0; i < test_byte_array_8ext.length; i++) {
+            test_byte_array_8ext[i] = test_byte_array2[ix++];
+            test_byte_array_8_16[x++] = test_byte_array2[ix++];
+            test_byte_array_8_16[x++] = test_byte_array2[ix++];
+        }
+        buffer16_8 = new ModelByteBuffer(test_byte_array_8_16);
+        buffer8 = new ModelByteBuffer(test_byte_array_8ext);
+
+        AudioInputStream ais = new AudioInputStream(buffer.getInputStream(),
+                format, testarray.length);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        AudioSystem.write(ais, AudioFileFormat.Type.WAVE, baos);
+        buffer_wave = new ModelByteBuffer(baos.toByteArray());
+
+        test_file = File.createTempFile("test", ".raw");
+        FileOutputStream fos = new FileOutputStream(test_file);
+        fos.write(baos.toByteArray());
+        fos.close();
+        buffer_wave_ondisk = new ModelByteBuffer(test_file);
+
+    }
+
+    static void tearDown() throws Exception {
+        if (!test_file.delete())
+            test_file.deleteOnExit();
+    }
+
+    public static void testOpenStream(ModelByteBufferWavetable wavetable)
+            throws Exception {
+        AudioFloatInputStream ais = wavetable.openStream();
+        long frames = wavetable.getBuffer().capacity()
+                / wavetable.getFormat().getFrameSize();
+        long framelength = ais.getFrameLength();
+        ais.close();
+        if (frames != framelength) {
+            throw new Exception("Incorrect framelength returned (" + frames
+                    + " != " + framelength + ")");
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        setUp();
+
+        try {
+            testOpenStream(new ModelByteBufferWavetable(buffer, format));
+            testOpenStream(new ModelByteBufferWavetable(buffer_wave, format));
+            testOpenStream(new ModelByteBufferWavetable(buffer_wave_ondisk,
+                    format));
+        } finally {
+            tearDown();
+        }
+
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/ModelStandardIndexedDirector/ModelStandardIndexedDirectorTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+   @summary Test ModelStandardIndexedDirector class */
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.TreeSet;
+
+import com.sun.media.sound.ModelConnectionBlock;
+import com.sun.media.sound.ModelDirectedPlayer;
+import com.sun.media.sound.ModelPerformer;
+import com.sun.media.sound.ModelStandardDirector;
+import com.sun.media.sound.ModelStandardIndexedDirector;
+
+public class ModelStandardIndexedDirectorTest {
+
+    private static String treeToString(TreeSet<Integer> set)
+    {
+        StringBuffer buff = new StringBuffer();
+        boolean first = true;
+        for(Integer s : set)
+        {
+            if(!first)
+                buff.append(";");
+            buff.append(s);
+            first = false;
+        }
+        return buff.toString();
+    }
+
+    private static void testDirector(ModelPerformer[] performers) throws Exception
+    {
+        final TreeSet<Integer> played = new TreeSet<Integer>();
+        ModelDirectedPlayer player = new ModelDirectedPlayer()
+        {
+            public void play(int performerIndex,
+                    ModelConnectionBlock[] connectionBlocks) {
+                played.add(performerIndex);
+            }
+        };
+        ModelStandardIndexedDirector idirector =
+            new ModelStandardIndexedDirector(performers, player);
+        ModelStandardDirector director =
+            new ModelStandardDirector(performers, player);
+
+        for (int n = 0; n < 128; n++)
+        {
+            for (int v = 0; v < 128; v++)
+            {
+                director.noteOn(n, v);
+                String p1 = treeToString(played);
+                played.clear();
+                idirector.noteOn(n, v);
+                String p2 = treeToString(played);
+                played.clear();
+                if(!p1.equals(p2))
+                    throw new Exception(
+                            "Note = " + n + ", Vel = " + v + " failed");
+            }
+        }
+    }
+
+    private static void testDirectorCombinations(
+            ModelPerformer[] performers) throws Exception
+    {
+        for (int i = 0; i < performers.length; i++) {
+            ModelPerformer[] performers2 = new ModelPerformer[i];
+            for (int j = 0; j < performers2.length; j++) {
+                performers2[j] = performers[i];
+            }
+            testDirector(performers2);
+        }
+    }
+
+    private static void addPerformer(
+            List<ModelPerformer> performers,
+            int keyfrom,
+            int keyto,
+            int velfrom,
+            int velto)
+    {
+        ModelPerformer performer = new ModelPerformer();
+        performer.setKeyFrom(keyfrom);
+        performer.setKeyTo(keyto);
+        performer.setVelFrom(velfrom);
+        performer.setVelTo(velto);
+        performers.add(performer);
+    }
+
+    public static void main(String[] args) throws Exception
+    {
+        // Test collection of normal values
+        List<ModelPerformer> performers = new ArrayList<ModelPerformer>();
+        addPerformer(performers, 0, 0, 0, 127);
+        addPerformer(performers, 0, 50, 0, 127);
+        addPerformer(performers, 0, 127, 0, 127);
+        addPerformer(performers, 21, 21, 0, 127);
+        addPerformer(performers, 21, 60, 0, 127);
+        addPerformer(performers, 21, 127, 0, 127);
+        addPerformer(performers, 50, 50, 0, 127);
+        addPerformer(performers, 50, 60, 0, 127);
+        addPerformer(performers, 50, 127, 0, 127);
+        addPerformer(performers, 73, 73, 0, 127);
+        addPerformer(performers, 73, 80, 0, 127);
+        addPerformer(performers, 73, 127, 0, 127);
+        addPerformer(performers, 127, 127, 0, 127);
+        addPerformer(performers, 0, 0, 60, 127);
+        addPerformer(performers, 0, 50, 60, 127);
+        addPerformer(performers, 0, 127, 60, 127);
+        addPerformer(performers, 21, 21, 60, 127);
+        addPerformer(performers, 21, 60, 60, 127);
+        addPerformer(performers, 21, 127, 60, 127);
+        addPerformer(performers, 50, 50, 60, 127);
+        addPerformer(performers, 50, 60, 60, 127);
+        addPerformer(performers, 50, 127, 60, 127);
+        addPerformer(performers, 73, 73, 60, 127);
+        addPerformer(performers, 73, 80, 60, 127);
+        addPerformer(performers, 73, 127, 60, 127);
+        addPerformer(performers, 127, 127, 60, 127);
+        addPerformer(performers, 0, 0, 80, 83);
+        addPerformer(performers, 0, 50, 80, 83);
+        addPerformer(performers, 0, 127, 80, 83);
+        addPerformer(performers, 21, 21, 80, 83);
+        addPerformer(performers, 21, 60, 80, 83);
+        addPerformer(performers, 21, 127, 80, 83);
+        addPerformer(performers, 50, 50, 80, 83);
+        addPerformer(performers, 50, 60, 80, 83);
+        addPerformer(performers, 50, 127, 80, 83);
+        addPerformer(performers, 73, 73, 80, 83);
+        addPerformer(performers, 73, 80, 80, 83);
+        addPerformer(performers, 73, 127, 80, 83);
+        addPerformer(performers, 127, 127, 80, 83);
+
+
+        testDirectorCombinations(
+                performers.toArray(
+                        new ModelPerformer[performers.size()])
+                );
+
+        // Test reversed values
+        performers.clear();
+        addPerformer(performers, 50, 30, 80, 83);
+        addPerformer(performers, 30, 30, 50, 30);
+        addPerformer(performers, 37, 30, 50, 30);
+        testDirector(
+                performers.toArray(
+                        new ModelPerformer[performers.size()])
+                );
+
+        // Test out-of-range values
+        performers.clear();
+        addPerformer(performers, -20, 6, 0, 127);
+        addPerformer(performers, 0, 300, 0, 300);
+        addPerformer(performers, -2, -8, -5, -9);
+
+        testDirector(
+                performers.toArray(
+                        new ModelPerformer[performers.size()])
+                );
+
+    }
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/SoftChannel/ProgramAndBankChange.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+   @summary Test SoftChannel program and bank change */
+
+import java.io.IOException;
+
+import javax.sound.midi.*;
+import javax.sound.sampled.*;
+
+import com.sun.media.sound.*;
+
+public class ProgramAndBankChange {
+
+    private static SimpleInstrument generateTestInstrument(Patch patch) {
+        ModelOscillator osc = new ModelOscillator() {
+            public float getAttenuation() {
+                return 0;
+            }
+
+            public int getChannels() {
+                return 1;
+            }
+
+            public ModelOscillatorStream open(float samplerate) {
+                return new ModelOscillatorStream() {
+                    public void close() throws IOException {
+                    }
+
+                    public void noteOff(int velocity) {
+                    }
+
+                    public void noteOn(MidiChannel channel, VoiceStatus voice,
+                            int noteNumber, int velocity) {
+                    }
+
+                    public int read(float[][] buffer, int offset, int len)
+                            throws IOException {
+                        return len;
+                    }
+
+                    public void setPitch(float ipitch) {
+                    }
+                };
+            }
+        };
+        ModelPerformer performer = new ModelPerformer();
+        performer.getOscillators().add(osc);
+        SimpleInstrument testinstrument = new SimpleInstrument();
+        testinstrument.setPatch(patch);
+        testinstrument.add(performer);
+        return testinstrument;
+    }
+
+    private static void assertTrue(boolean value) throws Exception {
+        if (!value)
+            throw new RuntimeException("assertTrue fails!");
+    }
+
+    private static void testProgramAndBank(SoftSynthesizer soft,
+            AudioInputStream stream, Patch patch) throws Exception {
+
+        int program = patch.getProgram();
+        int bank = patch.getBank();
+
+        MidiChannel channel = soft.getChannels()[0];
+        byte[] buff = new byte[2048];
+
+        channel.programChange(bank, program);
+        channel.noteOn(64, 64);
+        stream.read(buff, 0, buff.length);
+
+        int foundprogram = -1;
+        int foundbank = -1;
+        VoiceStatus[] vstatus = soft.getVoiceStatus();
+        for (int i = 0; i < vstatus.length; i++) {
+            if (vstatus[i].active) {
+                foundprogram = vstatus[i].program;
+                foundbank = vstatus[i].bank;
+                break;
+            }
+        }
+
+        assertTrue(foundprogram == program);
+        assertTrue(foundbank == bank);
+
+        channel.noteOn(64, 0);
+        stream.read(buff, 0, buff.length);
+
+        channel = soft.getChannels()[1];
+        // Send MSB Bank
+        channel.controlChange(0x00, bank / 128);
+        // Send LSB Bank
+        channel.controlChange(0x20, bank % 128);
+        // Send Program Change
+        channel.programChange(program);
+        channel.noteOn(64, 64);
+        stream.read(buff, 0, buff.length);
+
+        foundprogram = -1;
+        foundbank = -1;
+        vstatus = soft.getVoiceStatus();
+        for (int i = 0; i < vstatus.length; i++) {
+            if (vstatus[i].active) {
+                foundprogram = vstatus[i].program;
+                foundbank = vstatus[i].bank;
+                break;
+            }
+        }
+        assertTrue(foundprogram == program);
+        assertTrue(foundbank == bank);
+        channel.noteOn(64, 0);
+        stream.read(buff, 0, buff.length);
+    }
+
+    public static void main(String[] args) throws Exception {
+        SoftSynthesizer soft = new SoftSynthesizer();
+        AudioInputStream stream = soft.openStream(null, null);
+        soft.unloadAllInstruments(soft.getDefaultSoundbank());
+
+        soft.loadInstrument(generateTestInstrument(new Patch(0, 0)));
+        soft.loadInstrument(generateTestInstrument(new Patch(7, 0)));
+        soft.loadInstrument(generateTestInstrument(new Patch(20, 10)));
+        soft.loadInstrument(generateTestInstrument(new Patch(3678, 15)));
+        soft.loadInstrument(generateTestInstrument(new Patch(4678, 15)));
+
+        testProgramAndBank(soft, stream, new Patch(0, 0));
+        testProgramAndBank(soft, stream, new Patch(7, 0));
+        testProgramAndBank(soft, stream, new Patch(20, 10));
+        testProgramAndBank(soft, stream, new Patch(3678, 15));
+        testProgramAndBank(soft, stream, new Patch(4678, 15));
+
+        soft.close();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/GetAvailableInstruments2.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ @summary Test SoftSynthesizer getAvailableInstruments method */
+
+import javax.sound.midi.MidiDevice;
+import javax.sound.midi.MidiUnavailableException;
+import javax.sound.midi.Patch;
+import javax.sound.midi.Soundbank;
+import javax.sound.sampled.*;
+import javax.sound.midi.MidiDevice.Info;
+
+import com.sun.media.sound.*;
+
+public class GetAvailableInstruments2 {
+
+    private static void assertEquals(Object a, Object b) throws Exception {
+        if (!a.equals(b))
+            throw new RuntimeException("assertEquals fails!");
+    }
+
+    private static void assertTrue(boolean value) throws Exception {
+        if (!value)
+            throw new RuntimeException("assertTrue fails!");
+    }
+
+    public static void main(String[] args) throws Exception {
+        AudioSynthesizer synth = new SoftSynthesizer();
+        synth.openStream(null, null);
+        Soundbank defsbk = synth.getDefaultSoundbank();
+        if (defsbk != null) {
+            synth.unloadAllInstruments(defsbk);
+            assertTrue(defsbk.getInstruments().length == synth
+                    .getAvailableInstruments().length);
+        }
+        synth.close();
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/GetLoadedInstruments2.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ @summary Test SoftSynthesizer getLoadedInstruments method */
+
+import javax.sound.midi.MidiDevice;
+import javax.sound.midi.MidiUnavailableException;
+import javax.sound.midi.Patch;
+import javax.sound.midi.Soundbank;
+import javax.sound.sampled.*;
+import javax.sound.midi.MidiDevice.Info;
+
+import com.sun.media.sound.*;
+
+public class GetLoadedInstruments2 {
+
+    private static void assertEquals(Object a, Object b) throws Exception {
+        if (!a.equals(b))
+            throw new RuntimeException("assertEquals fails!");
+    }
+
+    private static void assertTrue(boolean value) throws Exception {
+        if (!value)
+            throw new RuntimeException("assertTrue fails!");
+    }
+
+    public static void main(String[] args) throws Exception {
+        AudioSynthesizer synth = new SoftSynthesizer();
+        synth.openStream(null, null);
+        Soundbank defsbk = synth.getDefaultSoundbank();
+        if (defsbk != null) {
+            assertTrue(defsbk.getInstruments().length == synth
+                    .getLoadedInstruments().length);
+        }
+        synth.close();
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/GetPropertyInfo.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ @summary Test SoftSynthesizer getPropertyInfo method */
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.sound.midi.MidiDevice;
+import javax.sound.midi.MidiUnavailableException;
+import javax.sound.midi.Patch;
+import javax.sound.midi.Soundbank;
+import javax.sound.sampled.*;
+import javax.sound.sampled.AudioFormat.Encoding;
+import javax.sound.midi.MidiDevice.Info;
+
+import com.sun.media.sound.*;
+
+public class GetPropertyInfo {
+
+    private static void assertTrue(boolean value) throws Exception {
+        if (!value)
+            throw new RuntimeException("assertTrue fails!");
+    }
+
+    public static void main(String[] args) throws Exception {
+        SoftSynthesizer synth = new SoftSynthesizer();
+        Map<String, Object> p = new HashMap<String, Object>();
+        p.put("format", "8000 HZ 24 BIT MONO UNSIGNED BIG-ENDIAN");
+        p.put("control rate", 125);
+        p.put("reverb", false);
+        p.put("auto gain control", "false");
+        AudioSynthesizerPropertyInfo[] ap = synth.getPropertyInfo(p);
+        for (int i = 0; i < ap.length; i++) {
+            if (ap[i].name.equals("control rate"))
+                assertTrue(Math.abs((Float) ap[i].value - 125.0) < 0.001);
+            if (ap[i].name.equals("reverb"))
+                assertTrue((Boolean) ap[i].value == false);
+            if (ap[i].name.equals("auto gain control"))
+                assertTrue((Boolean) ap[i].value == false);
+            if (ap[i].name.equals("format")) {
+                AudioFormat format = (AudioFormat) ap[i].value;
+                assertTrue(format.getChannels() == 1);
+                assertTrue(format.getSampleSizeInBits() == 24);
+                assertTrue(format.isBigEndian());
+                assertTrue(Math.abs(format.getSampleRate() - 8000) < 0.001);
+                assertTrue(format.getEncoding() == Encoding.PCM_UNSIGNED);
+            }
+        }
+        p = new HashMap<String, Object>();
+        p.put("format", "9000 Hz, 8 bit, 4 channels");
+        ap = synth.getPropertyInfo(p);
+        for (int i = 0; i < ap.length; i++) {
+            if (ap[i].name.equals("format")) {
+                AudioFormat format = (AudioFormat) ap[i].value;
+                assertTrue(format.getChannels() == 4);
+                assertTrue(format.getSampleSizeInBits() == 8);
+                assertTrue(!format.isBigEndian());
+                assertTrue(Math.abs(format.getSampleRate() - 9000) < 0.001);
+                assertTrue(format.getEncoding() == Encoding.PCM_SIGNED);
+            }
+        }
+
+        p = new HashMap<String, Object>();
+        p.put("format", "PCM_UNSIGNED 44100.0 Hz, 16 bit, 3 channels, 6 bytes/frame, big-endian");
+        ap = synth.getPropertyInfo(p);
+        for (int i = 0; i < ap.length; i++) {
+            if (ap[i].name.equals("format")) {
+                AudioFormat format = (AudioFormat) ap[i].value;
+                assertTrue(format.getChannels() == 3);
+                assertTrue(format.getSampleSizeInBits() == 16);
+                assertTrue(format.isBigEndian());
+                assertTrue(Math.abs(format.getSampleRate() - 44100) < 0.001);
+                assertTrue(format.getEncoding() == Encoding.PCM_UNSIGNED);
+            }
+        }
+
+
+    }
+}
--- a/test/javax/sound/midi/Gervill/SoftSynthesizer/LoadAllInstruments.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/LoadAllInstruments.java	Fri Sep 24 16:41:32 2010 -0700
@@ -55,7 +55,6 @@
         Soundbank defsbk = synth.getDefaultSoundbank();
         if(defsbk != null)
         {
-            assertTrue(synth.getLoadedInstruments().length == 0);
             synth.unloadAllInstruments(defsbk);
             SimpleSoundbank sbk = new SimpleSoundbank();
             SimpleInstrument ins = new SimpleInstrument();
--- a/test/javax/sound/midi/Gervill/SoftSynthesizer/LoadInstrument.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/LoadInstrument.java	Fri Sep 24 16:41:32 2010 -0700
@@ -55,7 +55,6 @@
         Soundbank defsbk = synth.getDefaultSoundbank();
         if(defsbk != null)
         {
-            assertTrue(synth.getLoadedInstruments().length == 0);
             synth.unloadAllInstruments(defsbk);
             SimpleSoundbank sbk = new SimpleSoundbank();
             SimpleInstrument ins = new SimpleInstrument();
--- a/test/javax/sound/midi/Gervill/SoftSynthesizer/LoadInstruments.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/LoadInstruments.java	Fri Sep 24 16:41:32 2010 -0700
@@ -55,7 +55,6 @@
         Soundbank defsbk = synth.getDefaultSoundbank();
         if(defsbk != null)
         {
-            assertTrue(synth.getLoadedInstruments().length == 0);
             synth.unloadAllInstruments(defsbk);
             SimpleSoundbank sbk = new SimpleSoundbank();
             SimpleInstrument ins = new SimpleInstrument();
--- a/test/javax/sound/midi/Gervill/SoftSynthesizer/RemapInstrument.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/RemapInstrument.java	Fri Sep 24 16:41:32 2010 -0700
@@ -56,15 +56,15 @@
         Soundbank defsbk = synth.getDefaultSoundbank();
         if(defsbk != null)
         {
-            Instrument ins0 = defsbk.getInstrument(new Patch(0,0));
+            Instrument ins3 = defsbk.getInstrument(new Patch(0,3));
             Instrument ins10 = defsbk.getInstrument(new Patch(0,10));
-            assertTrue(synth.remapInstrument(ins0, ins10));
+            assertTrue(synth.remapInstrument(ins3, ins10));
             Instrument[] loaded = synth.getLoadedInstruments();
             for (int i = 0; i < loaded.length; i++) {
-                if(loaded[i].getPatch().getBank() == 0)
-                if(loaded[i].getPatch().getProgram() == 10)
+                if(loaded[i].getPatch().getBank() == ins3.getPatch().getBank())
+                if(loaded[i].getPatch().getProgram() == ins3.getPatch().getProgram())
                 {
-                    assertEquals(loaded[i].getName(), ins0.getName());
+                    assertEquals(loaded[i].getName(), ins10.getName());
                     break;
                 }
             }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/TestDisableLoadDefaultSoundbank.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ @summary Test Disable/enable loading default soundbank in SoftSynthesizer */
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.sound.midi.MidiDevice;
+import javax.sound.midi.MidiUnavailableException;
+import javax.sound.midi.Patch;
+import javax.sound.midi.Soundbank;
+import javax.sound.sampled.*;
+import javax.sound.midi.MidiDevice.Info;
+
+import com.sun.media.sound.*;
+
+public class TestDisableLoadDefaultSoundbank {
+
+    private static void assertEquals(Object a, Object b) throws Exception {
+        if (!a.equals(b))
+            throw new RuntimeException("assertEquals fails!");
+    }
+
+    private static void assertTrue(boolean value) throws Exception {
+        if (!value)
+            throw new RuntimeException("assertTrue fails!");
+    }
+
+    public static void main(String[] args) throws Exception {
+        AudioSynthesizer synth = new SoftSynthesizer();
+        synth.openStream(null, null);
+        Soundbank defsbk = synth.getDefaultSoundbank();
+        if (defsbk != null) {
+            assertTrue(defsbk.getInstruments().length == synth
+                    .getLoadedInstruments().length);
+        }
+        synth.close();
+        Map<String, Object> p = new HashMap<String, Object>();
+        p.put("load default soundbank", false);
+        synth.openStream(null, p);
+        if (defsbk != null) {
+            assertTrue(synth.getLoadedInstruments().length == 0);
+        }
+        synth.close();
+
+    }
+}
--- a/test/javax/sound/midi/Gervill/SoftSynthesizer/UnloadAllInstruments.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/UnloadAllInstruments.java	Fri Sep 24 16:41:32 2010 -0700
@@ -55,9 +55,8 @@
         Soundbank defsbk = synth.getDefaultSoundbank();
         if(defsbk != null)
         {
+            synth.unloadAllInstruments(defsbk);
             assertTrue(synth.getLoadedInstruments().length == 0);
-            synth.unloadAllInstruments(defsbk);
-            assertTrue(synth.getAvailableInstruments().length == 0);
             synth.loadAllInstruments(defsbk);
             assertTrue(synth.getLoadedInstruments().length != 0);
             synth.unloadAllInstruments(defsbk);
--- a/test/javax/sound/midi/Gervill/SoftSynthesizer/UnloadInstrument.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/UnloadInstrument.java	Fri Sep 24 16:41:32 2010 -0700
@@ -55,7 +55,6 @@
         Soundbank defsbk = synth.getDefaultSoundbank();
         if(defsbk != null)
         {
-            assertTrue(synth.getLoadedInstruments().length == 0);
             synth.unloadAllInstruments(defsbk);
             SimpleSoundbank sbk = new SimpleSoundbank();
             SimpleInstrument ins = new SimpleInstrument();
--- a/test/javax/sound/midi/Gervill/SoftSynthesizer/UnloadInstruments.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/javax/sound/midi/Gervill/SoftSynthesizer/UnloadInstruments.java	Fri Sep 24 16:41:32 2010 -0700
@@ -55,7 +55,6 @@
         Soundbank defsbk = synth.getDefaultSoundbank();
         if(defsbk != null)
         {
-            assertTrue(synth.getLoadedInstruments().length == 0);
             synth.unloadAllInstruments(defsbk);
             SimpleSoundbank sbk = new SimpleSoundbank();
             SimpleInstrument ins = new SimpleInstrument();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/Gervill/SoftTuning/RealTimeTuning.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ @summary Test RealTime-tunings using SoftReciver.send method */
+
+import java.io.IOException;
+
+import javax.sound.midi.*;
+import javax.sound.sampled.*;
+
+import com.sun.media.sound.*;
+
+public class RealTimeTuning {
+
+    private static class PitchSpy {
+        public float pitch = 0;
+
+        public Soundbank getSoundBank() {
+            ModelOscillator osc = new ModelOscillator() {
+                public float getAttenuation() {
+                    return 0;
+                }
+
+                public int getChannels() {
+                    return 0;
+                }
+
+                public ModelOscillatorStream open(float samplerate) {
+                    return new ModelOscillatorStream() {
+                        public void close() throws IOException {
+                            pitch = 0;
+                        }
+
+                        public void noteOff(int velocity) {
+                            pitch = 0;
+                        }
+
+                        public void noteOn(MidiChannel channel,
+                                VoiceStatus voice, int noteNumber, int velocity) {
+                            pitch = noteNumber * 100;
+                        }
+
+                        public int read(float[][] buffer, int offset, int len)
+                                throws IOException {
+                            return len;
+                        }
+
+                        public void setPitch(float ipitch) {
+                            pitch = ipitch;
+                        }
+                    };
+                }
+            };
+            ModelPerformer performer = new ModelPerformer();
+            performer.getOscillators().add(osc);
+            SimpleInstrument testinstrument = new SimpleInstrument();
+            testinstrument.setPatch(new Patch(0, 0));
+            testinstrument.add(performer);
+            SimpleSoundbank testsoundbank = new SimpleSoundbank();
+            testsoundbank.addInstrument(testinstrument);
+            return testsoundbank;
+        }
+    }
+
+    public static void sendTuningChange(Receiver recv, int channel,
+            int tuningpreset, int tuningbank) throws InvalidMidiDataException {
+        // Data Entry
+        ShortMessage sm1 = new ShortMessage();
+        sm1.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x64, 04);
+        ShortMessage sm2 = new ShortMessage();
+        sm2.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x65, 00);
+
+        // Tuning Bank
+        ShortMessage sm3 = new ShortMessage();
+        sm3.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x06, tuningbank);
+        // Data Increment
+        ShortMessage sm4 = new ShortMessage();
+        sm4.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x60, 0x7F);
+        // Data Decrement
+        ShortMessage sm5 = new ShortMessage();
+        sm5.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x61, 0x7F);
+
+        // Data Entry
+        ShortMessage sm6 = new ShortMessage();
+        sm6.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x64, 03);
+        ShortMessage sm7 = new ShortMessage();
+        sm7.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x65, 00);
+
+        // Tuning program
+        ShortMessage sm8 = new ShortMessage();
+        sm8
+                .setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x06,
+                        tuningpreset);
+        // Data Increment
+        ShortMessage sm9 = new ShortMessage();
+        sm9.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x60, 0x7F);
+        // Data Decrement
+        ShortMessage sm10 = new ShortMessage();
+        sm10.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x61, 0x7F);
+
+        recv.send(sm1, -1);
+        recv.send(sm2, -1);
+        recv.send(sm3, -1);
+        recv.send(sm4, -1);
+        recv.send(sm5, -1);
+        recv.send(sm6, -1);
+        recv.send(sm7, -1);
+        recv.send(sm8, -1);
+        recv.send(sm9, -1);
+        recv.send(sm10, -1);
+
+    }
+
+    private static void assertTrue(boolean value) throws Exception {
+        if (!value)
+            throw new RuntimeException("assertTrue fails!");
+    }
+
+    public static void testTunings(int[] msg, int tuningProgram,
+            int tuningBank, int targetNote, float targetPitch, boolean realtime)
+            throws Exception {
+        AudioSynthesizer synth = new SoftSynthesizer();
+        AudioInputStream stream = synth.openStream(null, null);
+        Receiver recv = synth.getReceiver();
+        MidiChannel channel = synth.getChannels()[0];
+        byte[] buff = new byte[2048];
+
+        // Create test instrument which we can use to monitor pitch changes
+        PitchSpy pitchspy = new PitchSpy();
+
+        synth.unloadAllInstruments(synth.getDefaultSoundbank());
+        synth.loadAllInstruments(pitchspy.getSoundBank());
+
+        SysexMessage sysex = null;
+
+        // Send tuning changes
+        if (msg != null) {
+            byte[] bmsg = new byte[msg.length];
+            for (int i = 0; i < bmsg.length; i++)
+                bmsg[i] = (byte) msg[i];
+            sysex = new SysexMessage();
+            sysex.setMessage(bmsg, bmsg.length);
+            if (targetPitch == 0) {
+                targetPitch = (float) new SoftTuning(bmsg)
+                        .getTuning(targetNote);
+                // Check if targetPitch != targetNote * 100
+                assertTrue(Math.abs(targetPitch - targetNote * 100.0) > 0.001);
+            }
+        }
+
+        if (tuningProgram != -1)
+            sendTuningChange(recv, 0, tuningProgram, tuningBank);
+
+        // First test without tunings
+        channel.noteOn(targetNote, 64);
+        stream.read(buff, 0, buff.length);
+        assertTrue(Math.abs(pitchspy.pitch - (targetNote * 100.0)) < 0.001);
+
+        // Test if realtime/non-realtime works
+        if (sysex != null)
+            recv.send(sysex, -1);
+        stream.read(buff, 0, buff.length);
+        if (realtime)
+            assertTrue(Math.abs(pitchspy.pitch - targetPitch) < 0.001);
+        else
+            assertTrue(Math.abs(pitchspy.pitch - (targetNote * 100.0)) < 0.001);
+
+        // Test if tunings works
+        channel.noteOn(targetNote, 0);
+        stream.read(buff, 0, buff.length);
+        assertTrue(Math.abs(pitchspy.pitch - 0.0) < 0.001);
+
+        channel.noteOn(targetNote, 64);
+        stream.read(buff, 0, buff.length);
+        assertTrue(Math.abs(pitchspy.pitch - targetPitch) < 0.001);
+
+        channel.noteOn(targetNote, 0);
+        stream.read(buff, 0, buff.length);
+        assertTrue(Math.abs(pitchspy.pitch - 0.0) < 0.001);
+
+        stream.close();
+    }
+
+    public static void main(String[] args) throws Exception {
+        // Test with no-tunings
+        testTunings(null, -1, -1, 60, 6000, false);
+
+        int[] msg;
+        // 0x02 SINGLE NOTE TUNING CHANGE (REAL-TIME)
+        msg = new int[] { 0xf0, 0x7f, 0x7f, 0x08, 0x02, 0x10, 0x02, 36, 36, 64,
+                0, 60, 70, 0, 0, 0xf7 };
+        testTunings(msg, 0x10, 0, 60, 7000, true);
+
+        // 0x07 SINGLE NOTE TUNING CHANGE (NON REAL-TIME) (BANK)
+        msg = new int[] { 0xf0, 0x7e, 0x7f, 0x08, 0x07, 0x05, 0x07, 0x02, 36,
+                36, 64, 0, 60, 80, 0, 0, 0xf7 };
+        testTunings(msg, 0x07, 0x05, 60, 8000, false);
+
+        // 0x07 SINGLE NOTE TUNING CHANGE (REAL-TIME) (BANK)
+        msg = new int[] { 0xf0, 0x7f, 0x7f, 0x08, 0x07, 0x05, 0x07, 0x02, 36,
+                36, 64, 0, 60, 80, 0, 0, 0xf7 };
+        testTunings(msg, 0x07, 0x05, 60, 8000, true);
+
+        // 0x08 scale/octave tuning 1-byte form (Non Real-Time)
+        msg = new int[] { 0xf0, 0x7e, 0x7f, 0x08, 0x08, 0x03, 0x7f, 0x7f, 5,
+                10, 15, 20, 25, 30, 35, 40, 45, 50, 51, 52, 0xf7 };
+        testTunings(msg, -1, -1, 60, 0, false);
+
+        // 0x08 scale/octave tuning 1-byte form (REAL-TIME)
+        msg = new int[] { 0xf0, 0x7f, 0x7f, 0x08, 0x08, 0x03, 0x7f, 0x7f, 5,
+                10, 15, 20, 25, 30, 35, 40, 45, 50, 51, 52, 0xf7 };
+        testTunings(msg, -1, -1, 60, 0, true);
+
+        // 0x09 scale/octave tuning 2-byte form (Non Real-Time)
+        msg = new int[] { 0xf0, 0x7e, 0x7f, 0x08, 0x09, 0x03, 0x7f, 0x7f, 5,
+                10, 15, 20, 25, 30, 35, 40, 45, 50, 51, 52, 5, 10, 15, 20, 25,
+                30, 35, 40, 45, 50, 51, 52, 0xf7 };
+        testTunings(msg, -1, -1, 60, 0, false);
+
+        // 0x09 scale/octave tuning 2-byte form (REAL-TIME)
+        msg = new int[] { 0xf0, 0x7f, 0x7f, 0x08, 0x09, 0x03, 0x7f, 0x7f, 5,
+                10, 15, 20, 25, 30, 35, 40, 45, 50, 51, 52, 5, 10, 15, 20, 25,
+                30, 35, 40, 45, 50, 51, 52, 0xf7 };
+        testTunings(msg, -1, -1, 60, 0, true);
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 4933700
+ * @summary Tests that default devices return MidiDeviceTransmitter/Receiver and returned objects return correct MidiDevice
+ * @compile -source 1.7 TestAllDevices.java
+ * @run main TestAllDevices
+ * @author Alex Menkov
+ */
+
+import javax.sound.midi.MidiDevice;
+import javax.sound.midi.MidiDeviceReceiver;
+import javax.sound.midi.MidiDeviceTransmitter;
+import javax.sound.midi.MidiSystem;
+import javax.sound.midi.MidiUnavailableException;
+import javax.sound.midi.Receiver;
+import javax.sound.midi.Transmitter;
+
+
+public class TestAllDevices {
+
+    static boolean failed = false;
+
+    public static void main(String[] args) throws Exception {
+        out("default receiver:");
+        try {
+            Receiver recv = MidiSystem.getReceiver();
+            out("  receiver: " + recv);
+            if (recv instanceof MidiDeviceReceiver) {
+                out("    OK");
+            } else {
+                out("    ERROR: not an instance of MidiDeviceReceiver");
+                failed = true;
+            }
+        } catch (MidiUnavailableException ex) {
+            // this is not an error
+            out("  receiver: MidiUnavailableException (test NOT failed)");
+        }
+
+        out("default transmitter:");
+        try {
+            Transmitter tran = MidiSystem.getTransmitter();
+            out("  transmitter: " + tran);
+            if (tran instanceof MidiDeviceTransmitter) {
+                out("    OK");
+            } else {
+                out("    ERROR: not an instance of MidiDeviceTransmitter");
+                failed = true;
+            }
+        } catch (MidiUnavailableException ex) {
+            // this is not an error
+            out("  transmitter: MidiUnavailableException (test NOT failed)");
+        }
+
+        MidiDevice.Info[] infos = MidiSystem .getMidiDeviceInfo();
+        for (MidiDevice.Info info: infos) {
+            out(info.toString() + ":");
+            try {
+                MidiDevice dev = MidiSystem.getMidiDevice(info);
+                dev.open();
+
+                try {
+                    Receiver recv = dev.getReceiver();
+                    out("  receiver: " + recv);
+                    if (recv instanceof MidiDeviceReceiver) {
+                        MidiDeviceReceiver devRecv = (MidiDeviceReceiver)recv;
+                        MidiDevice retDev = devRecv.getMidiDevice();
+                        if (retDev == dev) {
+                            out("    OK");
+                        } else {
+                            out("    ERROR: getMidiDevice returned incorrect device: " + retDev);
+                            failed = true;
+                        }
+                    } else {
+                        out("    ERROR: not an instance of MidiDeviceReceiver");
+                        failed = true;
+                    }
+                } catch (MidiUnavailableException ex) {
+                    // this is not an error
+                    out("  receiver: MidiUnavailableException (test NOT failed)");
+                }
+
+                try {
+                    Transmitter tran = dev.getTransmitter();
+                    out("  transmitter: " + tran);
+                    if (tran instanceof MidiDeviceTransmitter) {
+                        MidiDeviceTransmitter devTran = (MidiDeviceTransmitter)tran;
+                        MidiDevice retDev = devTran.getMidiDevice();
+                        if (retDev == dev) {
+                            out("    OK");
+                        } else {
+                            out("    ERROR: getMidiDevice retur4ned incorrect device: " + retDev);
+                            failed = true;
+                        }
+                    } else {
+                        out("    ERROR: not an instance of MidiDeviceTransmitter");
+                        failed = true;
+                    }
+                } catch (MidiUnavailableException ex) {
+                    // this is not an error
+                    out("  transmitter: MidiUnavailableException (test NOT failed)");
+                }
+
+                dev.close();
+            } catch (MidiUnavailableException ex) {
+                out("  device: MidiUnavailableException (test NOT failed)");
+            }
+        }
+
+        if (failed) {
+            throw new Exception("Test failed.");
+        }
+    }
+
+    static void out(String s) {
+        System.out.println(s);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/sampled/AudioFormat/Matches_NOT_SPECIFIED.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 4937708
+ * @summary Tests that AudioFormat.matches handle NOT_SPECIFIED value in all fields
+ * @run main Matches_NOT_SPECIFIED
+ * @author Alex Menkov
+ *
+ */
+
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioFormat.Encoding;
+import javax.sound.sampled.AudioSystem;
+
+
+public class Matches_NOT_SPECIFIED {
+
+    static boolean success = true;
+    static AudioFormat f1;
+    static AudioFormat f2;
+
+    public static void main(String[] args) throws Exception {
+        AudioFormat f3;
+        f1 = new AudioFormat(44100, 16, 2, true, false);
+        f2 = new AudioFormat(Encoding.PCM_SIGNED,
+                AudioSystem.NOT_SPECIFIED,
+                AudioSystem.NOT_SPECIFIED,
+                AudioSystem.NOT_SPECIFIED,
+                AudioSystem.NOT_SPECIFIED,
+                AudioSystem.NOT_SPECIFIED, false);
+        test(true);
+
+//        f1 = new AudioFormat(44100, 8, 16, true, false);
+        f2 = new AudioFormat(Encoding.PCM_SIGNED,
+                AudioSystem.NOT_SPECIFIED,
+                AudioSystem.NOT_SPECIFIED,
+                AudioSystem.NOT_SPECIFIED,
+                AudioSystem.NOT_SPECIFIED,
+                AudioSystem.NOT_SPECIFIED, true);
+        test(false);
+
+        f1 = new AudioFormat(44100, 8, 8, true, false);
+        test(true);
+
+        if (success) {
+            out("The test PASSED.");
+        } else {
+            out("The test FAILED.");
+            throw new Exception("The test FAILED");
+        }
+    }
+
+    static void test(boolean shouldMatch) {
+        out("testing:");
+        out("  - " + f1.toString());
+        out("  - " + f2.toString());
+        if (f1.matches(f2)) {
+            if (shouldMatch) {
+                out("  (OK) MATCHES");
+            } else {
+                out("  (ERROR) MATCHES");
+                success = false;
+            }
+        } else {
+            if (shouldMatch) {
+                out("  (ERROR) DOESNT MATCH!");
+                success = false;
+            } else {
+                out("  (OK) DOESNT MATCH!");
+            }
+        }
+    }
+
+    static void out(String s) {
+        System.out.println(s);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/sound/sampled/AudioFormat/PCM_FLOAT_support.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 6944033
+ * @summary Tests that PCM_FLOAT encoding is supported
+ * @compile -source 1.7 PCM_FLOAT_support.java
+ * @run main PCM_FLOAT_support
+ * @author Alex Menkov
+ *
+ */
+
+import javax.sound.sampled.AudioFormat.Encoding;
+import javax.sound.sampled.AudioSystem;
+
+
+public class PCM_FLOAT_support {
+
+    static Encoding pcmFloatEnc;
+
+    static boolean testFailed = false;
+
+    public static void main(String[] args) throws Exception {
+        // 1st checks Encoding.PCM_FLOAT is available
+        pcmFloatEnc = Encoding.PCM_FLOAT;
+
+        Encoding[] encodings = AudioSystem.getTargetEncodings(pcmFloatEnc);
+        out("conversion from PCM_FLOAT to " + encodings.length + " encodings:");
+        for (Encoding e: encodings) {
+            out("  - " + e);
+        }
+        if (encodings.length == 0) {
+            testFailed = true;
+        }
+
+        test(Encoding.PCM_SIGNED);
+        test(Encoding.PCM_UNSIGNED);
+
+        if (testFailed) {
+            throw new Exception("test failed");
+        }
+        out("test passed.");
+    }
+
+    static void out(String s) {
+        System.out.println(s);
+    }
+
+    static boolean test(Encoding enc) {
+        out("conversion " + enc + " -> PCM_FLOAT:");
+        Encoding[] encodings = AudioSystem.getTargetEncodings(enc);
+        for (Encoding e: encodings) {
+            if (e.equals(pcmFloatEnc)) {
+                out("  - OK");
+                return true;
+            }
+        }
+        out("  - FAILED (not supported)");
+        testFailed = true;
+        return false;
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/swing/JColorChooser/Test6977726.html	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,8 @@
+<html>
+<body>
+If you don't see the preview panel, then test failed, otherwise it passed.
+
+<applet width="500" height="400" code="Test6977726.class">
+</applet>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/swing/JColorChooser/Test6977726.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 6977726
+ * @summary Checks if JColorChooser.setPreviewPanel removes the old one
+ * @author Sergey Malenkov
+ * @run applet/manual=yesno Test6977726.html
+ */
+
+import javax.swing.JApplet;
+import javax.swing.JColorChooser;
+import javax.swing.JLabel;
+
+public class Test6977726 extends JApplet {
+    public void init() {
+        JColorChooser chooser = new JColorChooser();
+        chooser.setPreviewPanel(new JLabel("Text Preview Panel"));
+        getContentPane().add(chooser);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/swing/border/Test6978482.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 6978482
+ * @summary Tests unchecked casts
+ * @author Sergey Malenkov
+ */
+
+import com.sun.java.swing.plaf.motif.MotifBorders;
+import com.sun.java.swing.plaf.windows.WindowsBorders;
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.image.BufferedImage;
+
+import javax.swing.ActionMap;
+import javax.swing.JFileChooser;
+import javax.swing.JLabel;
+import javax.swing.JToggleButton;
+import javax.swing.JToolBar;
+import javax.swing.border.BevelBorder;
+import javax.swing.border.Border;
+import javax.swing.border.CompoundBorder;
+import javax.swing.border.EmptyBorder;
+import javax.swing.border.EtchedBorder;
+import javax.swing.border.LineBorder;
+import javax.swing.border.MatteBorder;
+import javax.swing.border.SoftBevelBorder;
+import javax.swing.border.TitledBorder;
+import javax.swing.plaf.ActionMapUIResource;
+import javax.swing.plaf.BorderUIResource;
+import javax.swing.plaf.synth.SynthLookAndFeel;
+import javax.swing.plaf.basic.BasicBorders;
+import javax.swing.plaf.basic.BasicToolBarUI;
+import javax.swing.plaf.metal.MetalBorders;
+import javax.swing.plaf.metal.MetalComboBoxEditor;
+
+import sun.swing.plaf.synth.SynthFileChooserUI;
+
+public class Test6978482 {
+    private static final JLabel LABEL = new JLabel();
+    private static final JToolBar TOOLBAR = new JToolBar(); // init non-rollover border
+
+    private static final Border[] BORDERS = {
+            new MotifBorders.BevelBorder(true, Color.BLACK, Color.WHITE),
+            new MotifBorders.ButtonBorder(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK),
+            new MotifBorders.FocusBorder(Color.BLACK, Color.WHITE),
+            new MotifBorders.FrameBorder(LABEL),
+            new MotifBorders.MenuBarBorder(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK),
+            new MotifBorders.MotifPopupMenuBorder(new Font(null, Font.PLAIN, 10), Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK),
+            new MotifBorders.ToggleButtonBorder(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK),
+
+            new WindowsBorders.ProgressBarBorder(Color.BLACK, Color.WHITE),
+            new WindowsBorders.ToolBarBorder(Color.BLACK, Color.WHITE),
+            //- WindowsInternalFrameUI.XPBorder is not accessible: check it visually
+            //? WindowsTableHeaderUI.IconBorder is not accessible: check it visually
+            //- XPStyle.XPEmptyBorder is not accessible: check it visually
+            //- XPStyle.XPFillBorder is not accessible: check it visually
+            //- XPStyle.XPImageBorder is not accessible: check it visually
+
+            new BevelBorder(BevelBorder.RAISED),
+            new CompoundBorder(),
+            new EmptyBorder(1, 2, 3, 4),
+            new EtchedBorder(),
+            new LineBorder(Color.BLACK, 2, true),
+            new MatteBorder(1, 2, 3, 4, Color.BLACK),
+            new SoftBevelBorder(BevelBorder.LOWERED),
+            new TitledBorder("4856008"),
+
+            new BorderUIResource(new EmptyBorder(1, 2, 3, 4)),
+
+            new BasicBorders.ButtonBorder(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK),
+            new BasicBorders.FieldBorder(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK),
+            new BasicBorders.MarginBorder(),
+            new BasicBorders.MenuBarBorder(Color.BLACK, Color.WHITE),
+            new BasicBorders.RadioButtonBorder(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK),
+            //+ BasicBorders.RolloverMarginBorder:
+            new ToolBar().getRolloverMarginBorder(),
+            new BasicBorders.SplitPaneBorder(Color.BLACK, Color.WHITE),
+            //+ BasicBorders.SplitPaneDividerBorder:
+            BasicBorders.getSplitPaneDividerBorder(),
+            new BasicBorders.ToggleButtonBorder(Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK),
+
+            new MetalBorders.ButtonBorder(),
+            //- MetalBorders.DialogBorder is not accessible: check it visually
+            new MetalBorders.Flush3DBorder(),
+            //- MetalBorders.FrameBorder is not accessible: check it visually
+            new MetalBorders.InternalFrameBorder(),
+            new MetalBorders.MenuBarBorder(),
+            new MetalBorders.MenuItemBorder(),
+            new MetalBorders.OptionDialogBorder(),
+            new MetalBorders.PaletteBorder(),
+            new MetalBorders.PopupMenuBorder(),
+            //- MetalBorders.RolloverMarginBorder is not accessible: check it visually
+            new MetalBorders.ScrollPaneBorder(),
+            new MetalBorders.TableHeaderBorder(),
+            new MetalBorders.ToolBarBorder(),
+            //+ MetalComboBoxEditor.EditorBorder:
+            new MetalEditor().getEditorBorder(),
+
+            //- SynthBorder is not accessible: check it visually
+            //- SynthScrollPaneUI.ViewportBorder is not accessible: check it visually
+
+            //? CSSBorder is not accessible: check it visually
+            //? CommentView.CommentBorder is not accessible: check it visually
+            //- HiddenTagView.EndTagBorder is not accessible: check it visually
+            //- HiddenTagView.StartTagBorder is not accessible: check it visually
+
+            //+ SynthFileChooserUI.UIBorder:
+            new SynthFileChooser().getUIBorder(),
+    };
+
+    public static void main(String[] args) {
+        Component c = new Component() {};
+        c.setBackground(Color.WHITE);
+        c.setForeground(Color.BLACK);
+        Graphics g = new BufferedImage(1024, 768, BufferedImage.TYPE_INT_RGB).getGraphics();
+        g.setClip(0, 0, 1024, 768);
+        for (Border border : BORDERS) {
+            System.out.println(border.getClass());
+            border.getBorderInsets(c);
+            border.paintBorder(c, g, 0, 0, 1024, 768);
+        }
+    }
+
+    // This class is used to get the instance of BasicBorders.RolloverMarginBorder
+    private static class ToolBar extends BasicToolBarUI {
+        private Border getRolloverMarginBorder() {
+            JToggleButton button = new JToggleButton();
+            CompoundBorder border = (CompoundBorder) getNonRolloverBorder(button);
+            return border.getInsideBorder();
+        }
+    }
+
+    // This class is used to get the instance of MetalComboBoxEditor.EditorBorder
+    private static class MetalEditor extends MetalComboBoxEditor {
+        private Border getEditorBorder() {
+            return editor.getBorder();
+        }
+    }
+
+    // This class is used to get the instance of SynthFileChooserUI.UIBorder
+    private static class SynthFileChooser extends SynthFileChooserUI {
+        private static final JFileChooser CHOOSER = new JFileChooser();
+        private String name;
+
+        private SynthFileChooser() {
+            super(CHOOSER);
+        }
+
+        private Border getUIBorder() {
+            new SynthLookAndFeel().initialize();
+            CHOOSER.setBorder(null);
+            installDefaults(CHOOSER);
+            return CHOOSER.getBorder();
+        }
+
+        @Override
+        protected ActionMap createActionMap() {
+            return new ActionMapUIResource();
+        }
+
+        @Override
+        public String getFileName() {
+            return this.name;
+        }
+
+        @Override
+        public void setFileName(String name) {
+            this.name = name;
+        }
+    }
+}
--- a/test/sun/java2d/DirectX/OnScreenRenderingResizeTest/OnScreenRenderingResizeTest.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/sun/java2d/DirectX/OnScreenRenderingResizeTest/OnScreenRenderingResizeTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -157,7 +157,7 @@
             if (cnt == 90 && robot != null) {
                 // area where we blitted to should be either white or green
                 Point p = frame.getLocationOnScreen();
-                p.move(in.left+10, in.top+10);
+                p.translate(in.left+10, in.top+10);
                 BufferedImage bi =
                     robot.createScreenCapture(
                         new Rectangle(p.x, p.y, IMAGE_W/2, IMAGE_H/2));
@@ -166,7 +166,7 @@
 
                 // the are where we didn't render should stay white
                 p = frame.getLocationOnScreen();
-                p.move(in.left, in.top+IMAGE_H+5);
+                p.translate(in.left, in.top+IMAGE_H+5);
                 bi = robot.createScreenCapture(
                     new Rectangle(p.x, p.y,
                                   frame.getWidth()-in.left-in.right,
--- a/test/sun/net/sdp/ProbeIB.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/sun/net/sdp/ProbeIB.java	Fri Sep 24 16:41:32 2010 -0700
@@ -34,21 +34,16 @@
 
 public class ProbeIB {
     public static void main(String[] args) throws IOException {
-        Scanner s = new Scanner(new File("/etc/path_to_inst"));
+        Scanner s = new Scanner(new File(args[0]));
         try {
             while (s.hasNextLine()) {
-                String line = s.nextLine();
-                if (line.startsWith("#"))
-                    continue;
-                String[] fields = line.split("\\s+");
-                if (!fields[2].equals("\"ibd\""))
-                    continue;
-                String name = fields[2].substring(1, fields[2].length()-1) + fields[1];
-                NetworkInterface ni = NetworkInterface.getByName(name);
+                String link = s.nextLine();
+                NetworkInterface ni = NetworkInterface.getByName(link);
                 if (ni != null) {
                     Enumeration<InetAddress> addrs = ni.getInetAddresses();
                     while (addrs.hasMoreElements()) {
-                        System.out.println(addrs.nextElement().getHostAddress());
+                        InetAddress addr = addrs.nextElement();
+                        System.out.println(addr.getHostAddress());
                     }
                 }
             }
--- a/test/sun/net/sdp/sanity.sh	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/sun/net/sdp/sanity.sh	Fri Sep 24 16:41:32 2010 -0700
@@ -33,14 +33,15 @@
     echo "This is a Solaris-only test"
     exit 0
 fi
-SDPADM=/usr/sbin/sdpadm
-if [ ! -f ${SDPADM} ]; then
-    echo "SDP not available"
-    exit 0
-fi
-${SDPADM} status|grep Enabled
-if [ $? != 0 ]; then 
-    echo "SDP not enabled"
+
+IB_LINKS=ib.links
+IB_ADDRS=ib.addrs
+
+# Display IB partition link information
+# (requires Solaris 11, will fail on Solaris 10)
+/usr/sbin/dladm show-part -o LINK -p > ${IB_LINKS}
+if [ $? != 0 ]; then
+    echo "Unable to get IB parition link information"
     exit 0
 fi
 
@@ -56,13 +57,13 @@
 export CLASSPATH
 
 # Probe for IP addresses plumbed to IB interfaces
-$JAVA -Djava.net.preferIPv4Stack=true ProbeIB > ib_addrs
+$JAVA -Djava.net.preferIPv4Stack=true ProbeIB ${IB_LINKS} > ${IB_ADDRS}
 
 # Create sdp.conf
 SDPCONF=sdp.conf
 rm ${SDPCONF}
 touch ${SDPCONF}
-cat ib_addrs | while read ADDR
+cat ${IB_ADDRS} | while read ADDR
 do
    echo "bind ${ADDR} *" > ${SDPCONF}
    echo "connect ${ADDR} *" >> ${SDPCONF}
--- a/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingTest.java	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingTest.java	Fri Sep 24 16:41:32 2010 -0700
@@ -38,7 +38,7 @@
 
 public class ChunkedEncodingTest{
     private static MessageDigest serverDigest, clientDigest;
-    private static byte[] serverMac, clientMac;
+    private static volatile byte[] serverMac, clientMac;
 
     static void client(String u) throws Exception {
         URL url = new URL(u);
@@ -106,7 +106,7 @@
             while (is.read() != -1);
             is.close();
 
-            t.sendResponseHeaders (200, MESSAGE_LENGTH);
+            t.sendResponseHeaders (200, 0);
             OutputStream os = t.getResponseBody();
             DigestOutputStream dos = new DigestOutputStream(os, serverDigest);
 
--- a/test/sun/security/tools/jarsigner/emptymanifest.sh	Thu Sep 23 17:33:40 2010 -0700
+++ b/test/sun/security/tools/jarsigner/emptymanifest.sh	Fri Sep 24 16:41:32 2010 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2009, 2010, Oracle and/or its affiliates. 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
@@ -49,13 +49,23 @@
 
 KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit -keystore $KS"
 JAR=$TESTJAVA${FS}bin${FS}jar
+JAVA=$TESTJAVA${FS}bin${FS}java
+JAVAC=$TESTJAVA${FS}bin${FS}javac
 JARSIGNER=$TESTJAVA${FS}bin${FS}jarsigner
 
 rm $KS $JFILE
 echo A > A
 echo B > B
 mkdir META-INF
-printf "\r\n" > META-INF${FS}MANIFEST.MF
+cat <<EOF > CrLf.java
+class CrLf {
+  public static void main(String[] args) throws Exception {
+    System.out.write(new byte[] {'\r', '\n'});
+  }
+}
+EOF
+$JAVAC CrLf.java
+$JAVA CrLf > META-INF${FS}MANIFEST.MF
 zip $JFILE META-INF${FS}MANIFEST.MF A B
 
 $KT -alias a -dname CN=a -keyalg rsa -genkey -validity 300
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/tools/launcher/MiscTests.java	Fri Sep 24 16:41:32 2010 -0700
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. 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.
+ *
+ * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 6856415 6981001
+ * @summary Miscellaneous tests, Exceptions, EnsureJRE etc.
+ * @compile -XDignore.symbol.file MiscTests.java TestHelper.java
+ * @run main MiscTests
+ */
+
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.HashMap;
+import java.util.Map;
+
+
+public class MiscTests {
+
+    // 6856415: Checks to ensure that proper exceptions are thrown by java
+    static void test6856415() {
+        // No pkcs library on win-x64, so we bail out.
+        if (TestHelper.is64Bit && TestHelper.isWindows) {
+            return;
+        }
+        StringBuilder sb = new StringBuilder();
+        sb.append("public static void main(String... args) {\n");
+        sb.append("java.security.Provider p = new sun.security.pkcs11.SunPKCS11(args[0]);\n");
+        sb.append("java.security.Security.insertProviderAt(p, 1);\n");
+        sb.append("}");
+        File testJar = new File("Foo.jar");
+        testJar.delete();
+        try {
+            TestHelper.createJar(testJar, sb.toString());
+        } catch (FileNotFoundException fnfe) {
+            throw new RuntimeException(fnfe);
+        }
+        TestHelper.TestResult tr = TestHelper.doExec(TestHelper.javaCmd,
+                "-Djava.security.manager", "-jar", testJar.getName(), "foo.bak");
+        for (String s : tr.testOutput) {
+            System.out.println(s);
+    }
+        if (!tr.contains("java.security.AccessControlException:" +
+                " access denied (\"java.lang.RuntimePermission\"" +
+                " \"accessClassInPackage.sun.security.pkcs11\")")) {
+            System.out.println(tr.status);
+        }
+    }
+    // 6981001 : Check EnsureJreInstallation is ok, note we cannot
+    // thoroughly test this function, we simply do our best.
+    static void test6981001() {
+        if (TestHelper.is64Bit || !TestHelper.isWindows) {
+            return;
+        }
+        Map<String, String> env = new HashMap<String, String>();
+        env.put("_JAVA_LAUNCHER_DEBUG", "true");
+        TestHelper.TestResult tr = TestHelper.doExec(env, TestHelper.javaCmd);
+        if (!tr.contains(TestHelper.JAVAHOME + "\\lib\\bundles")) {
+            System.out.println(tr.status);
+        }
+    }
+    public static void main(String... args) {
+        test6856415();
+        test6981001();
+        if (TestHelper.testExitValue != 0) {
+            throw new Error(TestHelper.testExitValue + " tests failed");
+    }
+}
+}
--- a/test/tools/launcher/VerifyExceptions.java	Thu Sep 23 17:33:40 2010 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-/*
- * Copyright (c) 2010, Oracle and/or its affiliates. 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.
- *
- * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 6856415
- * @summary Checks to ensure that proper exceptions are thrown by java
- * @compile -XDignore.symbol.file VerifyExceptions.java TestHelper.java
- * @run main VerifyExceptions
- */
-
-
-import java.io.File;
-import java.io.FileNotFoundException;
-
-
-public class VerifyExceptions {
-
-    static void test6856415() {
-        // No pkcs library on win-x64, so we bail out.
-        if (TestHelper.is64Bit && TestHelper.isWindows) {
-            return;
-        }
-        StringBuilder sb = new StringBuilder();
-        sb.append("public static void main(String... args) {\n");
-        sb.append("java.security.Provider p = new sun.security.pkcs11.SunPKCS11(args[0]);\n");
-        sb.append("java.security.Security.insertProviderAt(p, 1);\n");
-        sb.append("}");
-        File testJar = new File("Foo.jar");
-        testJar.delete();
-        try {
-            TestHelper.createJar(testJar, sb.toString());
-        } catch (FileNotFoundException fnfe) {
-            throw new RuntimeException(fnfe);
-        }
-        TestHelper.TestResult tr = TestHelper.doExec(TestHelper.javacCmd,
-                "-Djava.security.manager", "-jar", testJar.getName(), "foo.bak");
-        tr.checkNegative();
-        tr.contains("Exception in thread \"main\" java.security.AccessControlException: access denied (\"java.lang.RuntimePermission\" \"accessClassInPackage.sun.security.pkcs11\")\")");
-    }
-
-    public static void main(String... args) {
-        test6856415();
-    }
-}