Include modules/lcms in list of mirrored directories. Old history only available in CVS.
authorjst@mozilla.com
Fri, 10 Aug 2007 17:19:03 -0700
changeset 4506 0f1b7da7647bda9d9249298ab0c44d4f4cd22f02
parent 4505 1dc2a9b2b3834de38c9c591734810e63fb1ff21a
child 4507 5a68e7963bb24c9f46d6ba2b6f34b4d3b465071b
child 4510 d7f794dd496fdec0826004faf378c7adbb2750b2
push id1
push userbsmedberg@mozilla.com
push dateThu, 20 Mar 2008 16:49:24 +0000
treeherdermozilla-central@61007906a1f8 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone1.9a8pre
Include modules/lcms in list of mirrored directories. Old history only available in CVS.
modules/lcms/AUTHORS
modules/lcms/COPYING
modules/lcms/Makefile.in
modules/lcms/NEWS
modules/lcms/README.1ST
modules/lcms/include/Makefile.in
modules/lcms/include/icc34.h
modules/lcms/include/lcms.h
modules/lcms/src/Makefile.in
modules/lcms/src/cmscam02.c
modules/lcms/src/cmscam97.c
modules/lcms/src/cmscgats.c
modules/lcms/src/cmscnvrt.c
modules/lcms/src/cmserr.c
modules/lcms/src/cmsgamma.c
modules/lcms/src/cmsgmt.c
modules/lcms/src/cmsintrp.c
modules/lcms/src/cmsio0.c
modules/lcms/src/cmsio1.c
modules/lcms/src/cmslut.c
modules/lcms/src/cmsmatsh.c
modules/lcms/src/cmsmtrx.c
modules/lcms/src/cmsnamed.c
modules/lcms/src/cmspack.c
modules/lcms/src/cmspcs.c
modules/lcms/src/cmsps2.c
modules/lcms/src/cmssamp.c
modules/lcms/src/cmsvirt.c
modules/lcms/src/cmswtpnt.c
modules/lcms/src/cmsxform.c
modules/lcms/src/lcms.def
new file mode 100644
--- /dev/null
+++ b/modules/lcms/AUTHORS
@@ -0,0 +1,4 @@
+Main Author:
+------------
+Marti Maria <info@littlecms.com>
+
new file mode 100644
--- /dev/null
+++ b/modules/lcms/COPYING
@@ -0,0 +1,8 @@
+Little CMS
+Copyright (c) 1998-2007 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.
new file mode 100644
--- /dev/null
+++ b/modules/lcms/Makefile.in
@@ -0,0 +1,46 @@
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is lcms mozilla build integration.
+#
+# The Initial Developer of the Original Code is IBM Corporation.
+# Portions created by the Initial Developer are Copyright (C) 2007
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH		= ../..
+topsrcdir	= @top_srcdir@
+srcdir		= @srcdir@
+VPATH		= @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+MODULE		= lcms
+DIRS		= include src
+
+include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/modules/lcms/NEWS
@@ -0,0 +1,32 @@
+
+ New in ver 1.17
+ ===============
+  
+Changes in API
+----------------------
+
+WIN64 support
+_vsnprintf wrap
+BOOL replaced by LCMSBOOL
+cmsSetLanguage parameters changed to match ICC spec
+removed support for extended gamut descriptor (was never fully implemented)
+cmsFLAGS_NODEFAULTRESOURCEDEF moved to 0x01000000
+_cmsMalloc wrapper for malloc
+_cmsFree wrapper for free
+
+
+Implementation
+----------------------
+All errors moved to fatal, since there is no easy recovery strategy
+Vulnerability fixes on cmsio1.c 
+Status check, many functions now check the status when calling other functions. Improved robustness against ill-formed profiles.
+_cmsSaveProfile didn't copy tags from a file based profile, fixed.
+
+
+Utilities
+----------
+icctrans: CMYKcm support wrongly implemented, fixed.
+icclink: linking 3 to 7 channels didn't work in some cases, fixed.
+    
+
+
new file mode 100644
--- /dev/null
+++ b/modules/lcms/README.1ST
@@ -0,0 +1,94 @@
+
+ Read.me for release 1.17
+ ========================
+
+ 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.
+
+
+ The lcms library is now distributed under
+
+                MIT PUBLIC LICENSE
+
+ See file COPYING. for details
+
+
+   This is the 15th. public release the engine. It has been tested 
+   across several versions before, but it is possible some
+   bugs still arises. If so, sorry for the inconvenience, and
+   please feel free to submit any suggestion/solution (if you can
+   found it) at:
+
+                       info@littlecms.com
+
+ 
+   Note that the aesthetics of resulting colors are due only to
+   profiles, and not as consequence of the lcms package.
+
+   The main site for the package is located at
+
+           http://www.littlecms.com
+        or
+           http://www.lcms.coloraid.de
+
+
+   Littlecms has also a mailing list on:
+
+   http://lists.sourceforge.net/lists/listinfo/lcms-user
+
+
+   Looking forward the lcms project would grow in future, I will 
+   welcome any contribution/optimization/enhancement.
+
+   Enjoy!
+
+
+  About profiles
+  ==============
+
+    The demo of this package includes some profiles for colorspace
+    conversions. I figure all of them are in public domain, but
+    since some contains copyright notice, I will enumerate here
+    the sources:
+
+         Sun Microsystems Java SDK (widely available)
+         Kodak public FTP site: ftp.kodak.com
+         ICM Stress demo from microsoft. www.microsoft.com
+         sRGB from sRGB site www.srgb.com
+
+    If you found any of these not to be in public domain,
+    please notify me. I will remove the offending profile as soon as
+    posible.
+
+
+
+  Additional files
+  ================
+
+    ICC34.h is the header file the International Color Consortium
+    has posted for version spec 3.4, with some minor modifications
+    for improving portability.
+
+    You can reach it at
+
+                http://www.color.org
+
+
new file mode 100644
--- /dev/null
+++ b/modules/lcms/include/Makefile.in
@@ -0,0 +1,46 @@
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is lcms mozilla build integration.
+#
+# The Initial Developer of the Original Code is IBM Corporation.
+# Portions created by the Initial Developer are Copyright (C) 2007
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH		= ../../..
+topsrcdir	= @top_srcdir@
+srcdir		= @srcdir@
+VPATH		= @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+MODULE		= lcms
+EXPORTS		= icc34.h lcms.h
+
+include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/modules/lcms/include/icc34.h
@@ -0,0 +1,1029 @@
+/* Header file guard bands */
+#ifndef ICC_H
+#define ICC_H
+
+/***************************************************************** 
+ Copyright (c) 1994-1996 SunSoft, Inc.
+
+                    Rights Reserved
+
+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 restrict- 
+ion, 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 NON-
+INFRINGEMENT.  IN NO EVENT SHALL SUNSOFT, INC. OR ITS PARENT 
+COMPANY 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. 
+ 
+Except as contained in this notice, the name of SunSoft, Inc. 
+shall not be used in advertising or otherwise to promote the 
+sale, use or other dealings in this Software without written 
+authorization from SunSoft Inc. 
+******************************************************************/
+
+/*
+ * 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 */
new file mode 100644
--- /dev/null
+++ b/modules/lcms/include/lcms.h
@@ -0,0 +1,2044 @@
+//
+//  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.17
+
+#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        117
+
+// 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__)
+#   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
+
+#if __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
+//
+//            TTTTT U Y F P X S EEE CCCC BBB
+//
+//            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 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 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 int             LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE IT8, char ***PropertyNames);
+
+// 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);
+
+// The LABEL extension
+
+LCMSAPI int             LCMSEXPORT cmsIT8SetTableByLabel(LCMSHANDLE hIT8, const char* cSet, const char* cField, const char* ExpectedType);
+
+// 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 _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);
+               
+               // 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_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);
+
+// 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
+
new file mode 100644
--- /dev/null
+++ b/modules/lcms/src/Makefile.in
@@ -0,0 +1,75 @@
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is lcms mozilla build integration.
+#
+# The Initial Developer of the Original Code is IBM Corporation.
+# Portions created by the Initial Developer are Copyright (C) 2007
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH           = ../../..
+topsrcdir       = @top_srcdir@
+srcdir          = @srcdir@
+VPATH           = @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+MODULE		= lcms
+LIBRARY_NAME	= mozlcms
+
+GRE_MODULE	= 1
+LIBXUL_LIBRARY = 1
+DIST_INSTALL = 1
+
+ifeq (,$(MOZ_ENABLE_LIBXUL)$(BUILD_STATIC_LIBS))
+ifeq (,$(filter-out WINNT WINCE,$(OS_ARCH)))
+ifndef GNU_CC
+MAPFILE	= $(LIBRARY_NAME).map
+DEFFILE	= $(win_srcdir)/lcms.def
+endif
+endif
+
+ifeq (,$(filter-out WINNT WINCE OS2,$(OS_ARCH)))
+DEFINES	+= -DLCMS_DLL=1 -DLCMS_DLL_BUILD=1
+else
+VISIBILITY_FLAGS =
+endif
+endif
+
+REQUIRES	= $(LCMS_REQUIRES) \
+		  $(NULL)
+
+CSRCS = cmscnvrt.c cmserr.c cmsgamma.c cmsgmt.c cmsintrp.c cmsio1.c \
+	cmslut.c cmsmatsh.c cmsmtrx.c cmspack.c cmspcs.c cmswtpnt.c \
+	cmsxform.c cmssamp.c cmscam97.c cmsnamed.c cmsps2.c cmscam02.c \
+	cmsvirt.c cmscgats.c cmsio0.c
+
+LOCAL_INCLUDES += -I../include
+
+include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/modules/lcms/src/cmscam02.c
@@ -0,0 +1,490 @@
+//
+//  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.
+
+
+
+// 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];
+    
+} CAM02COLOR, *LPCAM02COLOR;
+
+typedef struct  {
+    
+    CAM02COLOR adoptedWhite;
+    double LA, Yb;
+    double F, c, Nc;
+    int surround;
+    double n, Nbb, Ncb, z, FL, D;
+    
+} cmsCIECAM02, *LPcmsCIECAM02;
+
+
+static
+double compute_n(LPcmsCIECAM02 pMod) 
+{
+    return(pMod -> Yb / pMod -> adoptedWhite.XYZ[1]);
+}
+
+static
+double compute_z(LPcmsCIECAM02 pMod) 
+{
+    return(1.48 + pow(pMod -> n, 0.5));
+}
+
+static
+double computeNbb(LPcmsCIECAM02 pMod) 
+{
+    return(0.725 * pow((1.0 / pMod -> n), 0.2));
+}
+
+static
+double computeFL(LPcmsCIECAM02 pMod) 
+{
+    double k, FL;
+    
+    k = 1.0 / ((5.0 * pMod->LA) + 1.0);
+    FL = 0.2 * pow(k, 4.0) * (5.0 * pMod->LA) + 0.1 *
+        (pow((1.0 - pow(k, 4.0)), 2.0)) *
+        (pow((5.0 * pMod->LA), (1.0 / 3.0)));
+    
+    return FL;
+}
+
+static    
+double computeD(LPcmsCIECAM02 pMod) 
+{
+    double D;
+
+    D = pMod->F - (1.0/3.6)*(exp(((-pMod ->LA-42) / 92.0)));
+
+    return D;
+}
+
+
+static
+CAM02COLOR XYZtoCAT02(CAM02COLOR clr) 
+{
+    clr.RGB[0] = (clr.XYZ[0] *  0.7328) + (clr.XYZ[1] *  0.4296) + (clr.XYZ[2] * -0.1624);
+    clr.RGB[1] = (clr.XYZ[0] * -0.7036) + (clr.XYZ[1] *  1.6975) + (clr.XYZ[2] *  0.0061);
+    clr.RGB[2] = (clr.XYZ[0] *  0.0030) + (clr.XYZ[1] *  0.0136) + (clr.XYZ[2] *  0.9834);
+    
+    return clr;
+}
+
+static
+CAM02COLOR ChromaticAdaptation(CAM02COLOR clr, LPcmsCIECAM02 pMod) 
+{
+    int i;
+    for (i = 0; i < 3; i++) {
+        clr.RGBc[i] = ((pMod -> adoptedWhite.XYZ[1] *
+            (pMod->D / pMod -> adoptedWhite.RGB[i])) +
+            (1.0 - pMod->D)) * clr.RGB[i];
+    }
+
+    return clr; 
+}
+
+
+static
+CAM02COLOR CAT02toHPE (CAM02COLOR clr) 
+{
+
+    double 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));
+    M[2] =(( 0.38971 *  0.182745) + (0.68898 * 0.072098) + (-0.07868 *  1.015326));
+    M[3] =((-0.22981 *  1.096124) + (1.18340 * 0.454369) + ( 0.04641 * -0.009628));
+    M[4] =((-0.22981 * -0.278869) + (1.18340 * 0.473533) + ( 0.04641 * -0.005698));
+    M[5] =((-0.22981 *  0.182745) + (1.18340 * 0.072098) + ( 0.04641 *  1.015326));
+    M[6] =(-0.009628);
+    M[7] =(-0.005698);
+    M[8] =( 1.015326);
+    
+    clr.RGBp[0] = (clr.RGBc[0] * M[0]) +  (clr.RGBc[1] * M[1]) + (clr.RGBc[2] * M[2]);
+    clr.RGBp[1] = (clr.RGBc[0] * M[3]) +  (clr.RGBc[1] * M[4]) + (clr.RGBc[2] * M[5]);
+    clr.RGBp[2] = (clr.RGBc[0] * M[6]) +  (clr.RGBc[1] * M[7]) + (clr.RGBc[2] * M[8]);
+    
+    return  clr;
+}
+
+static
+CAM02COLOR NonlinearCompression(CAM02COLOR clr, LPcmsCIECAM02 pMod) 
+{
+    int i;
+    double temp;
+
+    for (i = 0; i < 3; i++) {
+        if (clr.RGBp[i] < 0) {
+
+            temp = pow((-1.0 * pMod->FL * clr.RGBp[i] / 100.0), 0.42);
+            clr.RGBpa[i] = (-1.0 * 400.0 * temp) / (temp + 27.13) + 0.1;
+        }
+        else {
+            temp = pow((pMod->FL * clr.RGBp[i] / 100.0), 0.42);
+            clr.RGBpa[i] = (400.0 * temp) / (temp + 27.13) + 0.1;
+        }
+    }
+    
+    clr.A = (((2.0 * clr.RGBpa[0]) + clr.RGBpa[1] + 
+        (clr.RGBpa[2] / 20.0)) - 0.305) * pMod->Nbb;
+
+    return clr;
+}
+
+static
+CAM02COLOR ComputeCorrelates(CAM02COLOR clr, LPcmsCIECAM02 pMod) 
+{
+    double 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;
+    
+    r2d = (180.0 / 3.141592654);
+    if (a == 0) {
+        if (b == 0)     clr.h = 0;
+        else if (b > 0) clr.h = 90;
+        else            clr.h = 270;
+    }
+    else if (a > 0) {
+        temp = b / a;
+        if (b > 0)       clr.h = (r2d * atan(temp));
+        else if (b == 0) clr.h = 0;
+        else             clr.h = (r2d * atan(temp)) + 360;
+    }
+    else {
+        temp = b / a;
+        clr.h = (r2d * atan(temp)) + 180;
+    }
+    
+    d2r = (3.141592654 / 180.0);
+    e = ((12500.0 / 13.0) * pMod->Nc * pMod->Ncb) * 
+        (cos((clr.h * d2r + 2.0)) + 3.8); 
+    
+    if (clr.h < 20.14) {
+        temp = ((clr.h + 122.47)/1.2) + ((20.14 - clr.h)/0.8);
+        clr.H = 300 + (100*((clr.h + 122.47)/1.2)) / temp;
+    }
+    else if (clr.h < 90.0) {
+        temp = ((clr.h - 20.14)/0.8) + ((90.00 - clr.h)/0.7);
+        clr.H = (100*((clr.h - 20.14)/0.8)) / temp;
+    }
+    else if (clr.h < 164.25) {
+        temp = ((clr.h - 90.00)/0.7) + ((164.25 - clr.h)/1.0);
+        clr.H = 100 + ((100*((clr.h - 90.00)/0.7)) / temp);
+    }
+    else if (clr.h < 237.53) {
+        temp = ((clr.h - 164.25)/1.0) + ((237.53 - clr.h)/1.2);
+        clr.H = 200 + ((100*((clr.h - 164.25)/1.0)) / temp);
+    }
+    else {
+        temp = ((clr.h - 237.53)/1.2) + ((360 - clr.h + 20.14)/0.8);
+        clr.H = 300 + ((100*((clr.h - 237.53)/1.2)) / temp);
+    }
+    
+    clr.J = 100.0 * pow((clr.A / pMod->adoptedWhite.A), 
+        (pMod->c * pMod->z));
+
+    clr.Q = (4.0 / pMod->c) * pow((clr.J / 100.0), 0.5) *
+        (pMod->adoptedWhite.A + 4.0) * pow(pMod->FL, 0.25);
+    
+    t = (e * pow(((a * a) + (b * b)), 0.5)) /
+        (clr.RGBpa[0] + clr.RGBpa[1] + 
+        ((21.0 / 20.0) * clr.RGBpa[2]));
+
+    clr.C = pow(t, 0.9) * pow((clr.J / 100.0), 0.5) *
+        pow((1.64 - pow(0.29, pMod->n)), 0.73);
+
+    clr.M = clr.C * pow(pMod->FL, 0.25);
+    clr.s = 100.0 * pow((clr.M / clr.Q), 0.5);
+    
+    return clr;
+}
+
+
+static
+CAM02COLOR InverseCorrelates(CAM02COLOR clr, LPcmsCIECAM02 pMod) 
+{
+    
+    double 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) *
+        (pow((1.64 - pow(0.29, pMod->n)), 0.73)))), 
+        (1.0 / 0.9) );
+    e = ((12500.0 / 13.0) * pMod->Nc * pMod->Ncb) *
+        (cos((clr.h * d2r + 2.0)) + 3.8);
+    
+    clr.A = pMod->adoptedWhite.A * pow(
+           (clr.J / 100.0),
+           (1.0 / (pMod->c * pMod->z)));
+    
+    p1 = e / t;
+    p2 = (clr.A / pMod->Nbb) + 0.305;
+    p3 = 21.0 / 20.0;
+    
+    hr = clr.h * d2r;
+    
+    if (fabs(sin(hr)) >= fabs(cos(hr))) {
+        p4 = p1 / sin(hr);
+        clr.b = (p2 * (2.0 + p3) * (460.0 / 1403.0)) /
+            (p4 + (2.0 + p3) * (220.0 / 1403.0) *
+            (cos(hr) / sin(hr)) - (27.0 / 1403.0) +
+            p3 * (6300.0 / 1403.0));
+        clr.a = clr.b * (cos(hr) / sin(hr));
+    }
+    else {
+        p5 = p1 / cos(hr);
+        clr.a = (p2 * (2.0 + p3) * (460.0 / 1403.0)) /
+            (p5 + (2.0 + p3) * (220.0 / 1403.0) -
+            ((27.0 / 1403.0) - p3 * (6300.0 / 1403.0)) *
+            (sin(hr) / cos(hr)));
+        clr.b = clr.a * (sin(hr) / cos(hr));
+    }
+    
+    clr.RGBpa[0] = ((460.0 / 1403.0) * p2) + 
+              ((451.0 / 1403.0) * clr.a) +
+              ((288.0 / 1403.0) * clr.b);
+    clr.RGBpa[1] = ((460.0 / 1403.0) * p2) - 
+              ((891.0 / 1403.0) * clr.a) -
+              ((261.0 / 1403.0) * clr.b);
+    clr.RGBpa[2] = ((460.0 / 1403.0) * p2) -
+              ((220.0 / 1403.0) * clr.a) -
+              ((6300.0 / 1403.0) * clr.b);
+    
+    return clr;
+}
+
+static
+CAM02COLOR InverseNonlinearity(CAM02COLOR clr, LPcmsCIECAM02 pMod)
+{
+    int i;
+    double c1;
+    
+    for (i = 0; i < 3; i++) {
+        if ((clr.RGBpa[i] - 0.1) < 0) c1 = -1;
+        else                               c1 = 1;
+        clr.RGBp[i] = c1 * (100.0 / pMod->FL) *
+            pow(((27.13 * fabs(clr.RGBpa[i] - 0.1)) /
+            (400.0 - fabs(clr.RGBpa[i] - 0.1))),
+            (1.0 / 0.42));
+    }
+    
+    return clr;
+}
+
+static
+CAM02COLOR HPEtoCAT02(CAM02COLOR clr) 
+{
+    double M[9];
+    
+    M[0] = (( 0.7328 *  1.910197) + (0.4296 * 0.370950));
+    M[1] = (( 0.7328 * -1.112124) + (0.4296 * 0.629054));
+    M[2] = (( 0.7328 *  0.201908) + (0.4296 * 0.000008) - 0.1624);
+    M[3] = ((-0.7036 *  1.910197) + (1.6975 * 0.370950));
+    M[4] = ((-0.7036 * -1.112124) + (1.6975 * 0.629054));
+    M[5] = ((-0.7036 *  0.201908) + (1.6975 * 0.000008) + 0.0061);
+    M[6] = (( 0.0030 *  1.910197) + (0.0136 * 0.370950));
+    M[7] = (( 0.0030 * -1.112124) + (0.0136 * 0.629054));
+    M[8] = (( 0.0030 *  0.201908) + (0.0136 * 0.000008) + 0.9834);;
+    
+    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);
+}
+
+
+static
+CAM02COLOR InverseChromaticAdaptation(CAM02COLOR clr,  LPcmsCIECAM02 pMod) 
+{
+    int 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);
+}
+
+
+static
+CAM02COLOR CAT02toXYZ(CAM02COLOR clr) 
+{
+    clr.XYZ[0] = (clr.RGB[0] *  1.096124) + (clr.RGB[1] * -0.278869) + (clr.RGB[2] *  0.182745);
+    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);
+}
+
+
+
+
+LCMSHANDLE LCMSEXPORT cmsCIECAM02Init(LPcmsViewingConditions pVC)
+{
+    LPcmsCIECAM02 lpMod;
+
+
+   if((lpMod = (LPcmsCIECAM02) _cmsMalloc(sizeof(cmsCIECAM02))) == NULL) {
+        return (LCMSHANDLE) NULL;
+    }
+
+
+    ZeroMemory(lpMod, sizeof(cmsCIECAM02));
+
+    lpMod ->adoptedWhite.XYZ[0] = pVC ->whitePoint.X;
+    lpMod ->adoptedWhite.XYZ[1] = pVC ->whitePoint.Y;
+    lpMod ->adoptedWhite.XYZ[2] = pVC ->whitePoint.Z;
+
+    lpMod -> LA       = pVC ->La;
+    lpMod -> Yb       = pVC ->Yb;
+    lpMod -> D        = pVC ->D_value;
+    lpMod -> surround = pVC ->surround;
+
+    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 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;
+    
+    default:
+        // Average surround
+        lpMod -> F  = 1.0;
+        lpMod -> c  = 0.69;
+        lpMod -> Nc = 1.0;
+    }
+
+    lpMod -> n   = compute_n(lpMod);
+    lpMod -> z   = compute_z(lpMod);
+    lpMod -> Nbb = computeNbb(lpMod);
+    lpMod -> FL  = computeFL(lpMod);
+    
+    if (lpMod -> D == D_CALCULATE ||
+        lpMod -> D == D_CALCULATE_DISCOUNT) {
+
+    lpMod -> D   = computeD(lpMod);
+    }
+    
+    lpMod -> Ncb = lpMod -> Nbb;
+    
+    lpMod -> adoptedWhite = XYZtoCAT02(lpMod -> adoptedWhite);
+    lpMod -> adoptedWhite = ChromaticAdaptation(lpMod -> adoptedWhite, lpMod);
+    lpMod -> adoptedWhite = CAT02toHPE(lpMod -> adoptedWhite);
+    lpMod -> adoptedWhite = NonlinearCompression(lpMod -> adoptedWhite, lpMod);
+
+    return (LCMSHANDLE) lpMod;
+      
+}
+
+void LCMSEXPORT cmsCIECAM02Done(LCMSHANDLE hModel)
+{
+    LPcmsCIECAM02 lpMod = (LPcmsCIECAM02) (LPSTR) hModel;
+    if (lpMod) _cmsFree(lpMod);
+}
+
+
+void LCMSEXPORT cmsCIECAM02Forward(LCMSHANDLE hModel, LPcmsCIEXYZ pIn, LPcmsJCh pOut)
+{    
+    CAM02COLOR clr;
+    LPcmsCIECAM02 lpMod = (LPcmsCIECAM02) (LPSTR) hModel;
+    
+    clr.XYZ[0] = pIn ->X;
+    clr.XYZ[1] = pIn ->Y;
+    clr.XYZ[2] = pIn ->Z;
+    
+    clr = XYZtoCAT02(clr);
+    clr = ChromaticAdaptation(clr, lpMod);
+    clr = CAT02toHPE(clr);
+    clr = NonlinearCompression(clr, lpMod);
+    clr = ComputeCorrelates(clr, lpMod);
+    
+    pOut ->J = clr.J;
+    pOut ->C = clr.C;
+    pOut ->h = clr.h;         
+}
+
+void LCMSEXPORT cmsCIECAM02Reverse(LCMSHANDLE hModel, LPcmsJCh pIn, LPcmsCIEXYZ pOut)
+{
+    CAM02COLOR clr;
+    LPcmsCIECAM02 lpMod = (LPcmsCIECAM02) (LPSTR) hModel;
+    
+    
+    clr.J = pIn -> J;
+    clr.C = pIn -> C;
+    clr.h = pIn -> h;
+    
+    clr = InverseCorrelates(clr, lpMod);
+    clr = InverseNonlinearity(clr, lpMod);
+    clr = HPEtoCAT02(clr);
+    clr = InverseChromaticAdaptation(clr, lpMod);
+    clr = CAT02toXYZ(clr);
+    
+    pOut ->X = clr.XYZ[0];
+    pOut ->Y = clr.XYZ[1];
+    pOut ->Z = clr.XYZ[2];
+    
+}
+
new file mode 100644
--- /dev/null
+++ b/modules/lcms/src/cmscam97.c
@@ -0,0 +1,721 @@
+//
+//  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, (LPVEC3) &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
+
+}
new file mode 100644
--- /dev/null
+++ b/modules/lcms/src/cmscgats.c
@@ -0,0 +1,2460 @@
+//
+//  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.
+// 
+// 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 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 int             LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE IT8, char ***PropertyNames);
+
+// 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
+#define MAXSTR      255     // Max lenght of string
+#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	'\\'
+#else
+#define	DIR_CHAR	'/'
+#endif
+
+// Symbols
+
+typedef enum { 
+
+        SNONE,
+        SINUM,      // Integer
+        SDNUM,      // Real
+        SIDENT,     // Identifier
+        SSTRING,    // string
+        SCOMMENT,   // comment
+        SEOLN,      // End of line
+        SEOF,       // End of stream
+        SSYNERROR,  // Syntax error found on stream
+
+        // Keywords
+
+        SBEGIN_DATA,
+        SBEGIN_DATA_FORMAT,
+        SEND_DATA,
+        SEND_DATA_FORMAT,
+        SKEYWORD,
+        SINCLUDE
+
+    } SYMBOL;
+
+
+// How to write the value
+
+typedef enum { 
+        WRITE_UNCOOKED,
+        WRITE_STRINGIFY,            
+        WRITE_HEXADECIMAL,
+        WRITE_BINARY
+
+    } WRITEMODE;
+
+// Linked list of variable names
+
+typedef struct _KeyVal {
+
+        struct _KeyVal*  Next;
+        char*            Keyword;       // Name of variable
+        char*            Value;         // Points to value
+        WRITEMODE        WriteAs;       // How to write the value
+
+   } KEYVALUE, *LPKEYVALUE;
+
+
+// Linked list of memory chunks (Memory sink)
+
+typedef struct _OwnedMem {
+
+        struct _OwnedMem* Next;
+        void *            Ptr;          // Point to value
+
+   } OWNEDMEM, *LPOWNEDMEM;
+
+// Suballocator
+
+typedef struct _SubAllocator {
+
+         LPBYTE Block;
+         size_t BlockSize;
+         size_t Used;
+ 
+    } SUBALLOCATOR, *LPSUBALLOCATOR;
+
+// 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
+        
+        char**         DataFormat;            // The binary stream descriptor
+        char**         Data;                  // The binary stream        
+
+    } TABLE, *LPTABLE;
+
+// 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.
+
+typedef struct {
+
+        char SheetType[MAXSTR];  
+
+        int  TablesCount;                     // How many tables in this stream
+        int  nTable;                          // The actual table
+
+        TABLE Tab[MAXTABLES];
+
+        // Memory management
+
+        LPOWNEDMEM     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
+        char           id[MAXID];             // identifier
+        char           str[MAXSTR];           // string
+
+        // Allowed keywords & datasets. They have visibility on whole stream
+
+        LPKEYVALUE     ValidKeywords;
+        LPKEYVALUE     ValidSampleID;
+              
+        char*          Source;                // Points to loc. being parsed
+        int            lineno;                // line counter for error reporting
+       
+		LPFILECTX      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;
+
+
+
+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
+
+
+// A keyword
+typedef struct {
+
+        const char *id;
+        SYMBOL sy;
+
+   } KEYWORD;
+
+// 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 },
+        {"END_DATA",            SEND_DATA},
+        {"END_DATA_FORMAT",     SEND_DATA_FORMAT},
+        {"KEYWORD",             SKEYWORD}
+        
+        };
+
+#define NUMKEYS (sizeof(TabKeys)/sizeof(KEYWORD))
+
+// Predefined properties
+
+static const char* PredefinedProperties[] = {
+
+        "NUMBER_OF_FIELDS",    // Required - NUMBER OF FIELDS
+        "NUMBER_OF_SETS",      // Required - NUMBER OF SETS
+        "ORIGINATOR",          // Required - Identifies the specific system, organization or individual that created the data file.
+        "FILE_DESCRIPTOR",     // Required - Describes the purpose or contents of the data file.
+        "CREATED",             // Required - Indicates date of creation of the data file.
+        "DESCRIPTOR",          // Required  - Describes the purpose or contents of the data file.
+        "DIFFUSE_GEOMETRY",    // The diffuse geometry used. Allowed values are "sphere" or "opal".
+        "MANUFACTURER",
+        "MANUFACTURE",         // Some broken Fuji targets does store this value
+        "PROD_DATE",           // Identifies year and month of production of the target in the form yyyy:mm.
+        "SERIAL",              // Uniquely identifies individual physical target.
+
+        "MATERIAL",            // Identifies the material on which the target was produced using a code
+                               // uniquely identifying th e material. This is intend ed to be used for IT8.7
+                               // physical targets only (i.e . IT8.7/1 a nd IT8.7/2).
+
+        "INSTRUMENTATION",     // Used to report the specific instrumentation used (manufacturer and
+                               // model number) to generate the data reported. This data will often
+                               // provide more information about the particular data collected than an
+                               // extensive list of specific details. This is particularly important for
+                               // spectral data or data derived from spectrophotometry.
+
+        "MEASUREMENT_SOURCE",  // Illumination used for spectral measurements. This data helps provide
+                               // a guide to the potential for issues of paper fluorescence, etc.
+
+        "PRINT_CONDITIONS",    // Used to define the characteristics of the printed sheet being reported.
+                               // Where standard conditions have been defined (e.g., SWOP at nominal)
+                               // named conditions may suffice. Otherwise, detailed information is
+                               // needed.
+
+        "SAMPLE_BACKING",      // Identifies the backing material used behind the sample during
+                               // measurement. Allowed values are “black”, “white”, or "na".
+
+        "CHISQ_DOF"            // Degrees of freedom associated with the Chi squared statistic
+};
+
+#define NUMPREDEFINEDPROPS (sizeof(PredefinedProperties)/sizeof(char *))
+
+
+// Predefined sample types on dataset
+static const char* PredefinedSampleID[] = {
+
+        "CMYK_C",         // Cyan component of CMYK data expressed as a percentage
+        "CMYK_M",         // Magenta component of CMYK data expressed as a percentage
+        "CMYK_Y",         // Yellow component of CMYK data expressed as a percentage
+        "CMYK_K",         // Black component of CMYK data expressed as a percentage
+        "D_RED",          // Red filter density
+        "D_GREEN",        // Green filter density
+        "D_BLUE",         // Blue filter density
+        "D_VIS",          // Visual filter density
+        "D_MAJOR_FILTER", // Major filter d ensity
+        "RGB_R",          // Red component of RGB data
+        "RGB_G",          // Green component of RGB data
+        "RGB_B",          // Blue com ponent of RGB data
+        "SPECTRAL_NM",    // Wavelength of measurement expressed in nanometers
+        "SPECTRAL_PCT",   // Percentage reflectance/transmittance
+        "SPECTRAL_DEC",   // Reflectance/transmittance
+        "XYZ_X",          // X component of tristimulus data
+        "XYZ_Y",          // Y component of tristimulus data
+        "XYZ_Z",          // Z component of tristimulus data
+        "XYY_X"           // x component of chromaticity data
+        "XYY_Y",          // y component of chromaticity data
+        "XYY_CAPY",       // Y component of tristimulus data
+        "LAB_L",          // L* component of Lab data
+        "LAB_A",          // a* component of Lab data
+        "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_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)
+        "STDEV_X",        // Standard deviation of X (tristimulus data)
+        "STDEV_Y",        // Standard deviation of Y (tristimulus data)
+        "STDEV_Z",        // Standard deviation of Z (tristimulus data)
+        "STDEV_L",        // Standard deviation of L*
+        "STDEV_A"         // Standard deviation of a*
+        "STDEV_B",        // Standard deviation of b*
+        "STDEV_DE",       // Standard deviation of CIE dE
+        "CHI_SQD_PAR"};   // The average of the standard deviations of L*, a* and b*. It is
+                          // used to derive an estimate of the chi-squared parameter which is
+                          // recommended as the predictor of the variability of dE
+
+#define NUMPREDEFINEDSAMPLEID (sizeof(PredefinedSampleID)/sizeof(char *))
+
+//Forward declaration of some internal functions		
+static void* AllocChunk(LPIT8 it8, size_t size);
+
+// Checks if c is a separator
+static
+LCMSBOOL isseparator(int c)
+{
+        return (c == ' ') || (c == '\t') || (c == '\r');
+}
+
+// Checks whatever if c is a valid identifier char
+static 
+LCMSBOOL 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)
+{
+   return isalnum(c) || ismiddle(c);
+}
+
+// Checks whatsever if c is a valid identifier first char.
+static
+LCMSBOOL 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
+static
+LCMSBOOL isabsolutepath(const char *path)
+{
+	if(path == NULL)
+		return FALSE;
+	
+    if(path[0] == DIR_CHAR)
+		return TRUE;
+
+#ifndef	NON_WINDOWS
+	if(isalpha(path[0]) && path[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)
+{
+	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;
+		}
+	}
+	strncpy(buffer, relPath, MAX_PATH - 1);
+	return TRUE;
+}
+
+
+// Make sure no exploit is being even tried
+
+static
+const char* NoMeta(const char* str)
+{
+    if (strchr(str, '%') != NULL) 
+        return "**** CORRUPTED FORMAT STRING ***";
+
+    return str;
+}
+
+
+// Syntax error
+static
+LCMSBOOL SynError(LPIT8 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;
+}
+
+// Check if current symbol is same as specified. issue an error else.
+static
+LCMSBOOL Check(LPIT8 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)
+{
+    if (it8 -> FileStack[it8 ->IncludeSP]->Stream) {
+
+        it8 ->ch = fgetc(it8 ->FileStack[it8 ->IncludeSP]->Stream);
+
+        if (feof(it8 -> FileStack[it8 ->IncludeSP]->Stream))  {
+
+            if (it8 ->IncludeSP > 0) {
+
+                fclose(it8 ->FileStack[it8->IncludeSP--]->Stream);
+                it8 -> ch = ' ';                            // Whitespace to be ignored
+
+            } else
+                it8 ->ch = 0;   // EOF
+        }
+        
+        
+
+    }
+    else {
+        it8->ch = *it8->Source;
+        if (it8->ch) it8->Source++;
+    }
+}
+
+
+// Try to see if current identifier is a keyword, if so return the referred symbol
+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;
+}
+
+
+// 10 ^n
+static
+double xpow10(int n)
+{
+    return pow(10, (double) n);
+}
+
+
+//  Reads a Real number, tries to follow from integer number
+static
+void ReadReal(LPIT8 it8, int inum)
+{
+        it8->dnum = (double) 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));
+        }
+
+        // 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);
+        }
+}
+
+
+
+// Reads next symbol
+static
+void InSymbol(LPIT8 it8)
+{
+    register char *idptr;
+    register int k;
+    SYMBOL key;
+    int sng;
+    
+    do {
+        
+        while (isseparator(it8->ch))
+            NextCh(it8);
+        
+        if (isfirstidchar(it8->ch)) {          // Identifier
+            
+            
+            k = 0;
+            idptr = it8->id;
+            
+            do {
+                
+                if (++k < MAXID) *idptr++ = (char) it8->ch;
+                
+                NextCh(it8);
+                
+            } while (isidchar(it8->ch));
+            
+            *idptr = '\0';
+            
+            
+            key = BinSrchKey(it8->id);
+            if (key == SNONE) it8->sy = SIDENT;
+            else it8->sy = key;
+            
+        }
+        else                         // Is a number?
+            if (isdigit(it8->ch) || it8->ch == '.' || it8->ch == '-' || it8->ch == '+')
+            {
+                int sign = 1;
+                
+                if (it8->ch == '-') {
+                    sign = -1;
+                    NextCh(it8);
+                }
+                
+                it8->inum = 0;
+                it8->sy   = SINUM;
+                
+                if (it8->ch == '0') {          // 0xnnnn (Hexa) or 0bnnnn (Binary)
+                
+                    NextCh(it8);
+                    if (toupper(it8->ch) == 'X') {
+
+                        int j;
+                        
+                        NextCh(it8);
+                        while (isxdigit(it8->ch))
+                        {
+                            it8->ch = toupper(it8->ch);
+                            if (it8->ch >= 'A' && it8->ch <= 'F')  j = it8->ch -'A'+10;
+                            else j = it8->ch - '0';
+                            
+                            if ((long) it8->inum * 16L > (long) INT_MAX)
+                            {
+                                SynError(it8, "Invalid hexadecimal number");
+                                return;
+                            }
+                            
+                            it8->inum = it8->inum * 16 + j;
+                            NextCh(it8);
+                        }
+                        return;
+                    }
+                    
+                    if (toupper(it8->ch) == 'B') {  // Binary
+                    
+                        int j;
+                        
+                        NextCh(it8);
+                        while (it8->ch == '0' || it8->ch == '1')
+                        {
+                            j = it8->ch - '0';
+                            
+                            if ((long) it8->inum * 2L > (long) INT_MAX)
+                            {
+                                SynError(it8, "Invalid binary number");
+                                return;
+                            }
+                            
+                            it8->inum = it8->inum * 2 + j;
+                            NextCh(it8);
+                        }
+                        return;
+                    }
+                }
+                
+
+                while (isdigit(it8->ch)) {
+
+                    if ((long) it8->inum * 10L > (long) INT_MAX) {
+                        ReadReal(it8, it8->inum);
+                        it8->sy = SDNUM;
+                        it8->dnum *= sign;
+                        return;
+                    }
+                    
+                    it8->inum = it8->inum * 10 + (it8->ch - '0');
+                    NextCh(it8);
+                }
+                
+                if (it8->ch == '.') {
+                    
+                    ReadReal(it8, it8->inum);
+                    it8->sy = SDNUM;
+                    it8->dnum *= sign;
+                    return;
+                }
+                
+                it8 -> inum *= sign;
+
+                // Special case. Numbers followed by letters are taken as identifiers
+
+                if (isidchar(it8 ->ch)) {
+
+                    if (it8 ->sy == SINUM) {
+
+                        sprintf(it8->id, "%d", it8->inum);
+                    }
+                    else {
+
+                        sprintf(it8->id, it8 ->DoubleFormatter, it8->dnum);
+                    }
+
+                    k = (int) strlen(it8 ->id);
+                    idptr = it8 ->id + k;
+                    do {
+                
+                        if (++k < MAXID) *idptr++ = (char) it8->ch;
+                
+                        NextCh(it8);
+                
+                    } while (isidchar(it8->ch));
+            
+                    *idptr = '\0';
+                    
+                    it8->sy = SIDENT;
+                }
+                return;
+                
+            }
+            else
+                switch ((int) it8->ch) {
+
+        // EOF marker -- ignore it
+        case '\x1a':
+            NextCh(it8);
+            break;
+
+        // Eof stream markers
+
+        case 0:
+        case -1:
+            it8->sy = SEOF;
+            break;
+            
+            
+        // Next line
+            
+        case '\n':
+            NextCh(it8);
+            it8->sy = SEOLN;
+            it8->lineno++;
+            break;
+            
+        // Comment
+            
+        case '#':
+            NextCh(it8);
+            while (it8->ch && it8->ch != '\n')
+                NextCh(it8);
+            
+            it8->sy = SCOMMENT;
+            break;
+            
+            // String.
+            
+        case '\'':
+        case '\"':
+            idptr = it8->str;
+            sng = it8->ch;
+            k = 0;
+            NextCh(it8);
+            
+            while (k < MAXSTR && it8->ch != sng) {
+                
+                if (it8->ch == '\n'|| it8->ch == '\r') k = MAXSTR+1;
+                else {                                    
+                    *idptr++ = (char) it8->ch;
+                    NextCh(it8);
+                    k++;
+                }
+            }
+            
+            it8->sy = SSTRING;
+            *idptr = '\0';
+            NextCh(it8);
+            break;
+            
+            
+        default:
+            SynError(it8, "Unrecognized character: 0x%x", it8 ->ch);            
+            return;            
+            }
+            
+    } while (it8->sy == SCOMMENT);
+
+    // Handle the include special token
+
+    if (it8 -> sy == SINCLUDE) {
+
+                LPFILECTX FileNest;
+
+				if(it8 -> IncludeSP >= (MAXINCLUDE-1))
+				{
+					SynError(it8, "Too many recursion levels");
+					return;
+				}
+
+                InSymbol(it8);
+                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)
+						//	TODO: how to manage out-of-memory conditions?
+				}
+
+				if(_cmsMakePath(it8->str, it8->FileStack[it8->IncludeSP]->FileName, FileNest->FileName) == FALSE)
+				{
+					SynError(it8, "File path too long");
+					return;
+				}
+
+                FileNest->Stream = fopen(FileNest->FileName, "rt");
+                if (FileNest->Stream == NULL) {
+
+                        SynError(it8, "File %s not found", FileNest->FileName);
+                        return;
+                }
+				it8->IncludeSP++;
+
+                it8 ->ch = ' ';
+                InSymbol(it8);    
+    }
+                
+}
+
+// Checks end of line separator
+static
+LCMSBOOL CheckEOLN(LPIT8 it8)
+{
+        if (!Check(it8, SEOLN, "Expected separator")) return FALSE;
+        while (it8 -> sy == SEOLN)
+                        InSymbol(it8);
+        return TRUE;
+
+}
+
+// Skip a symbol
+
+static
+void Skip(LPIT8 it8, SYMBOL sy)
+{
+        if (it8->sy == sy && it8->sy != SEOF)
+                        InSymbol(it8);
+}
+
+
+// Skip multiple EOLN
+static
+void SkipEOLN(LPIT8 it8)
+{
+    while (it8->sy == SEOLN) {
+             InSymbol(it8);
+    }
+}
+
+
+// Returns a string holding current value
+static
+LCMSBOOL GetVal(LPIT8 it8, char* Buffer, size_t max, const char* ErrorTitle)
+{
+    switch (it8->sy) {
+
+    case SIDENT:  strncpy(Buffer, it8->id, max); break;
+    case SINUM:   snprintf(Buffer, max, "%d", it8 -> inum); break;
+    case SDNUM:   snprintf(Buffer, max, it8->DoubleFormatter, it8 -> dnum); break;
+    case SSTRING: strncpy(Buffer, it8->str, max); break;
+
+
+    default:
+         return SynError(it8, "%s", ErrorTitle);
+    }
+
+    Buffer[max] = 0;
+    return TRUE;
+}
+
+// ---------------------------------------------------------- Table
+
+static
+LPTABLE GetTable(LPIT8 it8)
+{        
+   if ((it8 -> nTable >= it8 ->TablesCount) || (it8 -> nTable < 0)) {
+
+           SynError(it8, "Table %d out of sequence", it8 -> nTable);
+           return it8 -> Tab;
+   }            
+
+   return it8 ->Tab + it8 ->nTable;
+}
+
+// ---------------------------------------------------------- Memory management
+
+
+
+// Frees an allocator and owned memory
+void LCMSEXPORT cmsIT8Free(LCMSHANDLE hIT8)
+{
+   LPIT8 it8 = (LPIT8) hIT8;
+
+    if (it8 == NULL)
+        return;
+
+
+    if (it8->MemorySink) {
+
+        LPOWNEDMEM p;
+        LPOWNEDMEM n;
+
+        for (p = it8->MemorySink; p != NULL; p = n) {
+
+            n = p->Next;
+            if (p->Ptr) _cmsFree(p->Ptr);
+            _cmsFree(p);
+        }
+    }
+
+    if (it8->MemoryBlock)
+        _cmsFree(it8->MemoryBlock);    
+
+     _cmsFree(it8);
+}
+
+
+// Allocates a chunk of data, keep linked list
+static
+void* AllocBigBlock(LPIT8 it8, size_t 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;
+        }
+
+        return ptr;
+}
+
+
+// Suballocator.
+static
+void* AllocChunk(LPIT8 it8, size_t size)
+{
+    size_t free = it8 ->Allocator.BlockSize - it8 ->Allocator.Used;
+    LPBYTE ptr;
+
+    size = ALIGNLONG(size);
+
+    if (size > free) {
+
+        if (it8 -> Allocator.BlockSize == 0)
+
+                it8 -> Allocator.BlockSize = 20*1024;
+        else
+                it8 ->Allocator.BlockSize *= 2;
+
+        if (it8 ->Allocator.BlockSize < size)
+                it8 ->Allocator.BlockSize = size;
+
+        it8 ->Allocator.Used = 0;
+        it8 ->Allocator.Block = (LPBYTE) AllocBigBlock(it8, it8 ->Allocator.BlockSize);
+    }
+            
+    ptr = it8 ->Allocator.Block + it8 ->Allocator.Used;
+    it8 ->Allocator.Used += size;
+
+    return (void*) ptr;
+    
+}
+
+
+// Allocates a string
+static
+char *AllocString(LPIT8 it8, const char* str)
+{
+    size_t Size = strlen(str)+1;
+    char *ptr;
+
+
+    ptr = (char *) AllocChunk(it8, Size);
+    if (ptr) strncpy (ptr, str, Size-1);
+
+    return ptr;
+}  
+
+// Searches through linked list
+
+static
+LCMSBOOL IsAvailableOnList(LPKEYVALUE p, const char* Key, LPKEYVALUE* LastPtr)
+{
+
+    for (;  p != NULL; p = p->Next) {
+
+        if (LastPtr) *LastPtr = p;
+
+        if (*Key != '#') { // Comments are ignored
+
+            if (stricmp(Key, p->Keyword) == 0)
+                    return TRUE;
+        }
+    }
+
+    return FALSE;
+}
+
+
+
+// Add a property into a linked list
+static
+LCMSBOOL AddToList(LPIT8 it8, LPKEYVALUE* Head, const char *Key, const char* xValue, WRITEMODE WriteAs)
+{
+    LPKEYVALUE p;
+    LPKEYVALUE last;
+
+
+    // Check if property is already in list (this is an error)
+
+    if (IsAvailableOnList(*Head, Key, &last)) {
+
+			// This may work for editing properties
+
+			 last->Value   = AllocString(it8, xValue);
+			 last->WriteAs = WriteAs;
+			 return TRUE;                                               
+    }
+
+    // Allocate the container
+    p = (LPKEYVALUE) AllocChunk(it8, sizeof(KEYVALUE));
+    if (p == NULL)
+    {
+        return SynError(it8, "AddToList: out of memory");        
+    }
+
+    // Store name and value
+    p->Keyword = AllocString(it8, Key);
+
+    if (xValue != NULL) {
+
+        p->Value   = AllocString(it8, xValue);
+    }
+    else {
+        p->Value   = NULL;
+    }
+
+    p->Next    = NULL;
+    p->WriteAs = WriteAs;
+
+    // Keep the container in our list
+    if (*Head == NULL)
+        *Head = p;
+    else
+        last->Next = p;
+
+    return TRUE;
+}
+
+static
+LCMSBOOL AddAvailableProperty(LPIT8 it8, const char* Key)
+{
+        return AddToList(it8, &it8->ValidKeywords, Key, NULL, WRITE_UNCOOKED);
+}
+
+
+static
+LCMSBOOL AddAvailableSampleID(LPIT8 it8, const char* Key)
+{
+        return AddToList(it8, &it8->ValidSampleID, Key, NULL, WRITE_UNCOOKED);
+}
+
+
+static
+void AllocTable(LPIT8 it8)
+{
+    LPTABLE t;
+
+    t = it8 ->Tab + it8 ->TablesCount;
+
+    t->HeaderList = NULL;
+    t->DataFormat = NULL;
+    t->Data       = NULL;
+   
+    it8 ->TablesCount++;
+}
+
+
+int LCMSEXPORT cmsIT8SetTable(LCMSHANDLE IT8, int nTable)
+{
+     LPIT8 it8 = (LPIT8) IT8;
+
+     if (nTable >= it8 ->TablesCount) {
+
+         if (nTable == it8 ->TablesCount) {
+
+             AllocTable(it8);
+         }
+         else {
+             SynError(it8, "Table %d is out of sequence", nTable);
+             return -1;
+         }
+     }
+
+     it8 ->nTable = nTable;
+
+     return nTable;
+}
+
+
+
+// Init an empty container
+LCMSHANDLE LCMSEXPORT cmsIT8Alloc(void)
+{
+    LPIT8 it8;
+    int i;
+
+    it8 = (LPIT8) _cmsMalloc(sizeof(IT8));
+    if (it8 == NULL) return NULL;
+
+    ZeroMemory(it8, sizeof(IT8));
+
+    AllocTable(it8);
+    
+    it8->MemoryBlock = NULL;
+    it8->MemorySink  = NULL;
+    
+    it8 ->nTable = 0;
+
+    it8->Allocator.Used = 0;
+    it8->Allocator.Block = NULL;
+    it8->Allocator.BlockSize = 0;  
+
+    it8->ValidKeywords = NULL;
+    it8->ValidSampleID = NULL;
+
+    it8 -> sy = SNONE;
+    it8 -> ch = ' ';
+    it8 -> Source = NULL;
+    it8 -> inum = 0;
+    it8 -> dnum = 0.0;
+
+	it8->FileStack[0] = (LPFILECTX)AllocChunk(it8, sizeof(FILECTX));
+    it8->IncludeSP   = 0;
+    it8 -> lineno = 1;
+
+    strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
+    strcpy(it8->SheetType, "CGATS.17");
+
+    // Initialize predefined properties & data
+    
+    for (i=0; i < NUMPREDEFINEDPROPS; i++)
+            AddAvailableProperty(it8, PredefinedProperties[i]);
+
+    for (i=0; i < NUMPREDEFINEDSAMPLEID; i++)
+            AddAvailableSampleID(it8, PredefinedSampleID[i]);
+
+
+   return (LCMSHANDLE) it8;
+}
+
+
+const char* LCMSEXPORT cmsIT8GetSheetType(LCMSHANDLE hIT8)
+{
+        LPIT8 it8 = (LPIT8) hIT8;
+
+        return it8 ->SheetType;
+
+}
+
+LCMSBOOL  LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type)
+{
+        LPIT8 it8 = (LPIT8) hIT8;
+
+        strncpy(it8 ->SheetType, Type, MAXSTR-1);
+        return TRUE;
+}
+
+LCMSBOOL LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* Val)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+
+    if (!Val) return FALSE;
+    if (!*Val) return FALSE;
+
+    return AddToList(it8, &GetTable(it8)->HeaderList, "# ", Val, WRITE_UNCOOKED);
+}
+
+
+
+// Sets a property
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* Key, const char *Val)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+
+    if (!Val) return FALSE;
+    if (!*Val) return FALSE;
+
+    return AddToList(it8, &GetTable(it8)->HeaderList, Key, Val, WRITE_STRINGIFY);
+}
+
+
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    char Buffer[1024];
+   
+    sprintf(Buffer, it8->DoubleFormatter, Val);
+
+    return AddToList(it8, &GetTable(it8)->HeaderList, cProp, Buffer, WRITE_UNCOOKED);    
+}
+
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    char Buffer[1024];
+   
+    sprintf(Buffer, "%d", Val);
+
+    return AddToList(it8, &GetTable(it8)->HeaderList, cProp, Buffer, WRITE_HEXADECIMAL);    
+}
+
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer)
+{
+    LPIT8 it8 = (LPIT8) hIT8;    
+    
+    return AddToList(it8, &GetTable(it8)->HeaderList, Key, Buffer, WRITE_UNCOOKED);
+}
+
+
+// Gets a property
+const char* LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* Key)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    LPKEYVALUE p;
+
+    if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, &p))
+    {
+        return p -> Value;
+    }
+    return NULL;
+}
+
+
+double LCMSEXPORT cmsIT8GetPropertyDbl(LCMSHANDLE hIT8, const char* cProp)
+{
+    const char *v = cmsIT8GetProperty(hIT8, cProp);
+
+    if (v) return atof(v);
+    else return 0.0;
+}
+
+// ----------------------------------------------------------------- Datasets
+
+
+static
+void AllocateDataFormat(LPIT8 it8)
+{
+    LPTABLE t = GetTable(it8);
+
+    if (t -> DataFormat) return;    // Already allocated
+
+    t -> nSamples  = (int) cmsIT8GetPropertyDbl(it8, "NUMBER_OF_FIELDS");
+
+    if (t -> nSamples <= 0) {
+
+        SynError(it8, "AllocateDataFormat: Unknown NUMBER_OF_FIELDS");
+        t -> nSamples = 10;
+        }
+
+    t -> DataFormat = (char**) AllocChunk (it8, (t->nSamples + 1) * sizeof(char *));
+    if (t->DataFormat == NULL)
+    {
+        SynError(it8, "AllocateDataFormat: Unable to allocate dataFormat array");
+    }
+
+}
+
+static
+const char *GetDataFormat(LPIT8 it8, int n)
+{
+    LPTABLE t = GetTable(it8);
+
+    if (t->DataFormat)
+        return t->DataFormat[n];
+
+    return NULL;
+}
+
+static
+LCMSBOOL SetDataFormat(LPIT8 it8, int n, const char *label)
+{
+    LPTABLE t = GetTable(it8);
+
+    if (!t->DataFormat)
+        AllocateDataFormat(it8);
+
+    if (n > t -> nSamples) {
+        SynError(it8, "More than NUMBER_OF_FIELDS fields.");
+        return FALSE;
+    }
+
+    
+    if (t->DataFormat) {                
+        t->DataFormat[n] = AllocString(it8, label);
+    }
+
+    return TRUE;
+}
+
+
+LCMSBOOL LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE h, int n, const char *Sample)
+{
+        LPIT8 it8 = (LPIT8) h;
+        return SetDataFormat(it8, n, Sample);
+}
+
+static
+void AllocateDataSet(LPIT8 it8)
+{
+    LPTABLE t = GetTable(it8);
+
+    if (t -> Data) return;    // Already allocated
+
+    t-> nSamples   = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
+    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)
+    {
+        SynError(it8, "AllocateDataSet: Unable to allocate data array");
+    }
+
+}
+
+static
+char* GetData(LPIT8 it8, int nSet, int nField)
+{
+    LPTABLE t = GetTable(it8);
+    int  nSamples   = t -> nSamples;
+    int  nPatches   = t -> nPatches;
+    
+
+    if (nSet >= nPatches || nField >= nSamples)
+        return NULL;
+
+    if (!t->Data) return NULL;
+    return t->Data [nSet * nSamples + nField];
+}
+
+static
+LCMSBOOL SetData(LPIT8 it8, int nSet, int nField, const char *Val)
+{
+    LPTABLE 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);            
+    }
+
+    if (nField > t ->nSamples || nField < 0) {
+            return SynError(it8, "Sample %d out of range, there are %d samples", nField, t ->nSamples);
+            
+    }
+
+            
+    t->Data [nSet * t -> nSamples + nField] = AllocString(it8, Val);
+    return TRUE;
+}
+
+
+// --------------------------------------------------------------- File I/O
+
+
+// Writes a string to file
+static
+void WriteStr(LPSAVESTREAM f, const char *str)
+{
+	
+	size_t len;
+
+	if (str == NULL) 
+		str = " ";
+	
+	// Lenghth to write
+	len = strlen(str);
+    f ->Used += len;
+	
+
+	if (f ->stream) {	// Should I write it to a file?
+
+		fwrite(str, 1, len, f->stream);
+		
+	}
+	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;
+			}
+			
+			CopyMemory(f ->Ptr, str, len);
+			f->Ptr += len;
+			
+		}
+						
+	}	
+}
+
+
+// Write formatted
+
+static
+void Writef(LPSAVESTREAM f, const char* frm, ...)
+{
+    char Buffer[4096];
+    va_list args;
+
+    va_start(args, frm);
+    vsnprintf(Buffer, 4095, frm, args);
+    Buffer[4095] = 0;
+    WriteStr(f, Buffer);
+    va_end(args);
+
+}
+
+// Writes full header
+static
+void WriteHeader(LPIT8 it8, LPSAVESTREAM fp)
+{
+    LPKEYVALUE p;
+    LPTABLE t = GetTable(it8);
+
+    
+    for (p = t->HeaderList; (p != NULL); p = p->Next)
+    {
+        if (*p ->Keyword == '#') {
+
+            char* Pt;
+            
+            WriteStr(fp, "#\n# ");
+            for (Pt = p ->Value; *Pt; Pt++) {
+
+
+				Writef(fp, "%c", *Pt);                
+
+                if (*Pt == '\n') {
+                    WriteStr(fp, "# ");
+                }
+            }
+        
+            WriteStr(fp, "\n#\n");
+            continue;
+        }
+
+
+        if (!IsAvailableOnList(it8-> ValidKeywords, p->Keyword, NULL)) {
+
+#ifdef STRICT_CGATS
+            WriteStr(fp, "KEYWORD\t\"");
+            WriteStr(fp, p->Keyword);
+            WriteStr(fp, "\"\n");
+#endif
+
+            AddAvailableProperty(it8, p->Keyword);
+
+        }
+
+        WriteStr(fp, p->Keyword);
+        if (p->Value) {
+
+            switch (p ->WriteAs) {
+
+            case WRITE_UNCOOKED:
+                    Writef(fp, "\t%s", p ->Value);                    
+                    break;
+
+            case WRITE_STRINGIFY:
+                    Writef(fp, "\t\"%s\"", p->Value );
+                    break;
+
+            case WRITE_HEXADECIMAL:
+                    Writef(fp, "\t0x%X", atoi(p ->Value));
+                    break;
+
+            case WRITE_BINARY:
+                    Writef(fp, "\t0x%B", atoi(p ->Value));
+                    break;
+
+            default: SynError(it8, "Unknown write mode %d", p ->WriteAs);
+                     return;
+            }
+        }
+
+        WriteStr (fp, "\n");
+    }
+
+}
+
+
+// Writes the data format
+static
+void WriteDataFormat(LPSAVESTREAM fp, LPIT8 it8)
+{
+    int i, nSamples;
+    LPTABLE t = GetTable(it8);
+
+    if (!t -> DataFormat) return;
+
+       WriteStr(fp, "BEGIN_DATA_FORMAT\n");
+       WriteStr(fp, " ");
+       nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
+
+       for (i = 0; i < nSamples; i++) {
+
+              WriteStr(fp, t->DataFormat[i]);
+              WriteStr(fp, ((i == (nSamples-1)) ? "\n" : "\t"));
+          }
+
+       WriteStr (fp, "END_DATA_FORMAT\n");
+}
+
+
+// Writes data array
+static
+void WriteData(LPSAVESTREAM fp, LPIT8 it8)
+{
+       int  i, j;
+       LPTABLE t = GetTable(it8);
+
+       if (!t->Data) return;
+
+       WriteStr (fp, "BEGIN_DATA\n");
+
+       t->nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
+
+       for (i = 0; i < t-> nPatches; i++) {
+
+              WriteStr(fp, " ");
+
+              for (j = 0; j < t->nSamples; j++) {
+
+                     char *ptr = t->Data[i*t->nSamples+j];
+
+                     if (ptr == NULL) WriteStr(fp, "\"\"");
+                     else {
+                         // If value contains whitespace, enclose within quote
+
+                         if (strchr(ptr, ' ') != NULL) {
+
+                             WriteStr(fp, "\"");
+                             WriteStr(fp, ptr);
+                             WriteStr(fp, "\"");
+                         }
+                         else
+                            WriteStr(fp, ptr);
+                     }
+
+                     WriteStr(fp, ((j == (t->nSamples-1)) ? "\n" : "\t"));
+              }
+       }
+       WriteStr (fp, "END_DATA\n");
+}
+
+
+
+// Saves whole file
+LCMSBOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE hIT8, const char* cFileName)
+{
+    SAVESTREAM sd;	
+    int i;
+    LPIT8 it8 = (LPIT8) hIT8;
+
+	ZeroMemory(&sd, sizeof(SAVESTREAM));
+
+    sd.stream = fopen(cFileName, "wt");
+    if (!sd.stream) return FALSE;
+    
+    WriteStr(&sd, it8->SheetType);
+    WriteStr(&sd, "\n");
+    for (i=0; i < it8 ->TablesCount; i++) {
+
+            cmsIT8SetTable(hIT8, i);
+            WriteHeader(it8, &sd);
+            WriteDataFormat(&sd, it8);
+            WriteData(&sd, it8);
+    }
+    
+	fclose(sd.stream);
+
+    return TRUE;
+}
+
+
+// Saves to memory
+LCMSBOOL LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded)
+{
+    SAVESTREAM sd;	
+    int i;
+    LPIT8 it8 = (LPIT8) hIT8;
+
+	ZeroMemory(&sd, sizeof(SAVESTREAM));
+
+    sd.stream = NULL;
+	sd.Base   = (LPBYTE) MemPtr;
+	sd.Ptr    = sd.Base;
+
+	sd.Used = 0;
+
+	if (sd.Base) 
+		sd.Max  = *BytesNeeded;		// Write to memory?
+	else 
+		sd.Max  = 0;				// Just counting the needed bytes
+   
+    WriteStr(&sd, it8->SheetType);
+    WriteStr(&sd, "\n");
+    for (i=0; i < it8 ->TablesCount; i++) {
+
+            cmsIT8SetTable(hIT8, i);
+            WriteHeader(it8, &sd);
+            WriteDataFormat(&sd, it8);
+            WriteData(&sd, it8);
+    }
+    
+	sd.Used++;	// The \0 at the very end
+
+	if (sd.Base)
+		sd.Ptr = 0;
+
+	*BytesNeeded = sd.Used;
+
+    return TRUE;
+}
+
+
+// -------------------------------------------------------------- Higer level parsing
+
+static
+LCMSBOOL DataFormatSection(LPIT8 it8)
+{
+    int iField = 0;    
+    LPTABLE t = GetTable(it8);
+
+    InSymbol(it8);   // Eats "BEGIN_DATA_FORMAT"
+    CheckEOLN(it8);
+
+    while (it8->sy != SEND_DATA_FORMAT &&
+        it8->sy != SEOLN &&
+        it8->sy != SEOF &&
+        it8->sy != SSYNERROR)  {
+        
+            if (it8->sy != SIDENT) {
+            
+                return SynError(it8, "Sample type expected");                    
+            }
+        
+            if (!SetDataFormat(it8, iField, it8->id)) return FALSE;
+            iField++;
+                
+            InSymbol(it8);
+            SkipEOLN(it8);
+       }
+
+       SkipEOLN(it8);
+       Skip(it8, SEND_DATA_FORMAT);
+       SkipEOLN(it8);
+
+       if (iField != t ->nSamples) {
+           SynError(it8, "Count mismatch. NUMBER_OF_FIELDS was %d, found %d\n", t ->nSamples, iField);
+
+           
+       }
+
+       return TRUE;
+}
+
+
+
+static
+LCMSBOOL DataSection (LPIT8 it8)
+{
+    int  iField = 0;
+    int  iSet   = 0;
+    char Buffer[256];
+    LPTABLE t = GetTable(it8);
+
+    InSymbol(it8);   // Eats "BEGIN_DATA"
+    CheckEOLN(it8);
+
+    if (!t->Data)
+        AllocateDataSet(it8);
+
+    while (it8->sy != SEND_DATA && it8->sy != SEOF)
+    {
+        if (iField >= t -> nSamples) {
+            iField = 0;
+            iSet++;
+          
+        }
+
+        if (it8->sy != SEND_DATA && it8->sy != SEOF) {
+
+            if (!GetVal(it8, Buffer, 255, "Sample data expected"))
+                return FALSE;
+
+            if (!SetData(it8, iSet, iField, Buffer))
+                return FALSE;
+
+            iField++;
+            
+            InSymbol(it8);
+            SkipEOLN(it8);           
+        }
+    }
+
+    SkipEOLN(it8);
+    Skip(it8, SEND_DATA);
+    SkipEOLN(it8);
+ 
+    // Check for data completion.
+
+    if ((iSet+1) != t -> nPatches)
+        return SynError(it8, "Count mismatch. NUMBER_OF_SETS was %d, found %d\n", t ->nPatches, iSet+1);
+
+    return TRUE;
+}
+
+
+
+
+static
+LCMSBOOL HeaderSection(LPIT8 it8)
+{
+    char VarName[MAXID];
+    char Buffer[MAXSTR];
+
+        while (it8->sy != SEOF &&
+               it8->sy != SSYNERROR &&
+               it8->sy != SBEGIN_DATA_FORMAT &&
+               it8->sy != SBEGIN_DATA) {
+
+
+        switch (it8 -> sy) {
+
+        case SKEYWORD:
+                InSymbol(it8);
+                if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;                
+                if (!AddAvailableProperty(it8, Buffer)) return FALSE;
+                InSymbol(it8);
+                break;
+
+
+        case SIDENT:
+                strncpy(VarName, it8->id, MAXID-1);
+                
+                if (!IsAvailableOnList(it8-> ValidKeywords, VarName, NULL)) {
+
+#ifdef STRICT_CGATS               
+                 return SynError(it8, "Undefined keyword '%s'", VarName);
+#else
+                if (!AddAvailableProperty(it8, VarName)) return FALSE;
+#endif
+                }
+
+                InSymbol(it8);
+                if (!GetVal(it8, Buffer, MAXSTR-1, "Property data expected")) return FALSE;
+
+				
+                AddToList(it8, &GetTable(it8)->HeaderList, VarName, Buffer, 
+								(it8->sy == SSTRING) ? WRITE_STRINGIFY : WRITE_UNCOOKED);
+				
+                InSymbol(it8);
+                break;
+
+        
+        case SEOLN: break;
+
+        default:
+                return SynError(it8, "expected keyword or identifier");
+        }
+
+    SkipEOLN(it8);
+    }
+
+    return TRUE;
+
+}
+
+
+static
+LCMSBOOL ParseIT8(LPIT8 it8)
+{
+    char* SheetTypePtr;
+
+    // First line is a very special case.
+
+    while (isseparator(it8->ch))
+            NextCh(it8);
+    
+    SheetTypePtr = it8 ->SheetType;
+
+    while (it8->ch != '\r' && it8 ->ch != '\n' && it8->ch != '\t' && it8 -> ch != -1) {
+
+        *SheetTypePtr++= (char) it8 ->ch;
+        NextCh(it8);
+    }
+
+    *SheetTypePtr = 0;
+    InSymbol(it8);
+   
+    SkipEOLN(it8);
+
+    while (it8-> sy != SEOF &&
+           it8-> sy != SSYNERROR) {
+
+            switch (it8 -> sy) {
+
+            case SBEGIN_DATA_FORMAT:
+                    if (!DataFormatSection(it8)) return FALSE;
+                    break;
+
+            case SBEGIN_DATA:
+
+                    if (!DataSection(it8)) return FALSE;
+                    
+                    if (it8 -> sy != SEOF) {
+
+                            AllocTable(it8);
+                            it8 ->nTable = it8 ->TablesCount - 1;
+                    }
+                    break;
+
+            case SEOLN:
+                    SkipEOLN(it8);
+                    break;
+
+            default:
+                    if (!HeaderSection(it8)) return FALSE;
+           }
+
+    }
+
+    return (it8 -> sy != SSYNERROR);
+}
+
+
+
+// Init usefull pointers
+
+static
+void CookPointers(LPIT8 it8)
+{
+    int idField, i;
+    char* Fld;
+    int j;
+    int nOldTable = it8 ->nTable;
+
+    for (j=0; j < it8 ->TablesCount; j++) {
+
+    LPTABLE 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;
+
+        }
+
+        Fld = t->DataFormat[idField];
+        if (!Fld) continue;
+
+
+        if (stricmp(Fld, "SAMPLE_ID") == 0) {
+
+                    t -> SampleID = idField;
+                
+        for (i=0; i < t -> nPatches; i++) {
+
+                char *Data = GetData(it8, i, idField);
+                if (Data) {
+                    char Buffer[256];
+                
+                    strncpy(Buffer, Data, 255);
+                                       
+                    if (strlen(Buffer) <= strlen(Data))
+                        strcpy(Data, Buffer);
+                    else
+                        SetData(it8, i, idField, Buffer);
+
+                }
+                }
+        
+        }
+
+        // "LABEL" is an extension. It keeps references to forward tables
+         
+        if ((stricmp(Fld, "LABEL") == 0) || Fld[0] == '$' ) {
+                                        
+                    // Search for table references...
+                    for (i=0; i < t -> nPatches; i++) {
+
+                            char *Label = GetData(it8, i, idField);
+                           
+                            if (Label) {                                
+                                
+                                int 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;
+
+                                    if (IsAvailableOnList(Table->HeaderList, Label, &p)) {
+
+                                        // Available, keep type and table
+                                        char Buffer[256];
+
+                                        char *Type  = p ->Value;
+                                        int  nTable = k;                                        
+
+                                        snprintf(Buffer, 255, "%s %d %s", Label, nTable, Type );
+                                                                                
+                                        SetData(it8, i, idField, Buffer);
+                                    }
+                                }
+
+
+                            }
+
+                    }
+
+
+        }
+
+    }
+    }
+
+    it8 ->nTable = nOldTable;
+}
+
+// Try to infere if the file is a CGATS/IT8 file at all. Read first line
+// that should be something like some printable characters plus a \n
+
+static
+LCMSBOOL IsMyBlock(LPBYTE Buffer, size_t n)
+{
+    size_t i;
+
+    if (n < 10) return FALSE;   // Too small
+
+    if (n > 132)
+        n = 132;
+
+    for (i = 1; i < n; i++) {
+
+        if (Buffer[i] == '\n' || Buffer[i] == '\r' || Buffer[i] == '\t') return TRUE;
+        if (Buffer[i] < 32) return FALSE;
+        if (Buffer[i] > 127) return FALSE;
+    }
+
+    return FALSE;
+
+}
+
+
+static
+LCMSBOOL IsMyFile(const char* FileName)
+{
+   FILE *fp;
+   size_t Size;
+   BYTE Ptr[133];
+
+   fp = fopen(FileName, "rt");
+   if (!fp) {
+       cmsSignalError(LCMS_ERRC_ABORTED, "File '%s' not found", FileName);
+       return FALSE;
+   }
+
+   Size = fread(Ptr, 1, 132, fp);
+   fclose(fp);
+
+   Ptr[Size] = '\0';
+
+   return IsMyBlock(Ptr, Size);
+}
+
+// ---------------------------------------------------------- Exported routines
+
+
+LCMSHANDLE LCMSEXPORT cmsIT8LoadFromMem(void *Ptr, size_t len)
+{
+    LCMSHANDLE hIT8; 
+    LPIT8  it8;
+
+    if (!IsMyBlock((LPBYTE) Ptr, len)) return NULL;
+    
+    hIT8 = cmsIT8Alloc();
+    if (!hIT8) return NULL;
+
+    it8 = (LPIT8) hIT8;
+    it8 ->MemoryBlock = (char*) _cmsMalloc(len + 1);
+
+    strncpy(it8 ->MemoryBlock, (const char*) Ptr, len);
+    it8 ->MemoryBlock[len] = 0;
+
+    strncpy(it8->FileStack[0]->FileName, "", MAX_PATH-1);
+    it8-> Source = it8 -> MemoryBlock;
+
+    if (!ParseIT8(it8)) { 
+       
+        cmsIT8Free(hIT8); 
+        return FALSE; 
+    }
+
+    CookPointers(it8);
+    it8 ->nTable = 0;
+
+     _cmsFree(it8->MemoryBlock);
+    it8 -> MemoryBlock = NULL;
+
+    return hIT8;
+
+
+}
+
+
+LCMSHANDLE LCMSEXPORT cmsIT8LoadFromFile(const char* cFileName)
+{
+
+     LCMSHANDLE hIT8; 
+     LPIT8  it8;
+
+     if (!IsMyFile(cFileName)) return NULL;
+
+     hIT8 = cmsIT8Alloc();
+     it8 = (LPIT8) hIT8;   
+     if (!hIT8) return NULL;
+
+
+     it8 ->FileStack[0]->Stream = fopen(cFileName, "rt");
+
+     if (!it8 ->FileStack[0]->Stream) {         
+         cmsIT8Free(hIT8);
+         return NULL;
+     }
+     
+
+    strncpy(it8->FileStack[0]->FileName, cFileName, MAX_PATH-1);    
+
+    if (!ParseIT8(it8)) { 
+    
+            fclose(it8 ->FileStack[0]->Stream);
+            cmsIT8Free(hIT8); 
+            return NULL; 
+    }
+
+    CookPointers(it8);
+    it8 ->nTable = 0;
+
+    fclose(it8 ->FileStack[0]->Stream);    
+    return hIT8;
+
+}
+
+int LCMSEXPORT cmsIT8EnumDataFormat(LCMSHANDLE hIT8, char ***SampleNames)
+{
+        LPIT8 it8 = (LPIT8) hIT8;
+        LPTABLE t = GetTable(it8);
+
+        *SampleNames = t -> DataFormat;
+        return t -> nSamples;
+}
+
+
+int LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE hIT8, char ***PropertyNames)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    LPKEYVALUE p;
+    int n;
+    char **Props;
+    LPTABLE t = GetTable(it8);
+
+    // Pass#1 - count properties
+
+    n = 0;
+    for (p = t -> HeaderList;  p != NULL; p = p->Next) {
+        n++;
+    }
+
+
+    Props = (char **) AllocChunk(it8, sizeof(char *) * n);
+
+    // Pass#2 - Fill pointers
+    n = 0;
+    for (p = t -> HeaderList;  p != NULL; p = p->Next) {
+        Props[n++] = p -> Keyword;
+    }
+
+    *PropertyNames = Props;
+    return n;
+}
+
+static
+int LocatePatch(LPIT8 it8, const char* cPatch)
+{
+    int i;
+    const char *data;
+    LPTABLE t = GetTable(it8);
+
+    for (i=0; i < t-> nPatches; i++) {
+
+        data = GetData(it8, i, t->SampleID);
+        
+        if (data != NULL) {
+
+                if (stricmp(data, cPatch) == 0)
+                        return i;
+                }
+        }
+
+        // SynError(it8, "Couldn't find patch '%s'\n", cPatch);                               
+        return -1;
+}
+
+
+static
+int LocateEmptyPatch(LPIT8 it8)
+{
+    int i;
+    const char *data;
+    LPTABLE t = GetTable(it8);
+
+    for (i=0; i < t-> nPatches; i++) {
+
+        data = GetData(it8, i, t->SampleID);
+        
+        if (data == NULL) 
+                    return i;
+                
+        }
+
+        return -1;
+}
+
+static
+int LocateSample(LPIT8 it8, const char* cSample)
+{
+    int i;
+    const char *fld;
+    LPTABLE t = GetTable(it8);
+
+    for (i=0; i < t->nSamples; i++) {
+
+        fld = GetDataFormat(it8, i);
+        if (stricmp(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)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    return LocateSample(it8, cSample);
+}
+
+
+
+const char* LCMSEXPORT cmsIT8GetDataRowCol(LCMSHANDLE hIT8, int row, int col)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+
+    return GetData(it8, row, col);
+}
+
+
+double LCMSEXPORT cmsIT8GetDataRowColDbl(LCMSHANDLE hIT8, int row, int col)
+{
+    const char* Buffer;
+
+    Buffer = cmsIT8GetDataRowCol(hIT8, row, col);
+    
+    if (Buffer) {
+
+        return atof(Buffer);
+        
+    } else
+        return 0;
+
+}
+
+
+LCMSBOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col, const char* Val)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    
+    return SetData(it8, row, col, Val);        
+}
+
+
+LCMSBOOL LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col, double Val)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    char Buff[256];
+
+    sprintf(Buff, it8->DoubleFormatter, Val);
+    
+    return SetData(it8, row, col, Buff);        
+}
+
+
+
+const char* LCMSEXPORT cmsIT8GetData(LCMSHANDLE hIT8, const char* cPatch, const char* cSample)                        
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    int iField, iSet;
+
+
+    iField = LocateSample(it8, cSample);
+    if (iField < 0) {       
+        return NULL;
+    }
+
+
+    iSet = LocatePatch(it8, cPatch);
+    if (iSet < 0) {          
+            return NULL;
+    }
+
+    return GetData(it8, iSet, iField);
+}
+
+
+double LCMSEXPORT cmsIT8GetDataDbl(LCMSHANDLE it8, const char* cPatch, const char* cSample)
+{
+    const char* Buffer;
+
+    Buffer = cmsIT8GetData(it8, cPatch, cSample);
+    
+    if (Buffer) {
+
+        return atof(Buffer);
+        
+    } else {
+        
+        return 0;
+    }
+}
+
+
+
+LCMSBOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE hIT8, const char* cPatch,
+                        const char* cSample,
+                        const char *Val)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    int iField, iSet;
+    LPTABLE 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;
+        }
+        else {
+                iSet = LocatePatch(it8, cPatch);
+                if (iSet < 0) {
+                    return FALSE;
+            }
+        }
+
+        return SetData(it8, iSet, iField, Val);
+}
+
+
+LCMSBOOL LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
+                        const char* cSample,
+                        double Val)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    char Buff[256];
+
+        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)
+{
+        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);        
+        return buffer;
+}
+
+int LCMSEXPORT cmsIT8TableCount(LCMSHANDLE hIT8)
+{
+        LPIT8 it8 = (LPIT8) hIT8;
+
+        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)
+{
+    const char* cLabelFld;
+    char Type[256], Label[256];
+    int nTable;
+   
+    if (cField != NULL && *cField == 0)
+            cField = "LABEL";
+
+    if (cField == NULL) 
+            cField = "LABEL";
+
+    cLabelFld = cmsIT8GetData(hIT8, cSet, cField); 
+    if (!cLabelFld) return -1;
+    
+    if (sscanf(cLabelFld, "%255s %d %255s", Label, &nTable, Type) != 3)
+            return -1;
+    
+    if (ExpectedType != NULL && *ExpectedType == 0)
+        ExpectedType = NULL;
+
+    if (ExpectedType) {
+
+        if (stricmp(Type, ExpectedType) != 0) return -1;
+    }
+
+    return cmsIT8SetTable(hIT8, nTable);    
+}
+
+
+void LCMSEXPORT cmsIT8DefineDblFormat(LCMSHANDLE hIT8, const char* Formatter)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+
+    if (Formatter == NULL)
+        strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
+    else
+        strcpy(it8->DoubleFormatter, Formatter);
+}
+
new file mode 100644
--- /dev/null
+++ b/modules/lcms/src/cmscnvrt.c
@@ -0,0 +1,637 @@
+//
+//  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"
+
+
+
+
+/*
+       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 --------------------------
+
+
+// Calculate m, offset Relativ -> Absolute undoing any chromatic 
+// adaptation done by the profile. 
+
+#ifdef _MSC_VER
+#pragma warning(disable : 4100 4505)
+#endif
+
+
+
+// join scalings to obtain:
+//     relative input to absolute and then to relative output
+
+static
+void Rel2RelStepAbsCoefs(double AdaptationState,
+
+                         LPcmsCIEXYZ BlackPointIn,
+                         LPcmsCIEXYZ WhitePointIn,
+                         LPcmsCIEXYZ IlluminantIn,
+                         LPMAT3 ChromaticAdaptationMatrixIn,
+
+                         LPcmsCIEXYZ BlackPointOut,
+                         LPcmsCIEXYZ WhitePointOut,
+                         LPcmsCIEXYZ IlluminantOut,
+                         LPMAT3 ChromaticAdaptationMatrixOut,
+
+                         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);
+                  
+       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));
+
+       }
+       else {
+
+            // Observer is not adapted, undo the chromatic adaptation
+            m1 = *ChromaticAdaptationMatrixIn;
+            MAT3inverse(&m1, &m2);
+       
+            MAT3per(&m3, &m2, &Scale);
+            MAT3per(m, &m3, ChromaticAdaptationMatrixOut);
+       }
+
+            
+       VEC3init(of, 0.0, 0.0, 0.0);
+                    
+}
+
+
+// The (in)famous black point compensation. Right now implemented as
+// a linear scaling in XYZ
+
+static
+void ComputeBlackPointCompensationFactors(LPcmsCIEXYZ BlackPointIn,
+                      LPcmsCIEXYZ WhitePointIn,
+                      LPcmsCIEXYZ IlluminantIn,
+                      LPcmsCIEXYZ BlackPointOut,
+                      LPcmsCIEXYZ WhitePointOut,
+                      LPcmsCIEXYZ IlluminantOut,
+                      LPMAT3 m, LPVEC3 of)
+{
+    
+
+   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);
+   
+   // Now we need to compute a matrix plus an offset m and of such of
+   // [m]*bpin + off = bpout
+   // [m]*D50  + off = D50
+   //
+   // This is a linear scaling in the form ax+b, where
+   // a = (bpout - D50) / (bpin - D50)
+   // b = - D50* (bpout - bpin) / (bpin - D50)
+
+
+   tx = RelativeBlackPointIn.X - IlluminantIn ->X;
+   ty = RelativeBlackPointIn.Y - IlluminantIn ->Y;
+   tz = RelativeBlackPointIn.Z - IlluminantIn ->Z;
+
+   ax = (RelativeBlackPointOut.X - IlluminantOut ->X) / tx;
+   ay = (RelativeBlackPointOut.Y - IlluminantOut ->Y) / ty;
+   az = (RelativeBlackPointOut.Z - IlluminantOut ->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;
+
+
+   MAT3identity(m);
+
+   m->v[VX].n[0] = ax;
+   m->v[VY].n[1] = ay;
+   m->v[VZ].n[2] = az;
+
+   VEC3init(of, bx, by, bz);
+
+}
+
+// Return TRUE if both m and of are empy -- "m" being identity and "of" being 0
+
+static
+LCMSBOOL IdentityParameters(LPWMAT3 m, LPWVEC3 of)
+{   
+    WVEC3 wv0;
+
+    VEC3initF(&wv0, 0, 0, 0);
+
+    if (!MAT3isIdentity(m, 0.00001)) return FALSE;
+    if (!VEC3equal(of, &wv0, 0.00001)) return FALSE;
+
+    return TRUE;
+}
+
+
+
+
+// ----------------------------------------- Inter PCS conversions
+
+// XYZ to XYZ linear scaling. Aso used on Black point compensation
+
+static
+void XYZ2XYZ(WORD In[], WORD Out[], LPWMAT3 m, LPWVEC3 of)
+{
+
+    WVEC3 a, r;
+
+    a.n[0] = In[0] << 1;
+    a.n[1] = In[1] << 1;
+    a.n[2] = In[2] << 1;
+
+    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);
+}
+
+
+// XYZ to Lab, scaling first
+
+static
+void XYZ2Lab(WORD In[], WORD Out[], LPWMAT3 m, LPWVEC3 of)
+{
+  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);
+}
+
+// Lab to XYZ, scalling and then, back to Lab
+
+static
+void Lab2XYZ2Lab(WORD In[], WORD Out[], LPWMAT3 m, LPWVEC3 of)
+{
+       WORD XYZ[3], XYZ2[3];
+
+       cmsLab2XYZEncoded(In, XYZ);
+       XYZ2XYZ(XYZ, XYZ2, m, of);
+       cmsXYZ2LabEncoded(XYZ2, Out);
+}
+
+// ------------------------------------------------------------------
+
+// Dispatcher for XYZ Relative LUT
+
+static
+int FromXYZRelLUT(int Absolute,
+                             LPcmsCIEXYZ BlackPointIn,
+                             LPcmsCIEXYZ WhitePointIn,
+                             LPcmsCIEXYZ IlluminantIn,
+                             LPMAT3 ChromaticAdaptationMatrixIn,
+
+                 int Phase2, LPcmsCIEXYZ BlackPointOut,
+                             LPcmsCIEXYZ WhitePointOut,
+                             LPcmsCIEXYZ IlluminantOut,
+                             LPMAT3 ChromaticAdaptationMatrixOut,
+
+                 int DoBlackPointCompensation,
+                 double AdaptationState,
+                 _cmsADJFN *fn1,
+                 LPMAT3 m, LPVEC3 of)
+
+{
+              switch (Phase2) {
+
+                     // From relative XYZ to Relative XYZ.
+
+                     case XYZRel:
+
+                            if (Absolute)
+                            {
+                                   // From input relative to absolute, and then
+                                   // back to output relative
+
+                                   Rel2RelStepAbsCoefs(AdaptationState,
+                                                       BlackPointIn,
+                                                       WhitePointIn,
+                                                       IlluminantIn,
+                                                       ChromaticAdaptationMatrixIn,
+                                                       BlackPointOut,
+                                                       WhitePointOut,
+                                                       IlluminantOut,
+                                                       ChromaticAdaptationMatrixOut,
+                                                       m, of);
+                                   *fn1 = XYZ2XYZ;
+
+                            }
+                            else
+                            {
+                                   // XYZ Relative to XYZ relative, no op required                                   
+                                   *fn1 = NULL;
+                                   if (DoBlackPointCompensation) {
+
+                                      *fn1 = XYZ2XYZ;
+                                      ComputeBlackPointCompensationFactors(BlackPointIn,
+                                                                      WhitePointIn,
+                                                                      IlluminantIn,
+                                                                      BlackPointOut,
+                                                                      WhitePointOut,
+                                                                      IlluminantOut,
+                                                                      m, of);
+
+                                   }
+                            }
+                            break;
+
+                    
+                     // 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)
+                            {   
+
+                                Rel2RelStepAbsCoefs(AdaptationState,
+                                                    BlackPointIn,
+                                                    WhitePointIn,
+                                                    IlluminantIn,
+                                                    ChromaticAdaptationMatrixIn,
+                                                    BlackPointOut,
+                                                    WhitePointOut,
+                                                    IlluminantOut,
+                                                    ChromaticAdaptationMatrixOut,
+                                                    m, of);
+                                
+                                *fn1 = XYZ2Lab;
+
+                            }
+                            else
+                            {
+                                   // Just Convert to Lab
+
+                                   MAT3identity(m);
+                                   VEC3init(of, 0, 0, 0);
+                                   *fn1 = XYZ2Lab;
+
+                                   if (DoBlackPointCompensation) {
+
+                                    ComputeBlackPointCompensationFactors(BlackPointIn,
+                                                                          WhitePointIn,
+                                                                          IlluminantIn,
+                                                                          BlackPointOut,
+                                                                          WhitePointOut,
+                                                                          IlluminantOut,
+                                                                          m, of);
+                                   }
+                            }
+                            break;
+
+                    
+                     default: return FALSE;
+                     }
+
+              return TRUE;
+}
+
+
+
+
+// From Lab Relative type LUT
+
+static
+int FromLabRelLUT(int Absolute,
+                             LPcmsCIEXYZ BlackPointIn,
+                             LPcmsCIEXYZ WhitePointIn,
+                             LPcmsCIEXYZ IlluminantIn,
+                             LPMAT3 ChromaticAdaptationMatrixIn,
+
+                 int Phase2, LPcmsCIEXYZ BlackPointOut,
+                             LPcmsCIEXYZ WhitePointOut,
+                             LPcmsCIEXYZ IlluminantOut,
+                             LPMAT3 ChromaticAdaptationMatrixOut,
+
+                int DoBlackPointCompensation,
+                double AdaptationState,
+
+                 _cmsADJFN *fn1,
+                 LPMAT3 m, LPVEC3 of)
+{
+
+          switch (Phase2) {
+
+              // From Lab Relative to XYZ Relative, very usual case
+
+              case XYZRel:
+
+                  if (Absolute) {  // Absolute intent
+
+                            // From lab relative, to XYZ absolute, and then,
+                            // back to XYZ relative
+
+                            Rel2RelStepAbsCoefs(AdaptationState,
+                                                BlackPointIn,
+                                                WhitePointIn,
+                                                cmsD50_XYZ(),
+                                                ChromaticAdaptationMatrixIn,
+                                                BlackPointOut,
+                                                WhitePointOut,
+                                                IlluminantOut,
+                                                ChromaticAdaptationMatrixOut,
+                                                m, of);
+
+                            *fn1 = Lab2XYZ;
+
+                     }
+                     else
+                     {
+                            // From Lab relative, to XYZ relative.
+                            
+                            *fn1 = Lab2XYZ;
+                            if (DoBlackPointCompensation) {
+
+                                 ComputeBlackPointCompensationFactors(BlackPointIn,
+                                                                      WhitePointIn,
+                                                                      IlluminantIn,
+                                                                      BlackPointOut,
+                                                                      WhitePointOut,
+                                                                      IlluminantOut,
+                                                                      m, of);
+
+                            }
+                     }
+                     break;
+
+
+
+              case LabRel:
+
+                     if (Absolute) {
+
+                             // First pass to XYZ using the input illuminant
+                             // * InIlluminant / D50, then to absolute. Then
+                             // to relative, but for input
+
+                             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
+
+                            *fn1 = NULL;
+                             if (DoBlackPointCompensation) {
+
+                                 *fn1 = Lab2XYZ2Lab;
+                                 ComputeBlackPointCompensationFactors(BlackPointIn,
+                                                                      WhitePointIn,
+                                                                      IlluminantIn,
+                                                                      BlackPointOut,
+                                                                      WhitePointOut,
+                                                                      IlluminantOut,
+                                                                      m, of);
+
+                                
+                            }
+                     }
+                     break;
+
+
+              default: return FALSE;
+              }
+
+   return TRUE;
+}
+
+
+// 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
+
+
+
+// Main dispatcher
+
+int 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)
+{
+
+       int rc;
+       MAT3 m;
+       VEC3 of;
+
+
+       MAT3identity(&m);
+       VEC3init(&of, 0, 0, 0);
+
+       switch (Phase1) {
+
+       // Input LUT is giving XYZ relative values.
+
+       case XYZRel:  rc = FromXYZRelLUT(Absolute,
+                                          BlackPointIn,
+                                          WhitePointIn,
+                                          IlluminantIn,
+                                          ChromaticAdaptationMatrixIn,
+                                          Phase2,
+                                          BlackPointOut,
+                                          WhitePointOut,
+                                          IlluminantOut,
+                                          ChromaticAdaptationMatrixOut,
+                                          DoBlackPointCompensation,
+                                          AdaptationState,
+                                          fn1, &m, &of);
+                     break;
+
+       
+
+       // Input LUT is giving Lab relative values
+
+       case LabRel:  rc =  FromLabRelLUT(Absolute,
+                                          BlackPointIn,
+                                          WhitePointIn,
+                                          IlluminantIn,
+                                          ChromaticAdaptationMatrixIn,
+                                          Phase2,
+                                          BlackPointOut,
+                                          WhitePointOut,
+                                          IlluminantOut,
+                                          ChromaticAdaptationMatrixOut,
+                                          DoBlackPointCompensation,
+                                          AdaptationState,
+                                          fn1, &m, &of);
+                     break;
+
+
+       
+
+       // Unrecognized combination
+
+       default:    cmsSignalError(LCMS_ERRC_ABORTED, "(internal) Phase error");
+                   return FALSE;
+
+       }
+
+       MAT3toFix(wm, &m);
+       VEC3toFix(wof, &of);
+
+       // Do some optimization -- discard conversion if identity parameters.
+
+       if (*fn1 == XYZ2XYZ || *fn1 == Lab2XYZ2Lab) {
+
+           if (IdentityParameters(wm, wof))
+               *fn1 = NULL;
+       }
+
+       
+       return rc;
+}
+
+
+      
new file mode 100644
--- /dev/null
+++ b/modules/lcms/src/cmserr.c
@@ -0,0 +1,110 @@
+//
+//  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"
+
+
+// As a rule, only the functions visible from API can signal
+// errors.
+
+void cdecl cmsSignalError(int ErrorCode, const char *ErrorText, ...);
+
+int  LCMSEXPORT cmsErrorAction(int lAbort);
+void LCMSEXPORT cmsSetErrorHandler(cmsErrorHandlerFunction Fn);
+
+
+// ******************************************************************
+
+static int nDoAbort = LCMS_ERROR_ABORT;
+static cmsErrorHandlerFunction UserErrorHandler = (cmsErrorHandlerFunction) NULL;
+
+
+int LCMSEXPORT cmsErrorAction(int nAction)
+{
+       int nOld = nDoAbort;    
+       nDoAbort = nAction;
+
+       return nOld;
+}
+
+void LCMSEXPORT cmsSetErrorHandler(cmsErrorHandlerFunction Fn)
+{
+       UserErrorHandler = Fn;
+}
+
+
+// Default error handler
+
+
+void cmsSignalError(int ErrorCode, const char *ErrorText, ...)
+{
+       va_list args;
+       
+       if (nDoAbort == LCMS_ERROR_IGNORE) return;
+
+        va_start(args, ErrorText);
+
+        if (UserErrorHandler != NULL) {
+
+            char Buffer[1024];
+
+            vsnprintf(Buffer, 1023, ErrorText, args);
+            va_end(args);   
+
+            if (UserErrorHandler(ErrorCode, Buffer)) {     
+
+                return;
+                }
+         }
+
+#if defined( __CONSOLE__ ) || defined( NON_WINDOWS )
+
+              fprintf(stderr, "lcms: Error #%d; ", ErrorCode);
+              vfprintf(stderr, ErrorText, args);
+              fprintf(stderr, "\n");
+              va_end(args);
+
+              if (nDoAbort == LCMS_ERROR_ABORT) exit(1);
+#else
+              {
+              char Buffer1[1024];
+              char Buffer2[256];
+
+              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);
+
+              if (nDoAbort == LCMS_ERROR_ABORT) {
+
+#ifdef __BORLANDC__
+                    _cexit();
+#endif
+
+                  FatalAppExit(0, "lcms is terminating application");
+              }
+              }
+#endif
+}
new file mode 100644
--- /dev/null
+++ b/modules/lcms/src/cmsgamma.c
@@ -0,0 +1,954 @@
+//
+//  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"
+
+// Gamma handling. 
+
+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);
+
+LCMSBOOL         cdecl _cmsSmoothEndpoints(LPWORD Table, int nPoints);
+
+
+// Sampled curves
+
+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);
+
+LPSAMPLEDCURVE cdecl cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints);
+
+double LCMSEXPORT cmsEstimateGamma(LPGAMMATABLE t);
+double LCMSEXPORT cmsEstimateGammaEx(LPWORD GammaTable, int nEntries, double Thereshold);
+
+// ----------------------------------------------------------------------------------------
+
+
+#define MAX_KNOTS   4096
+typedef float vec[MAX_KNOTS+1];
+
+
+// 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
+    
+static
+unsigned int Crc32(unsigned int result, LPVOID ptr, int len)
+{    
+    int          i,j;
+    BYTE         octet; 
+    LPBYTE       data = (LPBYTE) ptr;
+        
+    for (i=0; i < len; i++) {
+
+        octet = *data++;
+
+        for (j=0; j < 8; j++) {
+
+            if (result & 0x80000000) {
+
+                result = (result << 1) ^ QUOTIENT ^ (octet >> 7);
+            }
+            else
+            {
+                result = (result << 1) ^ (octet >> 7);
+            }
+            octet <<= 1;
+        }
+    }
+    
+    return result;
+}
+
+// Get CRC of gamma table 
+
+unsigned int _cmsCrc32OfGammaTable(LPGAMMATABLE Table)
+{
+    unsigned int crc = ~0U;
+
+    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);
+
+    return ~crc;
+
+}
+
+
+LPGAMMATABLE LCMSEXPORT cmsAllocGamma(int nEntries)
+{
+       LPGAMMATABLE p;
+       size_t size;
+
+       if (nEntries > 65530 || nEntries < 0) {
+                cmsSignalError(LCMS_ERRC_ABORTED, "Couldn't create gammatable of more than 65530 entries");
+                return NULL;
+       }
+
+       size = sizeof(GAMMATABLE) + (sizeof(WORD) * (nEntries-1));
+
+       p = (LPGAMMATABLE) _cmsMalloc(size);
+       if (!p) return NULL;
+
+       ZeroMemory(p, size);
+
+       p -> Seed.Type     = 0;
+       p -> nEntries = nEntries;
+       
+       return p;
+}
+
+void LCMSEXPORT cmsFreeGamma(LPGAMMATABLE Gamma)
+{
+       if (Gamma)  _cmsFree(Gamma);
+}
+
+
+
+void LCMSEXPORT cmsFreeGammaTriple(LPGAMMATABLE Gamma[3])
+{
+    cmsFreeGamma(Gamma[0]);
+    cmsFreeGamma(Gamma[1]);
+    cmsFreeGamma(Gamma[2]);
+    Gamma[0] = Gamma[1] = Gamma[2] = NULL;
+}
+
+
+
+// Duplicate a gamma table
+
+LPGAMMATABLE  LCMSEXPORT cmsDupGamma(LPGAMMATABLE In)
+{
+       LPGAMMATABLE Ptr;
+       size_t size;
+
+       Ptr = cmsAllocGamma(In -> nEntries);
+       if (Ptr == NULL) return NULL;
+
+       size = sizeof(GAMMATABLE) + (sizeof(WORD) * (In -> nEntries-1));
+
+       CopyMemory(Ptr, In, size);                  
+       return Ptr;
+}
+
+
+// Handle gamma using interpolation tables. The resulting curves can become
+// very stange, but are pleasent to eye.
+
+LPGAMMATABLE LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma,
+                          LPGAMMATABLE OutGamma)
+{
+       register int i;
+       L16PARAMS L16In, L16Out;
+       LPWORD InPtr, OutPtr;
+       LPGAMMATABLE p;
+
+       p = cmsAllocGamma(256);
+       if (!p) return NULL;
+
+       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;
+}
+
+
+
+// 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)
+
+
+LPGAMMATABLE LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma,
+                                       LPGAMMATABLE OutGamma, int nPoints)
+{
+
+    LPSAMPLEDCURVE x, y, r;
+    LPGAMMATABLE res;
+    
+    x = cmsConvertGammaToSampledCurve(InGamma,  nPoints);
+    y = cmsConvertGammaToSampledCurve(OutGamma, nPoints);
+    r = cmsJoinSampledCurves(y, x, nPoints);
+
+    // Does clean "hair"
+    cmsSmoothSampledCurve(r, 0.001);
+
+    cmsClampSampledCurve(r, 0.0, 65535.0); 
+    
+    cmsFreeSampledCurve(x);
+    cmsFreeSampledCurve(y);
+
+    res = cmsConvertSampledCurveToGamma(r, 65535.0);
+    cmsFreeSampledCurve(r);
+
+    return res;
+}
+
+
+
+// Reverse a gamma table
+
+LPGAMMATABLE LCMSEXPORT cmsReverseGamma(int nResultSamples, LPGAMMATABLE InGamma)
+{
+       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);
+       }
+
+
+       // Nope, reverse the table 
+       p = cmsAllocGamma(nResultSamples);
+       if (!p) return NULL;
+
+       cmsCalcL16Params(InGamma -> nEntries, &L16In);
+       InPtr  = InGamma -> GammaTable;
+
+       for (i=0; i < nResultSamples; i++)
+       {
+              WORD wValIn, wValOut;
+
+              wValIn = _cmsQuantizeVal(i, nResultSamples);           
+              wValOut = cmsReverseLinearInterpLUT16(wValIn, InPtr, &L16In);
+              p -> GammaTable[i] = wValOut;
+       }
+
+           
+       return p;
+}
+
+
+
+// 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[])
+{
+        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;       
+
+        CopyMemory(Table ->Seed.Params, Params, ParamsByType[abs(Type)] * sizeof(double));
+
+
+        for (i=0; i < nEntries; i++) {
+
+                R   = (double) i / (nEntries-1);
+
+                switch (Type) {
+
+                // X = Y ^ Gamma
+                case 1:
+                      Val = pow(R, Params[0]);
+                      break;
+
+                // Type 1 Reversed: X = Y ^1/gamma
+                case -1:
+                      Val = pow(R, 1/Params[0]);
+                      break;
+
+                // 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: 
+                    
+                    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]) {
+                            
+                      e = Params[1]*R + Params[2];                    
+                      Val = pow(e, Params[0]) + Params[3];
+                    }
+                    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];
+                        Val = (pow(e, 1/Params[0]) - Params[2]) / Params[1];
+                        if (Val < 0) 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:
+                    if (R >= pow(Params[1] * Params[4] + Params[2], Params[0])) {
+
+                        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             | else
+                case 5:
+                    if (R >= Params[4]) {
+                             
+                        e = Params[1]*R + Params[2];
+                        Val = pow(e, Params[0]) + Params[5];
+                    }        
+                    else
+                        Val = R*Params[3] + Params[6];
+                    break;
+
+
+                // 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]) {
+
+                    Val = pow(R - Params[5], 1/Params[0]) - Params[2] / Params[1];
+                }
+                else {
+                    Val = (R - Params[6]) / Params[3];
+                }
+                break;
+
+                default:
+                        cmsSignalError(LCMS_ERRC_ABORTED, "Unsupported parametric curve type=%d", abs(Type)-1);
+                        cmsFreeGamma(Table);
+                        return NULL;
+                }
+
+
+        // Saturate
+
+        dval = Val * 65535.0 + .5;
+        if (dval > 65535.) dval = 65535.0;
+        if (dval < 0) dval = 0;
+
+        Table->GammaTable[i] = (WORD) floor(dval);
+        }
+
+        Table -> Seed.Crc32 = _cmsCrc32OfGammaTable(Table);
+
+        return Table;
+}
+
+// Build a gamma table based on gamma constant
+
+LPGAMMATABLE LCMSEXPORT cmsBuildGamma(int nEntries, double Gamma)
+{
+    return cmsBuildParametricGamma(nEntries, 1, &Gamma);
+}
+
+
+
+// From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite
+// differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.
+//
+// Smoothing and interpolation with second differences.
+//
+//   Input:  weights (w), data (y): vector from 1 to m.
+//   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)
+{
+  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];
+}
+
+
+
+// Smooths a curve sampled at regular intervals
+
+LCMSBOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda)
+
+{
+    vec w, y, z;
+    int i, nItems, Zeros, Poles;
+
+
+    if (cmsIsLinear(Tab->GammaTable, Tab->nEntries)) return FALSE; // Nothing to do
+
+    nItems = Tab -> nEntries;
+
+    if (nItems > MAX_KNOTS) {
+                cmsSignalError(LCMS_ERRC_ABORTED, "cmsSmoothGamma: 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++)
+    {
+        y[i+1] = (float) Tab -> GammaTable[i];
+        w[i+1] = 1.0;
+    }
+
+    smooth2(w, y, z, (float) lambda, nItems);
+
+    // 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 (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
+
+        float v = z[i+1];
+
+        if (v < 0) v = 0;
+        if (v > 65535.) v = 65535.;
+
+        Tab -> GammaTable[i] = (WORD) floor(v + .5);
+        }
+
+    return TRUE;
+}
+
+
+// Check if curve is exponential, return gamma if so.
+
+double LCMSEXPORT cmsEstimateGammaEx(LPWORD GammaTable, int nEntries, double Thereshold)
+{
+    double gamma, sum, sum2;
+    double n, x, y, Std;
+    int i;
+
+    sum = sum2 = n = 0;
+    
+    // Does exclude endpoints   
+    for (i=1; i < nEntries - 1; i++) {
+
+            x = (double) i / (nEntries - 1);
+            y = (double) GammaTable[i] / 65535.;
+            
+            // Avoid 7% on lower part to prevent 
+            // artifacts due to linear ramps
+
+            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)
+        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;
+}
new file mode 100644
--- /dev/null
+++ b/modules/lcms/src/cmsgmt.c
@@ -0,0 +1,1243 @@
+//
+//  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"
+
+/*
+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);
+
+}
+
+
+// Square
+static
+double Sqr(double v)
+{
+    return v *  v; 
+}
+
+// Return the CIE94 Delta E 
+double LCMSEXPORT cmsCIE94DeltaE(LPcmsCIELab Lab1, LPcmsCIELab Lab2)
+{
+    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
+
+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;
+    
+    
+    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;
+    
+    
+    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(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;
+
+  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;
+}
+
+
+
+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);
+    
+    while (h > 360.)         
+        h -= 360.;
+    
+    while ( h < 0)
+        h += 360.;
+    
+    return h;
+
+}
+
+
+static
+double RADIANES(double deg)
+{
+    return (deg * M_PI) / 180.;
+}
+
+
+// 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)
+{
+    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) );
+
+    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;
+
+    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;
+
+    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));
+
+    double Sl = 1 + (0.015 * Sqr((Ls + L1) /2- 50) )/ sqrt(20 + Sqr( (Ls+L1)/2 - 50) );
+
+    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)));
+
+    double Rt = -sin(2 * RADIANES(delta_ro)) * Rc;
+
+    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)));
+
+    return deltaE00;
+}
+
+   
+
+// Carefully,  clamp on CIELab space.
+
+void LCMSEXPORT cmsClampLab(LPcmsCIELab Lab, double amax, double amin,
+                                   double bmax, double bmin)
+{
+
+            // Whole Luma surface to zero
+
+        if (Lab -> L < 0) {
+
+                Lab-> L = Lab->a = Lab-> b = 0.0;
+                return;
+            }
+
+            // 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
+
+
+                 if (Lab -> a == 0.0) { // Is hue exactly 90?
+
+                        // atan will not work, so clamp here
+                        Lab -> b = Lab->b < 0 ? bmin : bmax;
+                        return;
+                 }
+
+                 cmsLab2LCh(&LCh, Lab);
+
+                 slope = Lab -> b / Lab -> a;
+                 h = LCh.h;
+
+                 // There are 4 zones
+
+                 if ((h >= 0. && h < 45.) ||
+                     (h >= 315 && h <= 360.)) {
+
+                     // 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;
+
+                 }
+                 else
+                 if (h >= 225 && h < 315) {
+                        // clip by bmin
+                        Lab -> b = bmin;
+                        Lab -> a = bmin / slope;
+                 }
+                 else
+                        cmsSignalError(LCMS_ERRC_ABORTED, "Invalid angle");
+
+        }
+}
+
+// Several utilities -------------------------------------------------------
+
+// Translate from our colorspace to ICC representation
+
+icColorSpaceSignature LCMSEXPORT _cmsICCcolorSpace(int OurNotation)
+{
+       switch (OurNotation) {
+
+       case 1:
+       case PT_GRAY: return  icSigGrayData;
+
+       case 2:
+       case PT_RGB:  return  icSigRgbData;
+
+       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;
+
+       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;
+       }
+}
+
+
+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;        
+}
+
+
+// Used by gamut & softproofing
+
+typedef struct {
+
+    cmsHTRANSFORM hInput;               // From whatever input color space. NULL for Lab
+    cmsHTRANSFORM hForward, hReverse;   // Transforms going from Lab to colorant and back
+    double Thereshold;                  // The thereshold after which is considered out of gamut
+    
+    } GAMUTCHAIN,FAR* LPGAMUTCHAIN;
+
+// 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)
+{
+    LPGAMUTCHAIN t = (LPGAMUTCHAIN) Cargo;
+    WORD Proof[MAXCHANNELS], Check[MAXCHANNELS];
+    WORD Proof2[MAXCHANNELS], Check2[MAXCHANNELS];
+    cmsCIELab LabIn1, LabOut1;  
+    cmsCIELab LabIn2, LabOut2;  
+    double 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);
+
+    // converts from PCS to colorant. This always
+    // does return in-gamut values, 
+    cmsDoTransform(t -> hForward, In, Proof, 1);
+    
+    // Now, do the inverse, from colorant to PCS.
+    cmsDoTransform(t -> hReverse, Proof, Check, 1);
+    
+    
+    // Try again, but this time taking Check as input
+    cmsDoTransform(t -> hForward, Check, Proof2,  1);
+    cmsDoTransform(t -> hReverse, Proof2, Check2, 1);
+    
+    
+    
+    // Does the transform returns out-of-gamut?
+    if (Check[0] == 0xFFFF && 
+        Check[1] == 0xFFFF && 
+        Check[2] == 0xFFFF) 
+        
+        Out[0] = 0xFF00;            // Out of gamut!
+    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) 
+            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 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;
+                }
+            
+    }    
+    
+    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.
+//
+// **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)
+{
+    cmsHPROFILE hLab;
+    LPLUT Gamut;
+    DWORD dwFormat;
+    GAMUTCHAIN Chain;
+    int nErrState, nChannels, nGridpoints;
+    LPGAMMATABLE Trans[3];
+    icColorSpaceSignature ColorSpace;
+            
+    
+    ZeroMemory(&Chain, sizeof(GAMUTCHAIN)); 
+       
+    hLab = cmsCreateLabProfile(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))
+
+        Chain.Thereshold = 1.0;
+    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);
+
+    // 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);
+
+   
+    // 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. 
+
+    Gamut = cmsAllocLUT();
+    Gamut = cmsAlloc3DGrid(Gamut, nGridpoints, nChannels, 1);
+     
+    // If no input, then this is a gamut tag operated by Lab,
+    // so include pertinent prelinearization
+    if (hInput == NULL) {
+       
+        CreateLabPrelinearization(Trans);               
+        cmsAllocLinearTable(Gamut, Trans, 1);              
+        cmsFreeGammaTriple(Trans);
+    }
+
+   
+    cmsSample3DGrid(Gamut, GamutSampler, (LPVOID) &Chain, Gamut ->wFlags);          
+    }
+    else 
+        Gamut = NULL;   // Didn't work...
+
+    // Free all needed stuff.
+    if (Chain.hInput)   cmsDeleteTransform(Chain.hInput);
+    if (Chain.hForward) cmsDeleteTransform(Chain.hForward);
+    if (Chain.hReverse) cmsDeleteTransform(Chain.hReverse);
+
+    cmsCloseProfile(hLab);
+    
+    // And return computed hull
+    return Gamut;
+}
+
+
+// Wrapper
+
+LPLUT _cmsComputeGamutLUT(cmsHPROFILE hProfile, int Intent)
+{    
+    return ComputeGamutWithInput(NULL, hProfile, Intent);
+}
+
+
+// This routine does compute the gamut check CLUT. This CLUT goes from whatever 
+// input space to the 0 or != 0 gamut check.
+
+LPLUT _cmsPrecalculateGamutCheck(cmsHTRANSFORM h)
+{
+       _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) h;
+       
+       return ComputeGamutWithInput(p->InputProfile, p ->PreviewProfile, p->Intent);
+}
+
+
+// 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)
+{
+        LPGAMUTCHAIN t = (LPGAMUTCHAIN) Cargo;
+        WORD Colorant[MAXCHANNELS];
+                
+        // From pcs to colorant
+        cmsDoTransform(t -> hForward, In, Colorant, 1);
+
+        // Now, do the inverse, from colorant to pcs.
+        cmsDoTransform(t -> hReverse, Colorant, Out, 1);
+                
+        return TRUE;
+}
+
+// Does return Softproofing LUT on desired intent
+
+LPLUT _cmsComputeSoftProofLUT(cmsHPROFILE hProfile, int nIntent)
+{
+    cmsHPROFILE hLab;
+    LPLUT SoftProof;
+    DWORD dwFormat;
+    GAMUTCHAIN Chain;
+    int nErrState;
+    LPGAMMATABLE Trans[3];
+        
+
+    // 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);
+
+    // 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);
+
+    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;
+}
+
+
+static
+int MostlyLinear(WORD Table[], int nEntries)
+{
+       register int i;
+       int diff;
+
+       for (i=5; i < nEntries; i++) {
+
+           diff = abs((int) Table[i] - (int) _cmsQuantizeVal(i, nEntries));              
+           if (diff > 0x0300)
+                     return 0;
+       }
+
+       return 1;
+}
+
+
+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;
+
+    Val   = Table[At];
+    Slope = Val / At;
+
+    for (i=0; i < At; i++)
+        Table[i] = (WORD) floor(i * Slope + 0.5);
+
+}
+
+
+// Check for monotonicity.
+
+static
+LCMSBOOL IsMonotonic(LPGAMMATABLE t)
+{
+    int n = t -> nEntries;
+    int i, last;
+
+    last = t ->GammaTable[n-1];
+
+    for (i = n-2; i >= 0; --i) {
+        
+        if (t ->GammaTable[i] > last)
+
+               return FALSE;
+        else
+                last = t ->GammaTable[i];
+
+    }
+
+    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)) || 
</