Update library based on the chromium version; add BUILD.gn and
README.fuchsia.

Change-Id: I9f750555f78a4a11e41dd2e29e88cb97e690e5c9
diff --git a/AUTHORS b/AUTHORS
new file mode 100644
index 0000000..2fd0a12
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1,8 @@
+# This is the list of Fuchsia Authors.
+# Names should be added to this file as one of
+#     Organization's name
+#     Individual's name <submission email address>
+#     Individual's name <submission email address> <email2> <emailN>
+
+Google Inc.
+The Chromium Authors
diff --git a/BUILD.gn b/BUILD.gn
new file mode 100644
index 0000000..fdcad17
--- /dev/null
+++ b/BUILD.gn
@@ -0,0 +1,31 @@
+# Copyright 2016 The Fuchsia Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+config("qcms_config") {
+  include_dirs = [ "." ]
+}
+
+source_set("qcms") {
+  public_configs = [ ":qcms_config" ]
+
+  sources = [
+    "chain.c",
+    "chain.h",
+    "iccread.c",
+    "matrix.c",
+    "matrix.h",
+    "qcms.h",
+    "qcms_util.c",
+    "qcmsint.h",
+    "qcmstypes.h",
+    "transform.c",
+    "transform_util.c",
+    "transform_util.h",
+  ]
+
+  if (current_cpu == "x86" || current_cpu == "x64") {
+    defines = [ "SSE2_ENABLE" ]
+    sources += [ "transform-sse2.c" ]
+  }
+}
diff --git a/Makefile b/Makefile
deleted file mode 100644
index 32e6991..0000000
--- a/Makefile
+++ /dev/null
@@ -1,32 +0,0 @@
-
-COVERAGE_FLAGS=-fprofile-arcs -ftest-coverage
-#COVERAGE_FLAGS=
-OPT_FLAGS=-O0
-OPT_FLAGS=
-CFLAGS=`pkg-config --cflags lcms` -Wall $(OPT_FLAGS) $(COVERAGE_FLAGS) -Wdeclaration-after-statement -ggdb
-LDFLAGS=-ldl
-
-QCMS_SRC=iccread.c transform.c matrix.c chain.c transform_util.c transform-sse2.c transform-sse1.c
-QCMS_OBJS=iccread.o transform.o matrix.o chain.o transform_util.o transform-sse2.o transform-sse1.o
-
-PROGRAMS=profile-gen test test-invalid test-transform dump-profile div-test coverage malloc-fail invalid-coverage
-
-# I don't know a good way to get the exit code of pkg-config into a make variable
-HAS_LCMS:=$(shell pkg-config --exists lcms; echo $$?)
-ifeq ($(HAS_LCMS),0)
-PROGRAMS+=lcms-compare
-CFLAGS+=`pkg-config --cflags lcms`
-LDFLAGS+=`pkg-config --libs lcms`
-endif
-
-all: $(PROGRAMS)
-
-$(PROGRAMS): $(QCMS_OBJS)
-
-gen-coverage:
-	mkdir -p lcov
-	lcov -d . -c --output-file lcov/lcov.info
-	genhtml -o lcov/ lcov/lcov.info
-
-clean:
-	rm -f $(PROGRAMS) $(QCMS_OBJS)
diff --git a/README.fuchsia b/README.fuchsia
new file mode 100644
index 0000000..bf93f45
--- /dev/null
+++ b/README.fuchsia
@@ -0,0 +1,106 @@
+Name: Quick Color Management System
+Short Name: qcms
+URL: https://github.com/jrmuizel/qcms/tree/v4
+Version: v4
+Date: 2012-03-13
+License: MIT
+License File: COPYING
+Security Critical: yes
+
+Description:
+Contains support for applying an ICC color profile to an image.  The code is
+originally based on tinycms, re-written by Mozilla for better security and
+performance.  This copy is a source-drop from Mozilla on March 13, 2012.
+
+Local Modifications:
+Some files only have license headers in the master branch.
+ - Added the same license headers to the versions brought down from the 'v4'
+   branch src URL qcms/tree/v4
+The following changes have been made since qcms was imported:
+ - Add bgra output support.
+ - Use HAVE_POSIX_MEMALIGN instead of HAS_POSIX_MEMALIG
+   (https://bugzilla.mozilla.org/show_bug.cgi?id=692922)
+ - Applied upstream patch:
+   - https://bug752254.bugzilla.mozilla.org/attachment.cgi?id=626102
+ - Applied upstream patch for sanitizing gamma table:
+   - Expanded gamma clamp range to allow 1.0.
+ - Do not short-circuit bogus profile check for A2B0 or B2A0 unless v4 enabled.
+ - Only reference code from transform-sse1.c and transform-sse2.c when SSE is
+   enabled.
+ - Limit the use an x86-only attribute to 32-bit x86 builds.
+ - Fix integer truncation warning/errors on Win64 build.
+ - Apply upstream thread safety (fix) patch from
+   - https://bugzilla.mozilla.org/show_bug.cgi?id=853169
+ - Apply upstream fix for qcms_profile_from_memory from
+   - https://bugzilla.mozilla.org/show_bug.cgi?id=969226
+ - Apply upstream simplification of qcmstypes.h
+   - https://hg.mozilla.org/mozilla-central/rev/b5be94737a83
+ - Check for unused tag_len in read_nested_curveType()
+ - Apply qcms_transform_precacheLUT_float does not properly free dest buffer
+   - https://bugzilla.mozilla.org/show_bug.cgi?id=701348
+ - Add qcms_profile_match api
+ - Add qcms_profile_get_description api71
+ - Convert MLUC profile description embedded nulls to '.'
+ - [APPLE port] Use en-localized profile description names
+ - [APPLE port] Use mmod data for profile descriptions
+ - Minor variable name change: description -> description_offset
+ - Avoid divisions creating sample points in the float cube LUT builder
+ - Add bgra (z,y,x) sampled transform lookup table api
+ - Apply upstream fix reject invalid sizes from
+ - lut_inverse_interp16: remove odd whitespace formatting
+ - lut_inverse_interp16: better handle degenerate TRC curves
+ - Add vcgt tag reader and API to read its RGB gamma data
+ - Consolidate loop over channels and elements in VCGT parser
+ - Limit vcgt table to a maximum of 1024 entries
+ - Add float to half float conversion routine
+ - Use half float conversion tables (not functions)
+ - Add matrix transform flag and matrix extraction api
+ - Add tone reproduction curve (TRC) extraction api
+ - lut_inverse_interp16: interpolate degenerate zeros in TRC curves
+ - Make half float code self-contained: add halffloat.h
+ - lut_inverse_interp16: fix black level inversion error
+ - Apply upstream fix of uninitialized value
+   - https://github.com/jrmuizel/qcms/commit/0edb697
+ - Apply Keep the output of the TRC between 0 and 1
+   - https://bugzilla.mozilla.org/show_bug.cgi?id=764181
+ - Drop SSE1 code as Chromium mandates SSE2 as a minimum requirement
+ - Apply Fix potential leaks in qcms_transform_create
+   - https://bugzilla.mozilla.org/show_bug.cgi?id=1168480
+ - Apply fix for crash in qcms_transform_data_rgb_out_lut_sse1
+   - https://bugzilla.mozilla.org/show_bug.cgi?id=1163740
+ - Add SSE2 code for qcms_transform_data_rgba_out_lut_sse2
+ - Turbo charge SSE2 qcms_transform_data_rgba_out_lut_sse2
+ - Check matrix transforms have the same PCS
+ - Apply Don't reject valid profiles with no CLUT offset
+   - https://bugzilla.mozilla.org/show_bug.cgi?id=1176551
+ - Runtime detect qcms_transform_data_tetra_clut_rgba_sse2 use
+ - LUT8/16 profiles with an empty CLUT are invalid
+ - Caching transform prelude to save computation in V4 profiles
+ - Use the caching transform prelude for non-SSE code in transform.c
+ - Expand QCMS tests. Add Munsell test for transform accuracy
+ - Compute RMS error from color error dE in the Munsell test
+ - Store color profile version and add a version read API
+ - Add support for VCGT tag formula gamma
+ - Minimize transform RMS in qcms_transform_data_rgb(a)_out_lut
+ - Allow negative XYZ for display profiles on the APPLE port
+ - Add a color profile white point transform api
+ - Compute the pole and zero values needed by lut_inverse_interp16 once
+ - Store the profile media white point during iccread.c
+ - Add an API to check for profile media white point
+ - Add a qcms_profile_get_white_point() api
+ - Set the media white point of the sRGB profile
+ - Don't build QCMS on Android and iOS
+ - Fix para curve tag interval paramater use
+ - Verify internal sRGB profile tristimulus match the standard sRGB profile
+ - Expose unsigned short version of TRC curve
+ - Add qcms_profile_ntsc_relative_gamut_size api
+ - Fix build issue of qcms_tests for MIPS Linux
+ - Update primaries used to build internal sRGB profile
+ - Update internal sRGB profile test report output
+ - Add more internal sRGB profile tests
+ - Fix build_output_lut to return correct data for parametric curves
+ - Make build_output_lut output 4096 points for parametric curves
+ - Use a static table in build_output_lut to invert para curves
+ - Make qcms_test_output_trc handle normal gamma curves
+ - Add API to output parametric gamma curve data
+ - Fix an unitialized read in gamma curve data.
diff --git a/chain.c b/chain.c
index a259499..5255070 100644
--- a/chain.c
+++ b/chain.c
@@ -133,6 +133,8 @@
 	float* g_table = transform->g_clut;
 	float* b_table = transform->b_clut;
 
+	assert(transform->grid_size >= 1);
+
 	for (i = 0; i < length; i++) {
 		float linear_r = *src++;
 		float linear_g = *src++;
@@ -187,6 +189,9 @@
 	float* r_table = transform->r_clut;
 	float* g_table = transform->g_clut;
 	float* b_table = transform->b_clut;
+
+	assert(transform->grid_size >= 1);
+
 	for (i = 0; i < length; i++) {
 		float device_r = *src++;
 		float device_g = *src++;
@@ -892,6 +897,7 @@
 {
 	struct qcms_modular_transform *first_transform = NULL;
 	struct qcms_modular_transform **next_transform = &first_transform;
+	qcms_bool transform_to_pcs_xyz_only = (out == NULL);
 
 	if (in->color_space == RGB_SIGNATURE) {
 		struct qcms_modular_transform* rgb_to_pcs;
@@ -904,7 +910,7 @@
 		goto fail;
 	}
 
-	if (in->pcs == LAB_SIGNATURE && out->pcs == XYZ_SIGNATURE) {
+	if (in->pcs == LAB_SIGNATURE && (transform_to_pcs_xyz_only || out->pcs == XYZ_SIGNATURE)) {
 		struct qcms_modular_transform* lab_to_pcs;
 		lab_to_pcs = qcms_modular_transform_alloc();
 		if (!lab_to_pcs) 
@@ -913,6 +919,9 @@
 		lab_to_pcs->transform_module_fn = qcms_transform_module_LAB_to_XYZ;
 	}
 
+	if (transform_to_pcs_xyz_only)
+		return first_transform;
+
 	// This does not improve accuracy in practice, something is wrong here.
 	//if (in->chromaticAdaption.invalid == false) {
 	//	struct qcms_modular_transform* chromaticAdaption;
@@ -987,3 +996,31 @@
 	}
 	return NULL;
 }
+
+qcms_bool qcms_profile_white_transform(qcms_profile *profile, float XYZ[3])
+{
+	const float inverse_internal_scale = 1.999969482421875f;
+
+	// Set the output profile to NULL to request a color transform to PCS XYZ only.
+	struct qcms_modular_transform *transform_list = qcms_modular_transform_create(profile, NULL);
+
+	// Now calculate how the profile transforms white input color to PCS XYZ space.
+	if (transform_list != NULL) {
+		XYZ[0] = XYZ[1] = XYZ[2] = 1.0f; // white input
+		qcms_modular_transform_data(transform_list, XYZ, XYZ, 1);
+		// qcms_modular_transform_create internally scales input by 1/1.999969482421875f
+		// but no qcms changelog describes why / how that number was choosen. junov@ "it
+		// might be related to the epsilon of the fixed-point type 2*(1-1/(2^16)), but
+		// there is no explanation, which is disconcerting." Meanwhile, undo the internal
+		// scaling so we return a normalized CIEXYZ value viz., where Y is scaled to 1.0.
+		// A properly created color profile should produce Y=~1.0 in PCS XYZ with white
+		// input (the D50 test). If it does not, then the profile is likely bogus.
+		XYZ[0] *= inverse_internal_scale;
+		XYZ[1] *= inverse_internal_scale;
+		XYZ[2] *= inverse_internal_scale;
+		qcms_modular_transform_release(transform_list);
+		return true;
+	}
+
+	return false;
+}
diff --git a/coverage.c b/coverage.c
deleted file mode 100644
index 09e0f7f..0000000
--- a/coverage.c
+++ /dev/null
@@ -1,122 +0,0 @@
-#include <stdlib.h>
-#include <assert.h>
-#include "qcms.h"
-const unsigned char gray_icc[] =
-{0x00, 0x00, 0x01, 0x70, 0x4E, 0x4B, 0x4F, 0x4E, 0x02, 0x20, 0x00, 0x00,
-0x6D, 0x6E, 0x74, 0x72, 0x47, 0x52, 0x41, 0x59, 0x58, 0x59, 0x5A, 0x20,
-0x07, 0xCE, 0x00, 0x0B, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x61, 0x63, 0x73, 0x70, 0x41, 0x50, 0x50, 0x4C, 0x00, 0x00, 0x00, 0x00,
-0x6E, 0x6F, 0x6E, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6, 0xD6,
-0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xD3, 0x2D, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
-0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x4B,
-0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x01, 0x0C, 0x00, 0x00, 0x00, 0x14,
-0x6B, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x20, 0x00, 0x00, 0x00, 0x0E,
-0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0x30, 0x00, 0x00, 0x00, 0x2C,
-0x62, 0x6B, 0x70, 0x74, 0x00, 0x00, 0x01, 0x5C, 0x00, 0x00, 0x00, 0x14,
-0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1A,
-0x4E, 0x69, 0x6B, 0x6F, 0x6E, 0x47, 0x72, 0x61, 0x79, 0x47, 0x31, 0x2E,
-0x38, 0x20, 0x76, 0x34, 0x2E, 0x30, 0x2E, 0x30, 0x2E, 0x33, 0x30, 0x30,
-0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x1A, 0x4E, 0x69, 0x6B, 0x6F, 0x6E, 0x47, 0x72, 0x61, 0x79, 0x47, 0x31,
-0x2E, 0x38, 0x20, 0x76, 0x34, 0x2E, 0x30, 0x2E, 0x30, 0x2E, 0x33, 0x30,
-0x30, 0x30, 0x00, 0x00, 0x58, 0x59, 0x5A, 0x20, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0xF3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xCC,
-0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
-0x01, 0xCD, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00,
-0x4E, 0x69, 0x6B, 0x6F, 0x6E, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x20, 0x26,
-0x20, 0x4E, 0x69, 0x6B, 0x6F, 0x6E, 0x20, 0x43, 0x6F, 0x72, 0x70, 0x6F,
-0x72, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x32, 0x30, 0x30, 0x31, 0x00,
-0x58, 0x59, 0x5A, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
-void test_gray(qcms_profile *output_profile)
-{
-	unsigned char srct[3] = { 221, 79, 129};
-	unsigned char outt[3];
-	qcms_transform *transform;
-	qcms_profile *gray_profile = qcms_profile_from_memory(gray_icc, sizeof(gray_icc));
-	assert(gray_profile);
-	transform = qcms_transform_create(gray_profile, QCMS_DATA_GRAY_8, output_profile, QCMS_DATA_RGB_8, QCMS_INTENT_PERCEPTUAL);
-	qcms_transform_data(transform, srct, outt, 1);
-	assert(
-			outt[0] == 0xe4 &&
-			outt[1] == 0xe4 &&
-			outt[2] == 0xe4);
-	qcms_transform_release(transform);
-
-	transform = qcms_transform_create(gray_profile, QCMS_DATA_GRAYA_8, output_profile, QCMS_DATA_RGBA_8, QCMS_INTENT_PERCEPTUAL);
-	qcms_transform_data(transform, srct, outt, 1);
-	assert(
-			outt[0] == 0xe4 &&
-			outt[1] == 0xe4 &&
-			outt[2] == 0xe4 &&
-			outt[3] == 79);
-	qcms_transform_release(transform);
-	qcms_profile_release(gray_profile);
-}
-
-const extern unsigned char gray_icc[];
-int main()
-{
-	unsigned char srct[4] = { 221, 79, 129, 92};
-	unsigned char outt[4];
-	qcms_transform *transform;
-	qcms_profile *input_profile, *output_profile, *rgb;
-	qcms_CIE_xyY white_point = { 0, 0.1, 1.};
-	qcms_CIE_xyYTRIPLE primaries = { {1, 0.01, 0}, {0, 0, 0.01}, {20, .4, 1.}};
-
-	input_profile = qcms_profile_sRGB();
-	output_profile = qcms_profile_sRGB();
-
-	test_gray(output_profile);
-
-	rgb = qcms_profile_create_rgb_with_gamma(white_point, primaries, 1.8);
-	// it is not clear how to create a bogus profile with the above interface
-	//assert(qcms_profile_is_bogus(rgb));
-
-	assert(!qcms_profile_is_bogus(input_profile));
-	assert(!qcms_profile_is_bogus(output_profile));
-
-	transform = qcms_transform_create(input_profile, QCMS_DATA_RGBA_8, output_profile, QCMS_DATA_RGBA_8, QCMS_INTENT_PERCEPTUAL);
-
-	qcms_transform_data(transform, srct, outt, 1);
-	assert(outt[0] == 0xdd && outt[1] == 0x4f && outt[2] == 0x81 && outt[3] == 92);
-
-	qcms_transform_release(transform);
-
-	transform = qcms_transform_create(input_profile, QCMS_DATA_RGB_8, output_profile, QCMS_DATA_RGB_8, QCMS_INTENT_PERCEPTUAL);
-
-	qcms_transform_data(transform, srct, outt, 1);
-	assert(outt[0] == 0xdd && outt[1] == 0x4f && outt[2] == 0x81);
-
-	qcms_transform_release(transform);
-
-	qcms_profile_precache_output_transform(output_profile);
-
-	transform = qcms_transform_create(input_profile, QCMS_DATA_RGBA_8, output_profile, QCMS_DATA_RGBA_8, QCMS_INTENT_PERCEPTUAL);
-
-	qcms_transform_data(transform, srct, outt, 1);
-	assert(outt[0] == 0xdd && outt[1] == 0x4f && outt[2] == 0x81 && outt[3] == 92);
-
-	qcms_transform_release(transform);
-
-	transform = qcms_transform_create(input_profile, QCMS_DATA_RGB_8, output_profile, QCMS_DATA_RGB_8, QCMS_INTENT_PERCEPTUAL);
-
-	qcms_transform_data(transform, srct, outt, 1);
-	assert(outt[0] == 0xdd && outt[1] == 0x4f && outt[2] == 0x81);
-
-	qcms_transform_release(transform);
-
-	test_gray(output_profile);
-
-	qcms_profile_release(input_profile);
-	qcms_profile_release(output_profile);
-
-	return 0;
-}
-
diff --git a/div-test.c b/div-test.c
deleted file mode 100644
index 4e4a009..0000000
--- a/div-test.c
+++ /dev/null
@@ -1,33 +0,0 @@
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-uint32_t ref(uint32_t a)
-{
-	return (a + 128)/ 255;
-	return (a + (65535/2))/ 65535;
-}
-
-uint32_t try1(a)
-{
-	return (((uint64_t)a + 128)*257) / 65535LL;
-	return (((uint64_t)a + 32767)*65538) / 4294967296LL;
-}
-
-
-
-int main()
-{
-	uint32_t x = 0;
-	do {
-		uint32_t r1 = ref(x);
-		uint32_t r2 = try1(x);
-		if (r1 != r2) {
-			printf("FAIL: %x -> %x %x\n", x, r1, r2);
-			exit(1);
-		}
-		if (x == 0xffffffff)
-			break;
-		x++;
-	} while (1);
-	return 0;
-}
diff --git a/dump-profile.c b/dump-profile.c
deleted file mode 100644
index 4427f0c..0000000
--- a/dump-profile.c
+++ /dev/null
@@ -1,32 +0,0 @@
-#include <stdlib.h>
-#include "qcms.h"
-
-void dump_profile(qcms_profile *profile)
-{
-	if (profile) {
-		printf(" rendering intent: %d\n", qcms_profile_get_rendering_intent(profile));
-		if (qcms_profile_is_bogus(profile)) {
-			printf(" bogus\n");
-		}
-		qcms_profile_release(profile);
-	} else {
-		printf("bad profile\n");
-	}
-}
-
-int main(int argc, char **argv)
-{
-	if (argc > 1) {
-		int i;
-		for (i=1; i<argc; i++) {
-			char *input_path = argv[i];
-			printf("%s\n", input_path);
-			dump_profile(qcms_profile_from_path(input_path));
-		}
-	} else {
-		dump_profile(qcms_profile_sRGB());
-	}
-
-
-	return 0;
-}
diff --git a/halffloat.h b/halffloat.h
new file mode 100644
index 0000000..35c7250
--- /dev/null
+++ b/halffloat.h
@@ -0,0 +1,106 @@
+/* vim: set ts=8 sw=8 noexpandtab: */
+//  qcms
+//  Copyright (C) 2009 Mozilla Foundation
+//  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.
+
+#ifndef _QCMS_HALFFLOAT_H
+#define _QCMS_HALFFLOAT_H
+
+const unsigned short qcms_half_float_base_table[512] = {
+        0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,
+        0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,
+        0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,
+        0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,
+        0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,
+        0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,      0,
+        0,      0,      0,      0,      0,      0,      0,      1,      2,      4,      8,      16,     32,     64,     128,    256,
+        512,    1024,   2048,   3072,   4096,   5120,   6144,   7168,   8192,   9216,   10240,  11264,  12288,  13312,  14336,  15360,
+        16384,  17408,  18432,  19456,  20480,  21504,  22528,  23552,  24576,  25600,  26624,  27648,  28672,  29696,  30720,  31744,
+        31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,
+        31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,
+        31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,
+        31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,
+        31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,
+        31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,
+        31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,  31744,
+        32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,
+        32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,
+        32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,
+        32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,
+        32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,
+        32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,  32768,
+        32768,  32768,  32768,  32768,  32768,  32768,  32768,  32769,  32770,  32772,  32776,  32784,  32800,  32832,  32896,  33024,
+        33280,  33792,  34816,  35840,  36864,  37888,  38912,  39936,  40960,  41984,  43008,  44032,  45056,  46080,  47104,  48128,
+        49152,  50176,  51200,  52224,  53248,  54272,  55296,  56320,  57344,  58368,  59392,  60416,  61440,  62464,  63488,  64512,
+        64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,
+        64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,
+        64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,
+        64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,
+        64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,
+        64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,
+        64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512,  64512
+};
+
+const unsigned char qcms_half_float_shift_table[512] = {
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     23,     22,     21,     20,     19,     18,     17,     16,     15,
+        14,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,
+        13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     13,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     23,     22,     21,     20,     19,     18,     17,     16,     15,
+        14,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,
+        13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     13,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,
+        24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     24,     13
+};
+
+static inline unsigned short float_to_half_float(float f)
+{
+	// See Blink::Source/platform/graphics/gpu/WebGLImageConversion.cpp::convertFloatToHalfFloat() and http://crbug.com/491784
+
+	unsigned temp = *((unsigned *)(&f));
+	unsigned signexp = (temp >> 23) & 0x1ff;
+	return qcms_half_float_base_table[signexp] + ((temp & 0x007fffff) >> qcms_half_float_shift_table[signexp]);
+}
+
+#endif
diff --git a/iccread.c b/iccread.c
index 5bd12a2..0bdba02 100644
--- a/iccread.c
+++ b/iccread.c
@@ -3,22 +3,22 @@
 //  Copyright (C) 2009 Mozilla Foundation
 //  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 
+// 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 
+// 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 
+// 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 <math.h>
@@ -146,29 +146,31 @@
 static void check_CMM_type_signature(struct mem_source *src)
 {
 	//uint32_t CMM_type_signature = read_u32(src, 4);
-	//TODO: do the check?
-
 }
 
-static void check_profile_version(struct mem_source *src)
+static void read_profile_version(qcms_profile *profile, struct mem_source *src)
 {
-
-	/*
 	uint8_t major_revision = read_u8(src, 8 + 0);
 	uint8_t minor_revision = read_u8(src, 8 + 1);
-	*/
-	uint8_t reserved1      = read_u8(src, 8 + 2);
-	uint8_t reserved2      = read_u8(src, 8 + 3);
-	/* Checking the version doesn't buy us anything
-	if (major_revision != 0x4) {
-		if (major_revision > 0x2)
-			invalid_source(src, "Unsupported major revision");
-		if (minor_revision > 0x40)
-			invalid_source(src, "Unsupported minor revision");
-	}
-	*/
-	if (reserved1 != 0 || reserved2 != 0)
+	uint8_t reserved_byte1 = read_u8(src, 8 + 2);
+	uint8_t reserved_byte2 = read_u8(src, 8 + 3);
+
+	profile->icc_version = major_revision << 8 | minor_revision;
+
+	if (reserved_byte1 || reserved_byte2) {
 		invalid_source(src, "Invalid reserved bytes");
+		return;
+	}
+
+	if (major_revision == 2)
+		return; // ICC V2.X color profile
+	if (major_revision == 4 && qcms_supports_iccv4)
+		return; // ICC V4.X color profile
+
+	/* Checking the version doesn't buy us anything: permit any
+	   version without failure for now */
+	// invalid_source(src, "Unsupported ICC revision");
+	return;
 }
 
 #define INPUT_DEVICE_PROFILE   0x73636e72 // 'scnr'
@@ -217,8 +219,7 @@
 	}
 }
 
-struct tag
-{
+struct tag {
 	uint32_t signature;
 	uint32_t offset;
 	uint32_t size;
@@ -252,73 +253,112 @@
 	return index;
 }
 
-// Checks a profile for obvious inconsistencies and returns
-// true if the profile looks bogus and should probably be
-// ignored.
+/* Checks a profile for obvious inconsistencies and return true if the
+ * profile looks bogus and should probably be ignored.
+ */
 qcms_bool qcms_profile_is_bogus(qcms_profile *profile)
 {
-       float sum[3], target[3], tolerance[3];
-       float rX, rY, rZ, gX, gY, gZ, bX, bY, bZ;
-       bool negative;
-       unsigned i;
+    float rX, rY, rZ, gX, gY, gZ, bX, bY, bZ;
+    float target[3], tolerance[3], sum[3];
+    unsigned i;
 
-       // We currently only check the bogosity of RGB profiles
-       if (profile->color_space != RGB_SIGNATURE)
-	       return false;
+    // We currently only check the bogosity of RGB profiles.
+    if (profile->color_space != RGB_SIGNATURE)
+        return false;
 
-       if (profile->A2B0 || profile->B2A0)
-               return false;
+    if (qcms_supports_iccv4 && (profile->A2B0 || profile->B2A0))
+        return false;
 
-       rX = s15Fixed16Number_to_float(profile->redColorant.X);
-       rY = s15Fixed16Number_to_float(profile->redColorant.Y);
-       rZ = s15Fixed16Number_to_float(profile->redColorant.Z);
+    rX = s15Fixed16Number_to_float(profile->redColorant.X);
+    rY = s15Fixed16Number_to_float(profile->redColorant.Y);
+    rZ = s15Fixed16Number_to_float(profile->redColorant.Z);
 
-       gX = s15Fixed16Number_to_float(profile->greenColorant.X);
-       gY = s15Fixed16Number_to_float(profile->greenColorant.Y);
-       gZ = s15Fixed16Number_to_float(profile->greenColorant.Z);
+    gX = s15Fixed16Number_to_float(profile->greenColorant.X);
+    gY = s15Fixed16Number_to_float(profile->greenColorant.Y);
+    gZ = s15Fixed16Number_to_float(profile->greenColorant.Z);
 
-       bX = s15Fixed16Number_to_float(profile->blueColorant.X);
-       bY = s15Fixed16Number_to_float(profile->blueColorant.Y);
-       bZ = s15Fixed16Number_to_float(profile->blueColorant.Z);
+    bX = s15Fixed16Number_to_float(profile->blueColorant.X);
+    bY = s15Fixed16Number_to_float(profile->blueColorant.Y);
+    bZ = s15Fixed16Number_to_float(profile->blueColorant.Z);
 
-       // Check if any of the XYZ values are negative (see mozilla bug 498245)
-       // CIEXYZ tristimulus values cannot be negative according to the spec.
-       negative =
-	       (rX < 0) || (rY < 0) || (rZ < 0) ||
-	       (gX < 0) || (gY < 0) || (gZ < 0) ||
-	       (bX < 0) || (bY < 0) || (bZ < 0);
+    // Build our target vector: CIE D50 white. See also mozilla bug 460629,
+    // and http://www.color.org/whyd50.xalter "Why is the media white point
+    // of a display profile always D50?"
 
-       if (negative)
-	       return true;
+    target[0] = (float) 0.96420;
+    target[1] = (float) 1.00000;
+    target[2] = (float) 0.82491;
 
+    // Our tolerance vector - Recommended by Chris Murphy [1] based on
+    // conversion from the L*a*b space criterion of no more than 3 in any
+    // one channel. This is similar to, but slightly more tolerant than
+    // Adobe's criterion. [1] https://bugzil.la/460629#c10
 
-       // Sum the values; they should add up to something close to white
-       sum[0] = rX + gX + bX;
-       sum[1] = rY + gY + bY;
-       sum[2] = rZ + gZ + bZ;
+    tolerance[0] = (float) 0.02;
+    tolerance[1] = (float) 0.02;
+    tolerance[2] = (float) 0.04;
 
-       // Build our target vector (see mozilla bug 460629)
-       target[0] = 0.96420;
-       target[1] = 1.00000;
-       target[2] = 0.82491;
+    // Sum the XYZ values: they should add to D50 white, within tolerance.
 
-       // Our tolerance vector - Recommended by Chris Murphy based on
-       // conversion from the LAB space criterion of no more than 3 in any one
-       // channel. This is similar to, but slightly more tolerant than Adobe's
-       // criterion.
-       tolerance[0] = 0.02;
-       tolerance[1] = 0.02;
-       tolerance[2] = 0.04;
+    // FIXME: this test assumes the TRC RGB curves equal 1.0 for the white
+    // input (255,255,255) RGB test color. For user display profiles, that
+    // is the normal case. Profiles with abnormal TRC exist. A better test
+    // would transform 255,255,255 white through the profile to either XYZ
+    // or L*a*b color and compare the result to D50 in XYZ or L*a*b color.
 
-       // Compare with our tolerance
-       for (i = 0; i < 3; ++i) {
-           if (!(((sum[i] - tolerance[i]) <= target[i]) &&
-                 ((sum[i] + tolerance[i]) >= target[i])))
-               return true;
-       }
+    sum[0] = rX + gX + bX;
+    sum[1] = rY + gY + bY;
+    sum[2] = rZ + gZ + bZ;
 
-       // All Good
-       return false;
+    for (i = 0; i < 3; ++i) {
+        if (!(((sum[i] - tolerance[i]) <= target[i]) &&
+              ((sum[i] + tolerance[i]) >= target[i]))) {
+            return true; // out of tolerance: bogus
+        }
+    }
+
+#ifndef __APPLE__
+    // Check if any of the XYZ values are negative (see mozilla bug 498245)
+    // CIEXYZ tristimulus values cannot be negative according to the spec.
+
+    bool negative =
+        (rX < 0) || (rY < 0) || (rZ < 0) ||
+        (gX < 0) || (gY < 0) || (gZ < 0) ||
+        (bX < 0) || (bY < 0) || (bZ < 0);
+
+    if (negative)
+        return true; // bogus
+#else
+    // Chromatic adaption to D50 can result in negative XYZ, but the white
+    // point D50 tolerance test has passed. Accept negative values herein.
+    // See https://bugzilla.mozilla.org/show_bug.cgi?id=498245#c18 onwards
+    // for discussion about whether profile XYZ can or cannot be negative,
+    // per the spec. Also the https://bugzil.la/450923 user report.
+
+    // FIXME: allow this relaxation on all ports?
+#endif
+    // All good.
+    return false;
+}
+
+qcms_bool qcms_profile_has_white_point(qcms_profile *profile)
+{
+    struct XYZNumber wp = profile->mediaWhitePoint;
+
+    return (wp.X != 0) && (wp.Y != 0) && (wp.Z != 0);
+}
+
+qcms_xyz_float qcms_profile_get_white_point(qcms_profile *profile)
+{
+    qcms_xyz_float wp = { 0.0f, 0.0f, 0.0f };
+
+    if (qcms_profile_has_white_point(profile)) {
+        wp.X = s15Fixed16Number_to_float(profile->mediaWhitePoint.X);
+        wp.Y = s15Fixed16Number_to_float(profile->mediaWhitePoint.Y);
+        wp.Z = s15Fixed16Number_to_float(profile->mediaWhitePoint.Z);
+    }
+
+    return wp;
 }
 
 #define TAG_bXYZ 0x6258595a
@@ -331,19 +371,272 @@
 #define TAG_A2B0 0x41324230
 #define TAG_B2A0 0x42324130
 #define TAG_CHAD 0x63686164
+#define TAG_desc 0x64657363
+#define TAG_vcgt 0x76636774
+#define TAG_wtpt 0x77747074
 
 static struct tag *find_tag(struct tag_index index, uint32_t tag_id)
 {
 	unsigned int i;
-	struct tag *tag = NULL;
+
 	for (i = 0; i < index.count; i++) {
-		if (index.tags[i].signature == tag_id) {
+		if (index.tags[i].signature == tag_id)
 			return &index.tags[i];
+	}
+
+	return NULL;
+}
+
+#define DESC_TYPE 0x64657363 // 'desc'
+#define MLUC_TYPE 0x6d6c7563 // 'mluc'
+#define MMOD_TYPE 0x6D6D6F64 // 'mmod'
+#define VCGT_TYPE 0x76636774 // 'vcgt'
+
+enum {
+	VCGT_TYPE_TABLE,
+	VCGT_TYPE_FORMULA,
+	VCGT_TYPE_LAST = VCGT_TYPE_FORMULA
+};
+
+static qcms_bool read_tag_vcgtType(qcms_profile *profile, struct mem_source *src, struct tag_index index)
+{
+	size_t tag_offset = find_tag(index, TAG_vcgt)->offset;
+	uint32_t tag_type = read_u32(src, tag_offset);
+	uint32_t vcgt_type = read_u32(src, tag_offset + 8);
+
+	if (!src->valid || tag_type != VCGT_TYPE)
+		goto invalid_vcgt_tag;
+
+	// Only support table and equation types.
+	if (vcgt_type > VCGT_TYPE_LAST)
+		return true;
+
+	if (vcgt_type == VCGT_TYPE_TABLE) {
+		uint16_t channels = read_u16(src, tag_offset + 12);
+		uint16_t elements = read_u16(src, tag_offset + 14);
+		uint16_t byte_depth = read_u16(src, tag_offset + 16);
+		size_t table_offset = tag_offset + 18;
+		uint32_t i;
+		uint16_t *dest;
+
+		if (!src->valid)
+			goto invalid_vcgt_tag;
+
+		// Only support 3 channels.
+		if (channels != 3)
+			return true;
+		// Only support single or double byte values.
+		if (byte_depth != 1 && byte_depth != 2)
+			return true;
+		// Limit the table to a sensible size; 10-bit gamma is a reasonable
+		// maximum for hardware correction.
+		if (elements > 1024)
+			return true;
+
+		// Empty table is invalid.
+		if (!elements)
+			goto invalid_vcgt_tag;
+
+		profile->vcgt.length = elements;
+		profile->vcgt.data = malloc(3 * elements * sizeof(uint16_t));
+		if (!profile->vcgt.data)
+			return false;
+
+		dest = profile->vcgt.data;
+
+		for (i = 0; i < 3 * elements; ++i) {
+			if (byte_depth == 1) {
+				*dest++ = read_u8(src, table_offset) * 256;
+			} else {
+				*dest++ = read_u16(src, table_offset);
+			}
+
+			table_offset += byte_depth;
+
+			if (!src->valid)
+				goto invalid_vcgt_tag;
+		}
+	} else {
+		size_t formula_offset = tag_offset + 12;
+		int i;
+		size_t j;
+		uint16_t *dest;
+
+		// For formula always provide an 8-bit lut.
+		profile->vcgt.length = 256;
+		profile->vcgt.data = malloc(3 * profile->vcgt.length * sizeof(uint16_t));
+		if (!profile->vcgt.data)
+			return false;
+
+		dest = profile->vcgt.data;
+		for (i = 0; i < 3; ++i) {
+			float gamma = s15Fixed16Number_to_float(
+					read_s15Fixed16Number(src, formula_offset + 12 * i));
+			float min = s15Fixed16Number_to_float(
+					read_s15Fixed16Number(src, formula_offset + 4 + 12 * i));
+			float max = s15Fixed16Number_to_float(
+					read_s15Fixed16Number(src, formula_offset + 8 + 12 * i));
+			float range = max - min;
+
+			if (!src->valid)
+				goto invalid_vcgt_tag;
+
+			for (j = 0; j < profile->vcgt.length; ++j) {
+				*dest++ = 65535.f *
+					(min + range * pow((float)j / (profile->vcgt.length - 1), gamma));
+			}
 		}
 	}
-	return tag;
+
+	return true;
+
+invalid_vcgt_tag:
+	invalid_source(src, "invalid vcgt tag");
+	return false;
 }
 
+static bool read_tag_descType(qcms_profile *profile, struct mem_source *src, struct tag_index index, uint32_t tag_id)
+{
+	struct tag *tag = find_tag(index, tag_id);
+	if (tag) {
+		const uint32_t limit = sizeof profile->description;
+		uint32_t offset = tag->offset;
+		uint32_t type = read_u32(src, offset);
+		uint32_t length = read_u32(src, offset+8);
+		uint32_t i, description_offset;
+		bool mluc = false;
+		if (length && type == MLUC_TYPE) {
+			length = read_u32(src, offset+20);
+			if (!length || (length & 1) || (read_u32(src, offset+12) != 12))
+				goto invalid_desc_tag;
+			description_offset = offset + read_u32(src, offset+24);
+			if (!src->valid)
+				goto invalid_desc_tag;
+			mluc = true;
+		} else if (length && type == DESC_TYPE) {
+			description_offset = offset + 12;
+		} else {
+			goto invalid_desc_tag;
+		}
+		if (length >= limit)
+			length = limit - 1;
+		for (i = 0; i < length; ++i) {
+			uint8_t value = read_u8(src, description_offset + i);
+			if (!src->valid)
+				goto invalid_desc_tag;
+			if (mluc && !value)
+				value = '.';
+			profile->description[i] = value;
+		}
+		profile->description[length] = 0;
+	} else {
+		goto invalid_desc_tag;
+	}
+
+	if (src->valid)
+		return true;
+
+invalid_desc_tag:
+	invalid_source(src, "invalid description");
+	return false;
+}
+
+#if defined(__APPLE__)
+
+// Use the dscm tag to change profile description "Display" to its more specific en-localized monitor name, if any.
+
+#define TAG_dscm  0x6473636D // 'dscm'
+
+static bool read_tag_dscmType(qcms_profile *profile, struct mem_source *src, struct tag_index index, uint32_t tag_id)
+{
+	if (strcmp(profile->description, "Display") != 0)
+		return true;
+
+	struct tag *tag = find_tag(index, tag_id);
+	if (tag) {
+		uint32_t offset = tag->offset;
+		uint32_t type = read_u32(src, offset);
+		uint32_t records = read_u32(src, offset+8);
+
+		if (!src->valid || !records || type != MLUC_TYPE)
+			goto invalid_dscm_tag;
+		if (read_u32(src, offset+12) != 12) // MLUC record size: bytes
+			goto invalid_dscm_tag;
+
+		for (uint32_t i = 0; i < records; ++i) {
+			const uint32_t limit = sizeof profile->description;
+			const uint16_t isoen = 0x656E; // ISO-3166-1 language 'en'
+
+			uint16_t language = read_u16(src, offset + 16 + (i * 12) + 0);
+			uint32_t length = read_u32(src, offset + 16 + (i * 12) + 4);
+			uint32_t description_offset = read_u32(src, offset + 16 + (i * 12) + 8);
+
+			if (!src->valid || !length || (length & 1))
+				goto invalid_dscm_tag;
+			if (language != isoen)
+				continue;
+
+			// Use a prefix to identify the display description source
+			strcpy(profile->description, "dscm:");
+			length += 5;
+
+			if (length >= limit)
+				length = limit - 1;
+			for (uint32_t j = 5; j < length; ++j) {
+				uint8_t value = read_u8(src, offset + description_offset + j - 5);
+				if (!src->valid)
+					goto invalid_dscm_tag;
+				profile->description[j] = value ? value : '.';
+			}
+			profile->description[length] = 0;
+			break;
+		}
+	}
+
+	if (src->valid)
+		return true;
+
+invalid_dscm_tag:
+	invalid_source(src, "invalid dscm tag");
+	return false;
+}
+
+// Use the mmod tag to change profile description "Display" to its specific mmod maker model data, if any.
+
+#define TAG_mmod  0x6D6D6F64 // 'mmod'
+
+static bool read_tag_mmodType(qcms_profile *profile, struct mem_source *src, struct tag_index index, uint32_t tag_id)
+{
+	if (strcmp(profile->description, "Display") != 0)
+		return true;
+
+	struct tag *tag = find_tag(index, tag_id);
+	if (tag) {
+		const uint8_t length = 4 * 4; // Four 4-byte fields: 'mmod', 0, maker, model.
+
+		uint32_t offset = tag->offset;
+		if (tag->size < 40 || read_u32(src, offset) != MMOD_TYPE)
+			goto invalid_mmod_tag;
+
+		for (uint8_t i = 0; i < length; ++i) {
+			uint8_t value = read_u8(src, offset + i);
+			if (!src->valid)
+				goto invalid_mmod_tag;
+			profile->description[i] = value ? value : '.';
+		}
+		profile->description[length] = 0;
+	}
+
+	if (src->valid)
+		return true;
+
+invalid_mmod_tag:
+	invalid_source(src, "invalid mmod tag");
+	return false;
+}
+
+#endif // __APPLE__
+
 #define XYZ_TYPE		0x58595a20 // 'XYZ '
 #define CURVE_TYPE		0x63757276 // 'curv'
 #define PARAMETRIC_CURVE_TYPE	0x70617261 // 'para'
@@ -397,7 +690,7 @@
 	return num;
 }
 
-// Read the tag at a given offset rather then the tag_index. 
+// Read the tag at a given offset rather then the tag_index.
 // This method is used when reading mAB tags where nested curveType are
 // present that are not part of the tag_index.
 static struct curveType *read_curveType(struct mem_source *src, uint32_t offset, uint32_t *len)
@@ -448,7 +741,7 @@
 		curve->type = type;
 
 		for (i=0; i < COUNT_TO_LENGTH[count]; i++) {
-			curve->parameter[i] = s15Fixed16Number_to_float(read_s15Fixed16Number(src, offset + 12 + i*4));	
+			curve->parameter[i] = s15Fixed16Number_to_float(read_s15Fixed16Number(src, offset + 12 + i*4));
 		}
 		*len = 12 + COUNT_TO_LENGTH[count] * 4;
 
@@ -484,19 +777,23 @@
 	uint32_t channel_offset = 0;
 	int i;
 	for (i = 0; i < num_channels; i++) {
-		uint32_t tag_len;
+		uint32_t tag_len = ~0;
 
 		(*curveArray)[i] = read_curveType(src, curve_offset + channel_offset, &tag_len);
 		if (!(*curveArray)[i]) {
 			invalid_source(src, "invalid nested curveType curve");
 		}
 
+		if (tag_len == (uint32_t)~0) {
+			invalid_source(src, "invalid nested curveType tag length");
+			return;
+		}
+
 		channel_offset += tag_len;
 		// 4 byte aligned
 		if ((tag_len % 4) != 0)
 			channel_offset += 4 - (tag_len % 4);
 	}
-
 }
 
 static void mAB_release(struct lutmABType *lut)
@@ -526,7 +823,7 @@
 	uint32_t type = read_u32(src, offset);
 	uint8_t num_in_channels, num_out_channels;
 	struct lutmABType *lut;
-	int i;
+	uint32_t i;
 
 	if (type != LUT_MAB_TYPE && type != LUT_MBA_TYPE) {
 		return NULL;
@@ -540,7 +837,7 @@
 	// We require 3in/out channels since we only support RGB->XYZ (or RGB->LAB)
 	// XXX: If we remove this restriction make sure that the number of channels
 	//      is less or equal to the maximum number of mAB curves in qcmsint.h
-	//      also check for clut_size overflow.
+	//      also check for clut_size overflow. Also make sure it's != 0
 	if (num_in_channels != 3 || num_out_channels != 3)
 		return NULL;
 
@@ -570,6 +867,9 @@
 		// clut_size can not overflow since lg(256^num_in_channels) = 24 bits.
 		for (i = 0; i < num_in_channels; i++) {
 			clut_size *= read_u8(src, clut_offset + i);
+			if (clut_size == 0) {
+				invalid_source(src, "bad clut_size");
+			}
 		}
 	} else {
 		clut_size = 0;
@@ -588,8 +888,13 @@
 	memset(lut, 0, sizeof(struct lutmABType));
 	lut->clut_table   = &lut->clut_table_data[0];
 
-	for (i = 0; i < num_in_channels; i++) {
-		lut->num_grid_points[i] = read_u8(src, clut_offset + i);
+	if (clut_offset) {
+		for (i = 0; i < num_in_channels; i++) {
+			lut->num_grid_points[i] = read_u8(src, clut_offset + i);
+			if (lut->num_grid_points[i] == 0) {
+				invalid_source(src, "bad grid_points");
+			}
+		}
 	}
 
 	// Reverse the processing of transformation elements for mBA type.
@@ -657,11 +962,11 @@
 	uint16_t num_input_table_entries;
 	uint16_t num_output_table_entries;
 	uint8_t in_chan, grid_points, out_chan;
-	uint32_t clut_offset, output_offset;
+	size_t clut_offset, output_offset;
 	uint32_t clut_size;
 	size_t entry_size;
 	struct lutType *lut;
-	int i;
+	uint32_t i;
 
 	/* I'm not sure why the spec specifies a fixed number of entries for LUT8 tables even though
 	 * they have room for the num_entries fields */
@@ -672,6 +977,10 @@
 	} else if (type == LUT16_TYPE) {
 		num_input_table_entries  = read_u16(src, offset + 48);
 		num_output_table_entries = read_u16(src, offset + 50);
+		if (num_input_table_entries == 0 || num_output_table_entries == 0) {
+			invalid_source(src, "Bad channel count");
+			return NULL;
+		}
 		entry_size = 2;
 	} else {
 		assert(0); // the caller checks that this doesn't happen
@@ -685,15 +994,23 @@
 
 	clut_size = pow(grid_points, in_chan);
 	if (clut_size > MAX_CLUT_SIZE) {
+		invalid_source(src, "CLUT too large");
+		return NULL;
+	}
+
+	if (clut_size <= 0) {
+		invalid_source(src, "CLUT must not be empty.");
 		return NULL;
 	}
 
 	if (in_chan != 3 || out_chan != 3) {
+		invalid_source(src, "CLUT only supports RGB");
 		return NULL;
 	}
 
 	lut = malloc(sizeof(struct lutType) + (num_input_table_entries * in_chan + clut_size*out_chan + num_output_table_entries * out_chan)*sizeof(float));
 	if (!lut) {
+		invalid_source(src, "CLUT too large");
 		return NULL;
 	}
 
@@ -704,9 +1021,9 @@
 
 	lut->num_input_table_entries  = num_input_table_entries;
 	lut->num_output_table_entries = num_output_table_entries;
-	lut->num_input_channels   = read_u8(src, offset + 8);
-	lut->num_output_channels  = read_u8(src, offset + 9);
-	lut->num_clut_grid_points = read_u8(src, offset + 10);
+	lut->num_input_channels   = in_chan;
+	lut->num_output_channels  = out_chan;
+	lut->num_clut_grid_points = grid_points;
 	lut->e00 = read_s15Fixed16Number(src, offset+12);
 	lut->e01 = read_s15Fixed16Number(src, offset+16);
 	lut->e02 = read_s15Fixed16Number(src, offset+20);
@@ -846,6 +1163,7 @@
 	curve = malloc(sizeof(struct curveType) + sizeof(uInt16Number)*num_entries);
 	if (!curve)
 		return NULL;
+	curve->type = CURVE_TYPE;
 	curve->count = num_entries;
 	curve->data[0] = float_to_u8Fixed8Number(gamma);
 	return curve;
@@ -866,7 +1184,6 @@
 	if (!profile)
 		return NO_MEM_PROFILE;
 
-	//XXX: should store the whitepoint
 	if (!set_rgb_colorants(profile, white_point, primaries)) {
 		qcms_profile_release(profile);
 		return INVALID_PROFILE;
@@ -880,9 +1197,11 @@
 		qcms_profile_release(profile);
 		return NO_MEM_PROFILE;
 	}
+
 	profile->class = DISPLAY_DEVICE_PROFILE;
 	profile->rendering_intent = QCMS_INTENT_PERCEPTUAL;
 	profile->color_space = RGB_SIGNATURE;
+	profile->pcs = XYZ_SIGNATURE;
 	return profile;
 }
 
@@ -895,7 +1214,6 @@
 	if (!profile)
 		return NO_MEM_PROFILE;
 
-	//XXX: should store the whitepoint
 	if (!set_rgb_colorants(profile, white_point, primaries)) {
 		qcms_profile_release(profile);
 		return INVALID_PROFILE;
@@ -909,9 +1227,11 @@
 		qcms_profile_release(profile);
 		return NO_MEM_PROFILE;
 	}
+
 	profile->class = DISPLAY_DEVICE_PROFILE;
 	profile->rendering_intent = QCMS_INTENT_PERCEPTUAL;
 	profile->color_space = RGB_SIGNATURE;
+	profile->pcs = XYZ_SIGNATURE;
 	return profile;
 }
 
@@ -920,7 +1240,7 @@
  * Invalid values of tempK will return
  * (x,y,Y) = (-1.0, -1.0, -1.0)
  * similar to argyll: icx_DTEMP2XYZ() */
-static qcms_CIE_xyY white_point_from_temp(int temp_K)
+qcms_CIE_xyY white_point_from_temp(int temp_K)
 {
 	qcms_CIE_xyY white_point;
 	double x, y;
@@ -973,26 +1293,81 @@
 	qcms_profile *profile;
 	uint16_t *table;
 
-	qcms_CIE_xyYTRIPLE Rec709Primaries = {
-		{0.6400, 0.3300, 1.0},
-		{0.3000, 0.6000, 1.0},
-		{0.1500, 0.0600, 1.0}
+	// Standard Illuminant D65 in XYZ coordinates, which is the standard
+	// sRGB IEC61966-2.1 / Rec.709 profile reference media white point.
+	struct XYZNumber D65 = {
+		0xf351, 0x10000, 0x116cc // ( 0.950455, 1.000000, 1.089050 )
 	};
-	qcms_CIE_xyY D65;
 
-	D65 = white_point_from_temp(6504);
+	// sRGB IEC61966-2.1 / Rec.709 color profile primaries, chromatically
+	// adapted (via Bradford procedures) to D50 white point.
+	// For details, refer to crbug/580917
+#if 0
+	// lindbloom: ASTM E308-01 D50 White point.
+	s15Fixed16Number primaries[3][3] = {
+		{ 0x06fa3, 0x06294, 0x024a1 }, // ( 0.436081, 0.385071, 0.143082 )
+		{ 0x038f6, 0x0b785, 0x00f85 }, // ( 0.222504, 0.716873, 0.060623 )
+		{ 0x00391, 0x018dc, 0x0b6d4 }, // ( 0.013931, 0.097107, 0.714172 )
+	};
+#else
+	// ninedegreesbelow: ICC D50 White point.
+	s15Fixed16Number primaries[3][3] = {
+		{ 0x06fa0, 0x06296, 0x024a0 }, // ( 0.436035, 0.385101, 0.143066 )
+		{ 0x038f2, 0x0b789, 0x00f85 }, // ( 0.222443, 0.716934, 0.060623 )
+		{ 0x0038f, 0x018da, 0x0b6c4 }, // ( 0.013901, 0.097076, 0.713928 )
+	};
+#endif
 
 	table = build_sRGB_gamma_table(1024);
 
 	if (!table)
 		return NO_MEM_PROFILE;
 
-	profile = qcms_profile_create_rgb_with_table(D65, Rec709Primaries, table, 1024);
+	profile = qcms_profile_create();
+
+	if (!profile) {
+		free(table);
+		return NO_MEM_PROFILE;
+	}
+
+	profile->redTRC = curve_from_table(table, 1024);
+	profile->blueTRC = curve_from_table(table, 1024);
+	profile->greenTRC = curve_from_table(table, 1024);
+
+	if (!profile->redTRC || !profile->blueTRC || !profile->greenTRC) {
+		qcms_profile_release(profile);
+		free(table);
+		return NO_MEM_PROFILE;
+	}
+
+	profile->redColorant.X = primaries[0][0];
+	profile->redColorant.Y = primaries[1][0];
+	profile->redColorant.Z = primaries[2][0];
+
+	profile->greenColorant.X = primaries[0][1];
+	profile->greenColorant.Y = primaries[1][1];
+	profile->greenColorant.Z = primaries[2][1];
+
+	profile->blueColorant.X = primaries[0][2];
+	profile->blueColorant.Y = primaries[1][2];
+	profile->blueColorant.Z = primaries[2][2];
+
+	profile->mediaWhitePoint.X = D65.X;
+	profile->mediaWhitePoint.Y = D65.Y;
+	profile->mediaWhitePoint.Z = D65.Z;
+
+	profile->class = DISPLAY_DEVICE_PROFILE;
+	profile->rendering_intent = QCMS_INTENT_PERCEPTUAL;
+	profile->color_space = RGB_SIGNATURE;
+	profile->pcs = XYZ_SIGNATURE;
+
+	strcpy(profile->description, "sRGB IEC61966-2.1");
+
 	free(table);
+
 	return profile;
 }
 
-
 /* qcms_profile_from_memory does not hold a reference to the memory passed in */
 qcms_profile* qcms_profile_from_memory(const void *mem, size_t size)
 {
@@ -1006,6 +1381,9 @@
 	source.size = size;
 	source.valid = true;
 
+	if (size < 4)
+		return INVALID_PROFILE;
+
 	length = read_u32(src, 0);
 	if (length <= size) {
 		// shrink the area that we can read if appropriate
@@ -1023,7 +1401,7 @@
 		return NO_MEM_PROFILE;
 
 	check_CMM_type_signature(src);
-	check_profile_version(src);
+	read_profile_version(profile, src);
 	read_class_signature(profile, src);
 	read_rendering_intent(profile, src);
 	read_color_space(profile, src);
@@ -1037,12 +1415,26 @@
 	if (!src->valid || !index.tags)
 		goto invalid_tag_table;
 
+	if (!read_tag_descType(profile, src, index, TAG_desc))
+		goto invalid_tag_table;
+#if defined(__APPLE__)
+	if (!read_tag_dscmType(profile, src, index, TAG_dscm))
+		goto invalid_tag_table;
+	if (!read_tag_mmodType(profile, src, index, TAG_mmod))
+		goto invalid_tag_table;
+#endif // __APPLE__
+
 	if (find_tag(index, TAG_CHAD)) {
 		profile->chromaticAdaption = read_tag_s15Fixed16ArrayType(src, index, TAG_CHAD);
 	} else {
 		profile->chromaticAdaption.invalid = true; //Signal the data is not present
 	}
 
+	if (find_tag(index, TAG_vcgt)) {
+		if (!read_tag_vcgtType(profile, src, index))
+			goto invalid_tag_table;
+	}
+
 	if (profile->class == DISPLAY_DEVICE_PROFILE || profile->class == INPUT_DEVICE_PROFILE ||
             profile->class == OUTPUT_DEVICE_PROFILE  || profile->class == COLOR_SPACE_PROFILE) {
 		if (profile->color_space == RGB_SIGNATURE) {
@@ -1093,31 +1485,70 @@
 		goto invalid_tag_table;
 	}
 
+	// Profiles other than DeviceLink should have a media white point.
+	// Here we read it if present.
+	if (find_tag(index, TAG_wtpt)) {
+		profile->mediaWhitePoint = read_tag_XYZType(src, index, TAG_wtpt);
+	}
+
 	if (!src->valid)
 		goto invalid_tag_table;
 
 	free(index.tags);
-
 	return profile;
 
 invalid_tag_table:
-	free(index.tags);
+	if (index.tags)
+		free(index.tags);
 invalid_profile:
 	qcms_profile_release(profile);
 	return INVALID_PROFILE;
 }
 
+qcms_bool qcms_profile_match(qcms_profile *p1, qcms_profile *p2)
+{
+	return memcmp(p1->description, p2->description, sizeof p1->description) == 0;
+}
+
+const char* qcms_profile_get_description(qcms_profile *profile)
+{
+	return profile->description;
+}
+
 qcms_intent qcms_profile_get_rendering_intent(qcms_profile *profile)
 {
 	return profile->rendering_intent;
 }
 
-icColorSpaceSignature
-qcms_profile_get_color_space(qcms_profile *profile)
+qcms_color_space qcms_profile_get_color_space(qcms_profile *profile)
 {
 	return profile->color_space;
 }
 
+unsigned qcms_profile_get_version(qcms_profile *profile)
+{
+	return profile->icc_version & 0xffff;
+}
+
+size_t qcms_profile_get_vcgt_channel_length(qcms_profile *profile)
+{
+	return profile->vcgt.length;
+}
+
+// Check unsigned short is uint16_t.
+typedef char assert_short_not_16b[(sizeof(unsigned short) == sizeof(uint16_t)) ? 1 : -1];
+
+qcms_bool qcms_profile_get_vcgt_rgb_channels(qcms_profile *profile, unsigned short *data)
+{
+	size_t vcgt_channel_bytes = qcms_profile_get_vcgt_channel_length(profile) * sizeof(uint16_t);
+
+	if (!vcgt_channel_bytes || !data)
+		return false;
+
+	memcpy(data, profile->vcgt.data, 3 * vcgt_channel_bytes);
+	return true;
+}
+
 static void lut_release(struct lutType *lut)
 {
 	free(lut);
@@ -1142,6 +1573,9 @@
 	if (profile->mBA)
 		mAB_release(profile->mBA);
 
+	if (profile->vcgt.data)
+		free(profile->vcgt.data);
+
 	free(profile->redTRC);
 	free(profile->blueTRC);
 	free(profile->greenTRC);
@@ -1149,8 +1583,8 @@
 	free(profile);
 }
 
-
 #include <stdio.h>
+
 qcms_profile* qcms_profile_from_file(FILE *file)
 {
 	uint32_t length, remaining_length;
@@ -1197,17 +1631,3 @@
 	}
 	return profile;
 }
-
-#ifdef _WIN32
-/* Unicode path version */
-qcms_profile* qcms_profile_from_unicode_path(const wchar_t *path)
-{
-	qcms_profile *profile = NULL;
-	FILE *file = _wfopen(path, L"rb");
-	if (file) {
-		profile = qcms_profile_from_file(file);
-		fclose(file);
-	}
-	return profile;
-}
-#endif
diff --git a/invalid-coverage.c b/invalid-coverage.c
deleted file mode 100644
index b96df73..0000000
--- a/invalid-coverage.c
+++ /dev/null
@@ -1,308 +0,0 @@
-#include <stdlib.h>
-#include <assert.h>
-#include <stdint.h>
-#include "qcms.h"
-
-typedef uint32_t __be32;
-
-/* __builtin_bswap isn't available in older gccs
- * so open code it for now */
-static __be32 cpu_to_be32(int32_t v)
-{
-#ifdef LITTLE_ENDIAN
-	return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v & 0xff0000) >> 8) | ((v & 0xff000000) >> 24);
-	//return __builtin_bswap32(v);
-#else
-	return v;
-#endif
-}
-
-char *buf;
-
-static void write_u32(size_t offset, uint32_t value)
-{
-	*(__be32*)(buf + offset) = cpu_to_be32(value);
-}
-#if 0
-static uint16_t read_u16(struct mem_source *mem, size_t offset)
-{
-	if (offset + 2 > mem->size) {
-		invalid_source(mem, "Invalid offset");
-		return 0;
-	} else {
-		return be16_to_cpu(*(__be16*)(mem->buf + offset));
-	}
-}
-#endif
-static void write_u8(size_t offset, uint8_t value)
-{
-	*(uint8_t*)(buf + offset) = value;
-}
-static void write_u16(size_t offset, uint16_t value)
-{
-	*(uint8_t*)(buf + offset + 1) = value & 0xff;
-	*(uint8_t*)(buf + offset) = (value>>8) & 0xff;
-}
-
-
-#define PROFILE_LENGTH 18000
-int main()
-{
-	qcms_profile_release(qcms_profile_sRGB());
-
-	buf = calloc(PROFILE_LENGTH, 1);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	// invalid size
-	write_u32(0, PROFILE_LENGTH + 2500);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	// proper size
-	write_u32(0, PROFILE_LENGTH);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-#define INPUT_DEVICE_PROFILE   0x73636e72 // 'scnr'
-	write_u32(12, INPUT_DEVICE_PROFILE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(8, 0x3); // invalid major revision
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(8, 0x2); // major revision
-	write_u8(9, 0x55); // invalid minor revision
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(8, 0x2); // major revision
-	write_u8(9, 0x40); // minor revision
-	write_u8(10, 1); // reserved 1
-	write_u8(11, 0); // reserved 2
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(10, 0); // reserved 1
-
-	write_u8(64, 0x32); // invalid rendering intent
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(64, 0); // invalid rendering intent
-
-#define RGB_SIGNATURE  0x52474220
-#define GRAY_SIGNATURE 0x47524159
-	write_u32(16, 0xdeadbeef);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(16, RGB_SIGNATURE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-#define XYZ_SIGNATURE  0x58595A20
-	write_u32(20, XYZ_SIGNATURE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128, 15000); // tag count
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128, 15); // tag count
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-     #define TAG_bXYZ 0x6258595a
-     #define TAG_gXYZ 0x6758595a
-     #define TAG_rXYZ 0x7258595a
-     #define TAG_rTRC 0x72545243
-     #define TAG_bTRC 0x62545243
-     #define TAG_gTRC 0x67545243
-     #define TAG_kTRC 0x6b545243
-     #define TAG_A2B0 0x41324230
-     #define TAG_B2A0 0x42324130
-     #define TAG_CHAD 0x63686164
-
-	write_u32(128 + 4, TAG_rXYZ); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(128 + 4 + 4, 1000); // offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*1*3, TAG_gXYZ); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(128 + 4 + 4*1*3 + 4, 1000); // offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*2*3, TAG_bXYZ); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(128 + 4 + 4*2*3 + 4, 1000); // offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-#define XYZ_TYPE   0x58595a20 // 'XYZ '
-#define CURVE_TYPE 0x63757276 // 'curv'
-#define LUT16_TYPE 0x6d667432 // 'mft2'
-#define LUT8_TYPE  0x6d667431 // 'mft1'
-#define LUT_MAB_TYPE		0x6d414220 // 'mAB '
-#define LUT_MBA_TYPE		0x6d424120 // 'mBA '
-#define CHROMATIC_TYPE          0x73663332 // 'sf32'
-#define PARAMETRIC_CURVE_TYPE   0x70617261 // 'para'
-	write_u32(1000, XYZ_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*3*3, TAG_rTRC); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(128 + 4 + 4*3*3 + 4, 1100); // offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*4*3, TAG_gTRC); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(128 + 4 + 4*4*3 + 4, 1100); // offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*5*3, TAG_bTRC); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(128 + 4 + 4*5*3 + 4, 1100); // offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*6*3, TAG_A2B0); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*6*3 + 4, 1200); // offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*7*3, TAG_CHAD); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(128 + 4 + 4*7*3 + 4, 5000); // offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200, 5); // invalid lut type
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200, LUT8_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(1200 + 8, 9); // max clut size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(1200 + 10, 9); // max clut size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(1200 + 8, 3); // in_chan
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(1200 + 9, 3); // proper out_chan
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(1200 + 10, 1); // sane clut size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200, LUT16_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u16(1200 + 48, 3); // input_table_entries
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u16(1200 + 50, 3); // output_table_entries
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*6*3, TAG_A2B0); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*6*3, TAG_B2A0); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200, LUT_MBA_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200, LUT_MAB_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*6*3, TAG_A2B0); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(1200 + 8, 15); // > max in_chan
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(1200 + 9, 15); // > max out_chan
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(1200 + 9, 4); // long out_chan
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(1200 + 8, 2); // short in_chan
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(1200 + 9, 3); // proper out_chan
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(1200 + 8, 3); // proper out_chan
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-
-	write_u32(1200 + 12, 5); // b curve offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200 + 12, 2000); // b curve offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200 + 16, 2000); // matrix offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200 + 20, 2000); // m curve offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200 + 24, 3000); // clut offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(4200, 255); // clut channel size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(4201, 255); // clut channel size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(4202, 255); // clut channel size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(4200, 2); // clut channel size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(4201, 2); // clut channel size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(4202, 2); // clut channel size
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u8(4216, 1); // clut precision
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u8(4216, 2); // clut precision
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1200 + 28, 2000); // a curve offset
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(3200, PARAMETRIC_CURVE_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u16(3208, 5);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u16(3208, 4);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u16(3208, 2);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(3200, CURVE_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	// reset the values
-	write_u16(3208, 0);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-
-	write_u32(3212, CURVE_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(3224, CURVE_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(5000, CHROMATIC_TYPE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-#if 1
-	write_u32(1100, CURVE_TYPE);
-	qcms_profile_release(qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1108, 100000); // curve count
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(1108, 1); // curve count
-	qcms_profile_release(qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	/* test out gray profiles */
-	write_u32(16, GRAY_SIGNATURE);
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	write_u32(128 + 4 + 4*8*3, TAG_kTRC); // tag
-	assert(!qcms_profile_from_memory(buf, PROFILE_LENGTH));
-	write_u32(128 + 4 + 4*8*3 + 4, 1100); // offset
-	qcms_profile_release(qcms_profile_from_memory(buf, PROFILE_LENGTH));
-
-	/* test out profiles that are the wrong size */
-	qcms_profile_from_path("sample-trunc.icc");
-#endif
-	return 0;
-}
-
diff --git a/lcms-compare.c b/lcms-compare.c
deleted file mode 100644
index 566eb1e..0000000
--- a/lcms-compare.c
+++ /dev/null
@@ -1,96 +0,0 @@
-#include <stdlib.h>
-#include <time.h>
-#include "sum.h"
-#include "lcms.h"
-#include "qcms.h"
-
-int main(int argc, char **argv)
-{
-	char *input_path = argv[1];
-	char *output_path = argv[2];
-	
-	qcms_profile *input_profile, *output_profile;
-	qcms_transform *transform;
-#define ALL
-#ifndef ALL
-#define LENGTH 1
-#else
-#define LENGTH (256*256*256)
-#endif
-	static unsigned char src[LENGTH*3];
-	static unsigned char qoutput[LENGTH*3];
-	static unsigned char loutput[LENGTH*3];
-#ifdef ALL
-	int i,j,k,l=0;
-	for (i=0; i<256; i++) {
-		for (j=0; j<256; j++) {
-			for (k=0; k<256; k++) {
-				src[l++] = i;
-				src[l++] = j;
-				src[l++] = k;
-			}
-		}
-	}
-#else
-	int i;
-	src[0] = 19;
-	src[1] = 28;
-	src[2] = 56;
-#endif
-	clock_t lcms_start = clock();
-	cmsHPROFILE linput_profile, loutput_profile;
-	cmsHTRANSFORM transformFixed;
-	linput_profile = cmsOpenProfileFromFile(input_path, "r");
-	loutput_profile = cmsOpenProfileFromFile(output_path, "r");
-#if 0
-	cmsPrecacheProfile(loutput_profile, CMS_PRECACHE_LI168_REVERSE);
-	cmsPrecacheProfile(linput_profile, CMS_PRECACHE_LI8F_FORWARD);
-	int flags = cmsFLAGS_FLOATSHAPER;
-#else
-	int flags = 0;
-#endif
-	transformFixed = cmsCreateTransform(
-			linput_profile, TYPE_RGB_8, 
-			loutput_profile, TYPE_RGB_8, 
-			INTENT_RELATIVE_COLORIMETRIC, flags);
-#if 0
-        QCMS_INTENT_PERCEPTUAL = 0,
-			               QCMS_INTENT_RELATIVE_COLORIMETRIC = 1,
-				               QCMS_INTENT_SATURATION = 2,
-					               QCMS_INTENT_ABSOLUTE_COLORIMETRIC = 3
-
-#endif
-	cmsDoTransform(transformFixed, src, loutput, LENGTH);
-	clock_t lcms_time = clock() - lcms_start;
-	clock_t qcms_start = clock();
-	input_profile = qcms_profile_from_path(input_path);
-	output_profile = qcms_profile_from_path(output_path);
-	qcms_profile_precache_output_transform(output_profile);
-
-	transform = qcms_transform_create(input_profile, QCMS_DATA_RGB_8, output_profile, QCMS_DATA_RGB_8, QCMS_INTENT_PERCEPTUAL);
-	qcms_transform_data(transform, src, qoutput, LENGTH);
-	clock_t qcms_time = clock() - qcms_start;
-	printf("lcms: %ld\n", lcms_time);
-	printf("qcms: %ld\n", qcms_time);
-	int total_diff = 0;
-	for (i=0; i<LENGTH; i++) {
-		int diff = 0;
-		diff += abs(loutput[i*3]-qoutput[i*3]);
-		diff += abs(loutput[i*3+1]-qoutput[i*3+1]);
-		diff += abs(loutput[i*3+2]-qoutput[i*3+2]);
-		total_diff += diff;
-		if (diff > 3) {
-			printf("differing output(%d): (%d %d %d) -> l(%d %d %d) vs. q(%d %d %d)\n",
-					diff, src[i*3], src[i*3+1], src[i*3+2],
-					loutput[i*3], loutput[i*3+1], loutput[i*3+2],
-					qoutput[i*3],
-					qoutput[i*3+1],
-					qoutput[i*3+2]);
-			//exit(1);
-		}
-	}
-	printf("%d - %f\n", total_diff, (double)total_diff/LENGTH);
-	qcms_profile_release(input_profile);
-	qcms_profile_release(output_profile);
-	return 0;
-}
diff --git a/malloc-fail.c b/malloc-fail.c
deleted file mode 100644
index 9554aa4..0000000
--- a/malloc-fail.c
+++ /dev/null
@@ -1,141 +0,0 @@
-#define _GNU_SOURCE
-
-#include <stdlib.h>
-#include <assert.h>
-#include <dlfcn.h> 
-
-#include "qcms.h"
-
-const unsigned char gray_icc[] =
-{0x00, 0x00, 0x01, 0x70, 0x4E, 0x4B, 0x4F, 0x4E, 0x02, 0x20, 0x00, 0x00,
-0x6D, 0x6E, 0x74, 0x72, 0x47, 0x52, 0x41, 0x59, 0x58, 0x59, 0x5A, 0x20,
-0x07, 0xCE, 0x00, 0x0B, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x61, 0x63, 0x73, 0x70, 0x41, 0x50, 0x50, 0x4C, 0x00, 0x00, 0x00, 0x00,
-0x6E, 0x6F, 0x6E, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6, 0xD6,
-0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xD3, 0x2D, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
-0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x4B,
-0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x01, 0x0C, 0x00, 0x00, 0x00, 0x14,
-0x6B, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x20, 0x00, 0x00, 0x00, 0x0E,
-0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0x30, 0x00, 0x00, 0x00, 0x2C,
-0x62, 0x6B, 0x70, 0x74, 0x00, 0x00, 0x01, 0x5C, 0x00, 0x00, 0x00, 0x14,
-0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1A,
-0x4E, 0x69, 0x6B, 0x6F, 0x6E, 0x47, 0x72, 0x61, 0x79, 0x47, 0x31, 0x2E,
-0x38, 0x20, 0x76, 0x34, 0x2E, 0x30, 0x2E, 0x30, 0x2E, 0x33, 0x30, 0x30,
-0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x1A, 0x4E, 0x69, 0x6B, 0x6F, 0x6E, 0x47, 0x72, 0x61, 0x79, 0x47, 0x31,
-0x2E, 0x38, 0x20, 0x76, 0x34, 0x2E, 0x30, 0x2E, 0x30, 0x2E, 0x33, 0x30,
-0x30, 0x30, 0x00, 0x00, 0x58, 0x59, 0x5A, 0x20, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0xF3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xCC,
-0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
-0x01, 0xCD, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00,
-0x4E, 0x69, 0x6B, 0x6F, 0x6E, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x20, 0x26,
-0x20, 0x4E, 0x69, 0x6B, 0x6F, 0x6E, 0x20, 0x43, 0x6F, 0x72, 0x70, 0x6F,
-0x72, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x32, 0x30, 0x30, 0x31, 0x00,
-0x58, 0x59, 0x5A, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
-void test_gray(qcms_profile *output_profile)
-{
-	unsigned char srct[3] = { 221, 79, 129};
-	unsigned char outt[3];
-	qcms_transform *transform;
-	qcms_profile *gray_profile = qcms_profile_from_memory(gray_icc, sizeof(gray_icc));
-	if (gray_profile) {
-		transform = qcms_transform_create(gray_profile, QCMS_DATA_GRAY_8, output_profile, QCMS_DATA_RGB_8, QCMS_INTENT_PERCEPTUAL);
-		if (transform) {
-			qcms_transform_data(transform, srct, outt, 1);
-			qcms_transform_release(transform);
-		}
-		qcms_profile_release(gray_profile);
-	}
-
-}
-
-void test_gray_precache(qcms_profile *output_profile)
-{
-	unsigned char srct[3] = { 221, 79, 129};
-	unsigned char outt[3];
-	qcms_transform *transform;
-	qcms_profile *gray_profile = qcms_profile_from_memory(gray_icc, sizeof(gray_icc));
-	qcms_profile_precache_output_transform(output_profile);
-	if (gray_profile) {
-		transform = qcms_transform_create(gray_profile, QCMS_DATA_GRAY_8, output_profile, QCMS_DATA_RGB_8, QCMS_INTENT_PERCEPTUAL);
-		if (transform) {
-			qcms_transform_data(transform, srct, outt, 1);
-			qcms_transform_release(transform);
-		}
-		qcms_profile_release(gray_profile);
-	}
-
-}
-void do_test(void) {
-	unsigned char srct[4] = { 221, 79, 129, 92};
-	unsigned char outt[4];
-	qcms_transform *transform;
-	qcms_profile *input_profile, *output_profile, *rgb;
-	qcms_CIE_xyY invalid_white_point = { 0., 0., 1.};
-	qcms_CIE_xyY white_point = { 0.9, 1., 1.};
-	qcms_CIE_xyYTRIPLE primaries = { {.9, .3, 1.}, {.2, .4, 1.}, {.7, .4, 1.}};
-
-	rgb = qcms_profile_create_rgb_with_gamma(invalid_white_point, primaries, 1.8);
-	if (rgb)
-		qcms_profile_release(rgb);
-	rgb = qcms_profile_create_rgb_with_gamma(white_point, primaries, 1.8);
-	input_profile = qcms_profile_sRGB();
-	output_profile = qcms_profile_sRGB();
-	if (output_profile) {
-		test_gray(output_profile);
-		test_gray_precache(output_profile);
-		qcms_profile_release(output_profile);
-	}
-	if (input_profile)
-		qcms_profile_release(input_profile);
-	if (rgb)
-		qcms_profile_release(rgb);
-	rgb = qcms_profile_from_path("sample-trunc.icc");
-	if (rgb)
-		qcms_profile_release(rgb);
-}
-
-static int current_counter;
-static int counter;
-
-void* malloc(size_t size)
-{
-	if (counter == current_counter++) {
-		return NULL;
-	}
-	static void* (*real_malloc)(size_t size);
-	if (!real_malloc)
-		real_malloc = (void* (*)(size_t)) dlsym(RTLD_NEXT, "malloc");
-	return real_malloc(size);
-}
-
-void* calloc(size_t count, size_t size)
-{
-	if (counter == current_counter++) {
-		return NULL;
-	}
-	static void* (*real_calloc)(size_t count, size_t size);
-	if (!real_calloc)
-		real_calloc = (void* (*)(size_t, size_t)) dlsym(RTLD_NEXT, "calloc");
-	return real_calloc(count, size);
-}
-
-
-const extern unsigned char gray_icc[];
-int main()
-{
-	while (current_counter >= counter) {
-		current_counter = 0;
-		do_test();
-		counter++;
-	}
-	return 0;
-}
-
diff --git a/qcms.h b/qcms.h
index 7d83623..b91498c 100644
--- a/qcms.h
+++ b/qcms.h
@@ -1,3 +1,25 @@
+/* vim: set ts=8 sw=8 noexpandtab: */
+//  qcms
+//  Copyright (C) 2009 Mozilla Foundation
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the "Software"),
+// to deal in the Software without restriction, including without limitation
+// the rights to use, copy, modify, merge, publish, distribute, sublicense,
+// and/or sell copies of the Software, and to permit persons to whom the Software
+// is furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
 #ifndef QCMS_H
 #define QCMS_H
 
@@ -5,87 +27,32 @@
 extern "C" {
 #endif
 
-/* if we've already got an ICC_H header we can ignore the following */
-#ifndef ICC_H
-/* icc34 defines */
-
-/***************************************************************** 
- 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. 
-******************************************************************/
-
-/* 
- * 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;
-#endif
-
 #include <stdio.h>
 
-typedef int qcms_bool;
-
-struct _qcms_transform;
-typedef struct _qcms_transform qcms_transform;
-
 struct _qcms_profile;
 typedef struct _qcms_profile qcms_profile;
 
-/* these values match the Rendering Intent values from the ICC spec */
+struct _qcms_transform;
+typedef struct _qcms_transform qcms_transform;
+
+typedef int qcms_bool;
+
+/* ICC Section 6.1.5 Color Space Signatures (abridged) */
+typedef enum {
+	XYZData		/* ‘XYZ ’ */ = 0x58595A20,
+	labData		/* ‘Lab ’ */ = 0x4C616220,
+	luvData		/* ‘Luv ’ */ = 0x4C757620,
+	YCbCrData	/* ‘YCbr' */ = 0x59436272,
+	YxyData		/* ‘Yxy ’ */ = 0x59787920,
+	rgbData		/* ‘RGB ’ */ = 0x52474220,
+	grayData	/* ‘GRAY’ */ = 0x47524159,
+	hsvData		/* ‘HSV ’ */ = 0x48535620,
+	hlsData		/* ‘HLS ’ */ = 0x484C5320,
+	cmykData	/* ‘CMYK’ */ = 0x434D594B,
+	cmyData		/* ‘CMY ’ */ = 0x434D5920,
+} qcms_color_space;
+
+/* ICC Section 6.1.11 Rendering Intents */
 typedef enum {
 	QCMS_INTENT_DEFAULT = 0,
 	QCMS_INTENT_PERCEPTUAL = 0,
@@ -94,7 +61,7 @@
 	QCMS_INTENT_ABSOLUTE_COLORIMETRIC = 3
 } qcms_intent;
 
-//XXX: I don't really like the _DATA_ prefix
+/* Input data formats */
 typedef enum {
 	QCMS_DATA_RGB_8,
 	QCMS_DATA_RGBA_8,
@@ -102,21 +69,45 @@
 	QCMS_DATA_GRAYA_8
 } qcms_data_type;
 
-/* the names for the following two types are sort of ugly */
-typedef struct
-{
+/* Output data format for qcms_transform_data_type() */
+typedef enum {
+	QCMS_OUTPUT_RGBX,
+	QCMS_OUTPUT_BGRX
+} qcms_output_type;
+
+/* Output data format for qcms_transform_get_input|output_trc_rgba() */
+typedef enum {
+	QCMS_TRC_PARAMETRIC, // Not implemented.
+	QCMS_TRC_FLOAT,      // Not implemented.
+	QCMS_TRC_HALF_FLOAT, // IEE754: binary16.
+	QCMS_TRC_USHORT,     // 0.16 fixed point.
+} qcms_trc_type;
+
+/* Output data of specific channel curve for qcms_profile_get_parametric_curve() */
+typedef enum {
+	QCMS_TRC_RED,
+	QCMS_TRC_GREEN,
+	QCMS_TRC_BLUE,
+} qcms_trc_channel;
+
+typedef struct {
 	double x;
 	double y;
 	double Y;
 } qcms_CIE_xyY;
 
-typedef struct
-{
+typedef struct {
 	qcms_CIE_xyY red;
 	qcms_CIE_xyY green;
 	qcms_CIE_xyY blue;
 } qcms_CIE_xyYTRIPLE;
 
+typedef struct {
+	float X;
+	float Y;
+	float Z;
+} qcms_xyz_float;
+
 qcms_profile* qcms_profile_create_rgb_with_gamma(
 		qcms_CIE_xyY white_point,
 		qcms_CIE_xyYTRIPLE primaries,
@@ -126,26 +117,50 @@
 
 qcms_profile* qcms_profile_from_file(FILE *file);
 qcms_profile* qcms_profile_from_path(const char *path);
-#ifdef _WIN32
-qcms_profile* qcms_profile_from_unicode_path(const wchar_t *path);
-#endif
 qcms_profile* qcms_profile_sRGB(void);
 void qcms_profile_release(qcms_profile *profile);
 
 qcms_bool qcms_profile_is_bogus(qcms_profile *profile);
+qcms_bool qcms_profile_has_white_point(qcms_profile *profile);
+qcms_xyz_float qcms_profile_get_white_point(qcms_profile *profile);
 qcms_intent qcms_profile_get_rendering_intent(qcms_profile *profile);
-icColorSpaceSignature qcms_profile_get_color_space(qcms_profile *profile);
+qcms_color_space qcms_profile_get_color_space(qcms_profile *profile);
+unsigned qcms_profile_get_version(qcms_profile *profile);
+qcms_bool qcms_profile_white_transform(qcms_profile *profile, float XYZ[3]);
+
+qcms_bool qcms_profile_match(qcms_profile *p1, qcms_profile *p2);
+const char* qcms_profile_get_description(qcms_profile *profile);
 
 void qcms_profile_precache_output_transform(qcms_profile *profile);
 
+size_t qcms_profile_get_vcgt_channel_length(qcms_profile *profile);
+qcms_bool qcms_profile_get_vcgt_rgb_channels(qcms_profile *profile, unsigned short *data);
+
+float qcms_profile_ntsc_relative_gamut_size(qcms_profile *profile);
+
+size_t qcms_profile_get_parametric_curve(qcms_profile *profile, qcms_trc_channel channel, float data[7]);
+
 qcms_transform* qcms_transform_create(
 		qcms_profile *in, qcms_data_type in_type,
-		qcms_profile* out, qcms_data_type out_type,
+		qcms_profile *out, qcms_data_type out_type,
 		qcms_intent intent);
 
-void qcms_transform_release(qcms_transform *);
+size_t qcms_transform_get_input_trc_rgba(
+		qcms_transform *transform, qcms_profile *in, qcms_trc_type type, unsigned short *data);
+size_t qcms_transform_get_output_trc_rgba(
+		qcms_transform *transform, qcms_profile *out, qcms_trc_type type, unsigned short *data);
+
+qcms_bool qcms_transform_is_matrix(qcms_transform *transform);
+float qcms_transform_get_matrix(qcms_transform *transform, unsigned i, unsigned j);
+
+qcms_bool qcms_transform_create_LUT_zyx_bgra(
+		qcms_profile *in, qcms_profile *out, qcms_intent intent,
+		int samples, unsigned char* lut);
 
 void qcms_transform_data(qcms_transform *transform, void *src, void *dest, size_t length);
+void qcms_transform_data_type(qcms_transform *transform, void *src, void *dest, size_t length, qcms_output_type type);
+
+void qcms_transform_release(qcms_transform *);
 
 void qcms_enable_iccv4();
 
@@ -153,4 +168,10 @@
 }
 #endif
 
+/*
+ * In general, QCMS is not threadsafe. However, it should be safe to create
+ * profile and transformation objects on different threads, so long as you
+ * don't use the same objects on different threads at the same time.
+ */
+
 #endif
diff --git a/qcms_util.c b/qcms_util.c
new file mode 100644
index 0000000..9b2d9fa
--- /dev/null
+++ b/qcms_util.c
@@ -0,0 +1,69 @@
+// Copyright 2016 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the Chromium LICENSE file.
+
+#include "qcmsint.h"
+
+#include <math.h>
+
+typedef struct _qcms_coords {
+    float x;
+    float y;
+} qcms_coords;
+
+typedef struct _qcms_triangle {
+    qcms_coords verticies[3];
+} qcms_triangle;
+
+#define NTSC_1953_GAMUT_SIZE    0.1582
+
+static qcms_triangle get_profile_triangle(qcms_profile *profile)
+{
+    float sumRed = s15Fixed16Number_to_float(profile->redColorant.X) +
+                   s15Fixed16Number_to_float(profile->redColorant.Y) +
+                   s15Fixed16Number_to_float(profile->redColorant.Z);
+    float xRed = s15Fixed16Number_to_float(profile->redColorant.X) / sumRed;
+    float yRed = s15Fixed16Number_to_float(profile->redColorant.Y) / sumRed;
+
+    float sumGreen = s15Fixed16Number_to_float(profile->greenColorant.X) +
+                     s15Fixed16Number_to_float(profile->greenColorant.Y) +
+                     s15Fixed16Number_to_float(profile->greenColorant.Z);
+    float xGreen = s15Fixed16Number_to_float(profile->greenColorant.X) / sumGreen;
+    float yGreen = s15Fixed16Number_to_float(profile->greenColorant.Y) / sumGreen;
+
+    float sumBlue = s15Fixed16Number_to_float(profile->blueColorant.X) +
+                    s15Fixed16Number_to_float(profile->blueColorant.Y) +
+                    s15Fixed16Number_to_float(profile->blueColorant.Z);
+    float xBlue = s15Fixed16Number_to_float(profile->blueColorant.X) / sumBlue;
+    float yBlue = s15Fixed16Number_to_float(profile->blueColorant.Y) / sumBlue;
+
+    qcms_triangle triangle = {{{xRed, yRed}, {xGreen, yGreen}, {xBlue, yBlue}}};
+    return triangle;
+}
+
+static float get_triangle_area(const qcms_triangle candidate)
+{
+    float xRed = candidate.verticies[0].x;
+    float yRed = candidate.verticies[0].y;
+    float xGreen = candidate.verticies[1].x;
+    float yGreen = candidate.verticies[1].y;
+    float xBlue = candidate.verticies[2].x;
+    float yBlue = candidate.verticies[2].y;
+
+    float area = fabs((xRed - xBlue) * (yGreen - yBlue) - (xGreen - xBlue) * (yRed - yBlue)) / 2;
+    return area;
+}
+
+static float get_ntsc_gamut_metric_area(const qcms_triangle candidate)
+{
+    float area = get_triangle_area(candidate);
+    return area * 100 / NTSC_1953_GAMUT_SIZE;
+}
+
+float qcms_profile_ntsc_relative_gamut_size(qcms_profile *profile)
+{
+    qcms_triangle triangle = get_profile_triangle(profile);
+    return get_ntsc_gamut_metric_area(triangle);
+}
+
+
diff --git a/qcmsint.h b/qcmsint.h
index 15c18ff..005b089 100644
--- a/qcmsint.h
+++ b/qcmsint.h
@@ -1,23 +1,23 @@
-// vim: set ts=8 sw=8 noexpandtab:
+/* vim: set ts=8 sw=8 noexpandtab: */
 //  qcms
 //  Copyright (C) 2009 Mozilla Foundation
 //
-// 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 
+// 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 
+// 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 
+// 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 "qcms.h"
@@ -45,6 +45,11 @@
 #define ALIGN __attribute__(( aligned (16) ))
 #endif
 
+typedef struct _qcms_format_type {
+	int r;
+	int b;
+} qcms_format_type;
+
 struct _qcms_transform {
 	float ALIGN matrix[3][4];
 	float *input_gamma_table_r;
@@ -88,7 +93,16 @@
 	struct precache_output *output_table_g;
 	struct precache_output *output_table_b;
 
-	void (*transform_fn)(struct _qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length);
+	void (*transform_fn)(struct _qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, struct _qcms_format_type output_format);
+
+	unsigned char floor_cache[256];
+	unsigned char ceil_cache[256];
+	float r_cache[256];
+
+#define TRANSFORM_FLAG_MATRIX		0x0001
+#define TRANSFORM_FLAG_CLUT_CACHE	0x0002
+
+	uint16_t transform_flags;
 };
 
 struct matrix {
@@ -200,6 +214,14 @@
 
 	float table_data[];
 };
+
+struct vcgtType {
+	/* data contains three gamma channels: R[length], then G[length], then
+	 * B[length]. */
+	uint16_t *data;
+	size_t length;
+};
+
 #if 0
 /* this is from an intial idea of having the struct correspond to the data in
  * the file. I decided that it wasn't a good idea.
@@ -225,10 +247,13 @@
 #define LAB_SIGNATURE  0x4C616220
 
 struct _qcms_profile {
+	uint32_t icc_version;
+	char description[64];
 	uint32_t class;
 	uint32_t color_space;
 	uint32_t pcs;
 	qcms_intent rendering_intent;
+	struct XYZNumber mediaWhitePoint;
 	struct XYZNumber redColorant;
 	struct XYZNumber blueColorant;
 	struct XYZNumber greenColorant;
@@ -241,6 +266,7 @@
 	struct lutmABType *mAB;
 	struct lutmABType *mBA;
 	struct matrix chromaticAdaption;
+	struct vcgtType vcgt;
 
 	struct precache_output *output_table_r;
 	struct precache_output *output_table_g;
@@ -280,41 +306,37 @@
 void qcms_transform_data_rgb_out_lut_sse2(qcms_transform *transform,
                                           unsigned char *src,
                                           unsigned char *dest,
-                                          size_t length);
+                                          size_t length,
+                                          qcms_format_type output_format);
 void qcms_transform_data_rgba_out_lut_sse2(qcms_transform *transform,
                                           unsigned char *src,
                                           unsigned char *dest,
-                                          size_t length);
-void qcms_transform_data_rgb_out_lut_sse1(qcms_transform *transform,
-                                          unsigned char *src,
-                                          unsigned char *dest,
-                                          size_t length);
-void qcms_transform_data_rgba_out_lut_sse1(qcms_transform *transform,
-                                          unsigned char *src,
-                                          unsigned char *dest,
-                                          size_t length);
+                                          size_t length,
+                                          qcms_format_type output_format);
+void qcms_transform_data_tetra_clut_rgba_sse2(qcms_transform* transform,
+                                              unsigned char* src,
+                                              unsigned char* dest,
+                                              size_t length,
+                                              qcms_format_type output_format);
+
+void qcms_transform_build_clut_cache(qcms_transform* transform);
 
 extern qcms_bool qcms_supports_iccv4;
 
-#ifdef NATIVE_OUTPUT
-# define RGB_OUTPUT_COMPONENTS 4
-# define RGBA_OUTPUT_COMPONENTS 4
-# ifdef IS_LITTLE_ENDIAN
-#  define OUTPUT_INDEX_A 3
-#  define OUTPUT_INDEX_R 2
-#  define OUTPUT_INDEX_G 1
-#  define OUTPUT_INDEX_B 0
-# else
-#  define OUTPUT_INDEX_A 0
-#  define OUTPUT_INDEX_R 1
-#  define OUTPUT_INDEX_G 2
-#  define OUTPUT_INDEX_B 3
-# endif
+
+#ifdef _MSC_VER
+
+long __cdecl _InterlockedIncrement(long volatile *);
+long __cdecl _InterlockedDecrement(long volatile *);
+#pragma intrinsic(_InterlockedIncrement)
+#pragma intrinsic(_InterlockedDecrement)
+
+#define qcms_atomic_increment(x) _InterlockedIncrement((long volatile *)&x)
+#define qcms_atomic_decrement(x) _InterlockedDecrement((long volatile*)&x)
+
 #else
-# define RGB_OUTPUT_COMPONENTS 3
-# define RGBA_OUTPUT_COMPONENTS 4
-# define OUTPUT_R_INDEX 0
-# define OUTPUT_G_INDEX 1
-# define OUTPUT_B_INDEX 2
-# define OUTPUT_A_INDEX 3
+
+#define qcms_atomic_increment(x) __sync_add_and_fetch(&x, 1)
+#define qcms_atomic_decrement(x) __sync_sub_and_fetch(&x, 1)
+
 #endif
diff --git a/qcmstypes.h b/qcmstypes.h
index 584ca94..b97307a 100644
--- a/qcmstypes.h
+++ b/qcmstypes.h
@@ -1,48 +1,27 @@
 //  qcms
 //  Copyright (C) 2009 Mozilla Foundation
 //
-// 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 
+// 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 
+// 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 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 #ifndef QCMS_TYPES_H
 #define QCMS_TYPES_H
 
-#ifdef MOZ_QCMS
-
-#include "mozilla/StandardInteger.h"
-
-#include "prtypes.h"
-/* prtypes.h defines IS_LITTLE_ENDIAN and IS_BIG_ENDIAN */
-
-#if defined (__SVR4) && defined (__sun)
-/* int_types.h gets included somehow, so avoid redefining the types differently */
-#include <sys/int_types.h>
-#elif defined (_AIX)
-#include <sys/types.h>
-#elif defined(__OS2__)
-/* OS/2's stdlib typdefs uintptr_t. So we'll just include that so we don't collide */
-#include <stdlib.h>
-#elif !defined(__intptr_t_defined) && !defined(_UINTPTR_T_DEFINED)
-typedef unsigned long uintptr_t;
-#endif
-
-#else // MOZ_QCMS
-
 #if BYTE_ORDER == LITTLE_ENDIAN
 #define IS_LITTLE_ENDIAN
 #elif BYTE_ORDER == BIG_ENDIAN
@@ -65,7 +44,7 @@
 
 #if defined (_SVR4) || defined (SVR4) || defined (__OpenBSD__) || defined (_sgi) || defined (__sun) || defined (sun) || defined (__digital__)
 #  include <inttypes.h>
-#elif defined (_MSC_VER)
+#elif defined (_MSC_VER) && _MSC_VER < 1600
 typedef __int8 int8_t;
 typedef unsigned __int8 uint8_t;
 typedef __int16 int16_t;
@@ -74,11 +53,6 @@
 typedef unsigned __int32 uint32_t;
 typedef __int64 int64_t;
 typedef unsigned __int64 uint64_t;
-#ifdef _WIN64
-typedef unsigned __int64 uintptr_t;
-#else
-typedef unsigned long uintptr_t;
-#endif
 
 #elif defined (_AIX)
 #  include <sys/inttypes.h>
@@ -86,8 +60,6 @@
 #  include <stdint.h>
 #endif
 
-#endif
-
 typedef qcms_bool bool;
 #define true 1
 #define false 0
diff --git a/sample-trunc.icc b/sample-trunc.icc
deleted file mode 100644
index 8a41f39..0000000
--- a/sample-trunc.icc
+++ /dev/null
Binary files differ
diff --git a/sum.h b/sum.h
deleted file mode 100644
index 15c949e..0000000
--- a/sum.h
+++ /dev/null
@@ -1,414 +0,0 @@
-/*
-SHA-1 in C
-By Steve Reid <sreid@sea-to-sky.net>
-100% Public Domain
-
------------------
-Modified 7/98 
-By James H. Brown <jbrown@burgoyne.com>
-Still 100% Public Domain
-
-Corrected a problem which generated improper hash values on 16 bit machines
-Routine SHA1Update changed from
-	void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int
-len)
-to
-	void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned
-long len)
-
-The 'len' parameter was declared an int which works fine on 32 bit machines.
-However, on 16 bit machines an int is too small for the shifts being done
-against
-it.  This caused the hash function to generate incorrect values if len was
-greater than 8191 (8K - 1) due to the 'len << 3' on line 3 of SHA1Update().
-
-Since the file IO in main() reads 16K at a time, any file 8K or larger would
-be guaranteed to generate the wrong hash (e.g. Test Vector #3, a million
-"a"s).
-
-I also changed the declaration of variables i & j in SHA1Update to 
-unsigned long from unsigned int for the same reason.
-
-These changes should make no difference to any 32 bit implementations since
-an
-int and a long are the same size in those environments.
-
---
-I also corrected a few compiler warnings generated by Borland C.
-1. Added #include <process.h> for exit() prototype
-2. Removed unused variable 'j' in SHA1Final
-3. Changed exit(0) to return(0) at end of main.
-
-ALL changes I made can be located by searching for comments containing 'JHB'
------------------
-Modified 8/98
-By Steve Reid <sreid@sea-to-sky.net>
-Still 100% public domain
-
-1- Removed #include <process.h> and used return() instead of exit()
-2- Fixed overwriting of finalcount in SHA1Final() (discovered by Chris Hall)
-3- Changed email address from steve@edmweb.com to sreid@sea-to-sky.net
-
------------------
-Modified 4/01
-By Saul Kravitz <Saul.Kravitz@celera.com>
-Still 100% PD
-Modified to run on Compaq Alpha hardware.  
-
------------------
-Modified 07/2002
-By Ralph Giles <giles@artofcode.com>
-Still 100% public domain
-modified for use with stdint types, autoconf
-code cleanup, removed attribution comments
-switched SHA1Final() argument order for consistency
-use SHA1_ prefix for public api
-move public api to sha1.h
-*/
-
-/*
-Test Vectors (from FIPS PUB 180-1)
-"abc"
-  A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
-"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
-  84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
-A million repetitions of "a"
-  34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
-*/
-
-#include <stddef.h>
-#include <stdint.h>
-/* public api for steve reid's public domain SHA-1 implementation */
-/* this file is in the public domain */
-
-#ifndef __SHA1_H
-#define __SHA1_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct {
-    uint32_t state[5];
-    uint32_t count[2];
-    uint8_t  buffer[64];
-} SHA1_CTX;
-
-#define SHA1_DIGEST_SIZE 20
-
-static void SHA1_Init(SHA1_CTX* context);
-static void SHA1_Update(SHA1_CTX* context, const uint8_t* data, const size_t len);
-static void SHA1_Final(SHA1_CTX* context, uint8_t digest[SHA1_DIGEST_SIZE]);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __SHA1_H */
-#define SHA1HANDSOFF
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <stdio.h>
-#include <string.h>
-
-//#include "os_types.h"
-//#include "sha1.h"
-
-static void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64]);
-
-#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
-
-/* blk0() and blk() perform the initial expand. */
-/* I got the idea of expanding during the round function from SSLeay */
-/* FIXME: can we do this in an endian-proof way? */
-#ifdef WORDS_BIGENDIAN
-#define blk0(i) block->l[i]
-#else
-#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
-    |(rol(block->l[i],8)&0x00FF00FF))
-#endif
-#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
-    ^block->l[(i+2)&15]^block->l[i&15],1))
-
-/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
-#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
-#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
-#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
-#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
-#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
-
-
-#ifdef VERBOSE  /* SAK */
-void SHAPrintContext(SHA1_CTX *context, char *msg){
-  printf("%s (%d,%d) %x %x %x %x %x\n",
-	 msg,
-	 context->count[0], context->count[1], 
-	 context->state[0],
-	 context->state[1],
-	 context->state[2],
-	 context->state[3],
-	 context->state[4]);
-}
-#endif /* VERBOSE */
-
-/* Hash a single 512-bit block. This is the core of the algorithm. */
-static void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64])
-{
-    uint32_t a, b, c, d, e;
-    typedef union {
-        uint8_t c[64];
-        uint32_t l[16];
-    } CHAR64LONG16;
-    CHAR64LONG16* block;
-
-#ifdef SHA1HANDSOFF
-    static uint8_t workspace[64];
-    block = (CHAR64LONG16*)workspace;
-    memcpy(block, buffer, 64);
-#else
-    block = (CHAR64LONG16*)buffer;
-#endif
-
-    /* Copy context->state[] to working vars */
-    a = state[0];
-    b = state[1];
-    c = state[2];
-    d = state[3];
-    e = state[4];
-
-    /* 4 rounds of 20 operations each. Loop unrolled. */
-    R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
-    R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
-    R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
-    R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
-    R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
-    R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
-    R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
-    R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
-    R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
-    R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
-    R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
-    R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
-    R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
-    R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
-    R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
-    R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
-    R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
-    R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
-    R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
-    R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
-
-    /* Add the working vars back into context.state[] */
-    state[0] += a;
-    state[1] += b;
-    state[2] += c;
-    state[3] += d;
-    state[4] += e;
-
-    /* Wipe variables */
-    a = b = c = d = e = 0;
-}
-
-
-/* SHA1Init - Initialize new context */
-static void SHA1_Init(SHA1_CTX* context)
-{
-    /* SHA1 initialization constants */
-    context->state[0] = 0x67452301;
-    context->state[1] = 0xEFCDAB89;
-    context->state[2] = 0x98BADCFE;
-    context->state[3] = 0x10325476;
-    context->state[4] = 0xC3D2E1F0;
-    context->count[0] = context->count[1] = 0;
-}
-
-
-/* Run your data through this. */
-static void SHA1_Update(SHA1_CTX* context, const uint8_t* data, const size_t len)
-{
-    size_t i, j;
-
-#ifdef VERBOSE
-    SHAPrintContext(context, "before");
-#endif
-
-    j = (context->count[0] >> 3) & 63;
-    if ((context->count[0] += len << 3) < (len << 3)) context->count[1]++;
-    context->count[1] += (len >> 29);
-    if ((j + len) > 63) {
-        memcpy(&context->buffer[j], data, (i = 64-j));
-        SHA1_Transform(context->state, context->buffer);
-        for ( ; i + 63 < len; i += 64) {
-            SHA1_Transform(context->state, data + i);
-        }
-        j = 0;
-    }
-    else i = 0;
-    memcpy(&context->buffer[j], &data[i], len - i);
-
-#ifdef VERBOSE
-    SHAPrintContext(context, "after ");
-#endif
-}
-
-
-/* Add padding and return the message digest. */
-static void SHA1_Final(SHA1_CTX* context, uint8_t digest[SHA1_DIGEST_SIZE])
-{
-    uint32_t i;
-    uint8_t  finalcount[8];
-
-    for (i = 0; i < 8; i++) {
-        finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
-         >> ((3-(i & 3)) * 8) ) & 255);  /* Endian independent */
-    }
-    SHA1_Update(context, (uint8_t *)"\200", 1);
-    while ((context->count[0] & 504) != 448) {
-        SHA1_Update(context, (uint8_t *)"\0", 1);
-    }
-    SHA1_Update(context, finalcount, 8);  /* Should cause a SHA1_Transform() */
-    for (i = 0; i < SHA1_DIGEST_SIZE; i++) {
-        digest[i] = (uint8_t)
-         ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
-    }
-    
-    /* Wipe variables */
-    i = 0;
-    memset(context->buffer, 0, 64);
-    memset(context->state, 0, 20);
-    memset(context->count, 0, 8);
-    memset(finalcount, 0, 8);	/* SWR */
-
-#ifdef SHA1HANDSOFF  /* make SHA1Transform overwrite its own static vars */
-    SHA1_Transform(context->state, context->buffer);
-#endif
-}
-
-static inline unsigned long sum(void *data, int len)
-{
-    SHA1_CTX sha;
-    uint8_t digest[20];
-
-    SHA1_Init(&sha);
-    SHA1_Update(&sha, data, len);
-
-    SHA1_Final(&sha, digest);
-    return digest[0] << 24 | digest[1] << 16 | digest[2] << 8 | digest[3];
-}
-#if 0
-int main(int argc, char** argv)
-{
-int i, j;
-SHA1_CTX context;
-unsigned char digest[SHA1_DIGEST_SIZE], buffer[16384];
-FILE* file;
-
-    if (argc > 2) {
-        puts("Public domain SHA-1 implementation - by Steve Reid <sreid@sea-to-sky.net>");
-        puts("Modified for 16 bit environments 7/98 - by James H. Brown <jbrown@burgoyne.com>");	/* JHB */
-        puts("Produces the SHA-1 hash of a file, or stdin if no file is specified.");
-        return(0);
-    }
-    if (argc < 2) {
-        file = stdin;
-    }
-    else {
-        if (!(file = fopen(argv[1], "rb"))) {
-            fputs("Unable to open file.", stderr);
-            return(-1);
-        }
-    } 
-    SHA1_Init(&context);
-    while (!feof(file)) {  /* note: what if ferror(file) */
-        i = fread(buffer, 1, 16384, file);
-        SHA1_Update(&context, buffer, i);
-    }
-    SHA1_Final(&context, digest);
-    fclose(file);
-    for (i = 0; i < SHA1_DIGEST_SIZE/4; i++) {
-        for (j = 0; j < 4; j++) {
-            printf("%02X", digest[i*4+j]);
-        }
-        putchar(' ');
-    }
-    putchar('\n');
-    return(0);	/* JHB */
-}
-#endif
-#if 0
-/* self test */
-#define TEST
-#ifdef TEST
-
-static char *test_data[] = {
-    "abc",
-    "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
-    "A million repetitions of 'a'"};
-static char *test_results[] = {
-    "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D",
-    "84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1",
-    "34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F"};
-    
-
-void digest_to_hex(const uint8_t digest[SHA1_DIGEST_SIZE], char *output)
-{
-    int i,j;
-    char *c = output;
-    
-    for (i = 0; i < SHA1_DIGEST_SIZE/4; i++) {
-        for (j = 0; j < 4; j++) {
-            sprintf(c,"%02X", digest[i*4+j]);
-            c += 2;
-        }
-        sprintf(c, " ");
-        c += 1;
-    }
-    *(c - 1) = '\0';
-}
-    
-int main(int argc, char** argv)
-{
-    int k;
-    SHA1_CTX context;
-    uint8_t digest[20];
-    char output[80];
-
-    fprintf(stdout, "verifying SHA-1 implementation... ");
-    
-    for (k = 0; k < 2; k++){ 
-        SHA1_Init(&context);
-        SHA1_Update(&context, (uint8_t*)test_data[k], strlen(test_data[k]));
-        SHA1_Final(&context, digest);
-	digest_to_hex(digest, output);
-
-        if (strcmp(output, test_results[k])) {
-            fprintf(stdout, "FAIL\n");
-            fprintf(stderr,"* hash of \"%s\" incorrect:\n", test_data[k]);
-            fprintf(stderr,"\t%s returned\n", output);
-            fprintf(stderr,"\t%s is correct\n", test_results[k]);
-            return (1);
-        }    
-    }
-    /* million 'a' vector we feed separately */
-    SHA1_Init(&context);
-    for (k = 0; k < 1000000; k++)
-        SHA1_Update(&context, (uint8_t*)"a", 1);
-    SHA1_Final(&context, digest);
-    digest_to_hex(digest, output);
-    if (strcmp(output, test_results[2])) {
-        fprintf(stdout, "FAIL\n");
-        fprintf(stderr,"* hash of \"%s\" incorrect:\n", test_data[2]);
-        fprintf(stderr,"\t%s returned\n", output);
-        fprintf(stderr,"\t%s is correct\n", test_results[2]);
-        return (1);
-    }
-
-    /* success */
-    fprintf(stdout, "ok\n");
-    return(0);
-}
-#endif /* TEST */
-#endif
diff --git a/test-invalid.c b/test-invalid.c
deleted file mode 100644
index 7a1b9a3..0000000
--- a/test-invalid.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include <stdlib.h>
-#include <assert.h>
-#include "qcms.h"
-
-
-int main()
-{
-	assert(!qcms_profile_from_path("bad-profiles/rand.icc"));
-	assert(!qcms_profile_from_path("bad-profiles/curve.icc"));
-	return 0;
-}
diff --git a/test-transform.c b/test-transform.c
deleted file mode 100644
index 611cabc..0000000
--- a/test-transform.c
+++ /dev/null
@@ -1,37 +0,0 @@
-#include <stdlib.h>
-#include <time.h>
-#include "sum.h"
-#include "lcms.h"
-#include "qcms.h"
-
-int main(int argc, char **argv)
-{
-	char *input_path = argv[1];
-	char *output_path = argv[2];
-
-	qcms_profile *input_profile, *output_profile;
-	qcms_transform *transform;
-#define LENGTH (256*256*256)
-	static unsigned char src[LENGTH*3];
-	static unsigned char qoutput[LENGTH*3];
-
-	int i,j,k,l=0;
-	for (i=0; i<256; i++) {
-		for (j=0; j<256; j++) {
-			for (k=0; k<256; k++) {
-				src[l++] = i;
-				src[l++] = j;
-				src[l++] = k;
-			}
-		}
-	}
-	input_profile = qcms_profile_from_path(input_path);
-	output_profile = qcms_profile_from_path(output_path);
-	qcms_profile_precache_output_transform(output_profile);
-
-	transform = qcms_transform_create(input_profile, QCMS_DATA_RGB_8, output_profile, QCMS_DATA_RGB_8, QCMS_INTENT_PERCEPTUAL);
-	qcms_transform_data(transform, src, qoutput, LENGTH);
-	qcms_profile_release(input_profile);
-	qcms_profile_release(output_profile);
-	return 0;
-}
diff --git a/test.c b/test.c
deleted file mode 100644
index f9c6955..0000000
--- a/test.c
+++ /dev/null
@@ -1,51 +0,0 @@
-#include <stdlib.h>
-#include "qcms.h"
-#include "sum.h"
-
-int main()
-{
-	unsigned char srct[3] = { 221, 79, 129};
-	unsigned char outt[3];
-#define LENGTH 256*256*256
-	static unsigned char src[LENGTH*3];
-	static unsigned char output[LENGTH*3];
-	int i,j,k,l=0;
-	qcms_profile *input_profile, *output_profile;
-	qcms_transform *transform;
-	input_profile = qcms_profile_from_path("lcms_test/input.icc");
-	output_profile = qcms_profile_from_path("lcms_test/output.icc");
-
-	transform = qcms_transform_create(input_profile, QCMS_DATA_RGB_8, output_profile, QCMS_DATA_RGB_8, QCMS_INTENT_PERCEPTUAL);
-	//transform = qcms_create_transform(output_profile, input_profile);
-
-	for (i=0; i<256; i++) {
-		for (j=0; j<256; j++) {
-			for (k=0; k<256; k++) {
-				src[l++] = i;
-				src[l++] = j;
-				src[l++] = k;
-			}
-		}
-	}
-
-	qcms_transform_data(transform, srct, outt, 1);
-
-	qcms_transform_data(transform, src, output, LENGTH);
-
-	for (i=256*40*3; i<30+256*40*3; i+=3) {
-	printf("(%d %d %d) -> output (%d %d %d)\n", src[i], src[i+1], src[i+2],
-			output[i],
-			output[i+1],
-			output[i+2]);
-	}
-
-	qcms_transform_release(transform);
-	qcms_profile_release(input_profile);
-	qcms_profile_release(output_profile);
-
-	if (sum(output, LENGTH*3) != 0xca89c51c) {
-		printf("DATA CHANGED: %lx\n", sum(output, LENGTH*3));
-		abort();
-	}
-	return 0;
-}
diff --git a/transform-sse1.c b/transform-sse1.c
deleted file mode 100644
index ecca4cc..0000000
--- a/transform-sse1.c
+++ /dev/null
@@ -1,275 +0,0 @@
-//  qcms
-//  Copyright (C) 2009 Mozilla Foundation
-//  Copyright (C) 2010 Steve Snyder
-//
-// 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 <xmmintrin.h>
-
-#include "qcmsint.h"
-
-/* pre-shuffled: just load these into XMM reg instead of load-scalar/shufps sequence */
-#define FLOATSCALE  (float)(PRECACHE_OUTPUT_SIZE)
-#define CLAMPMAXVAL ( ((float) (PRECACHE_OUTPUT_SIZE - 1)) / PRECACHE_OUTPUT_SIZE )
-static const ALIGN float floatScaleX4[4] =
-    { FLOATSCALE, FLOATSCALE, FLOATSCALE, FLOATSCALE};
-static const ALIGN float clampMaxValueX4[4] =
-    { CLAMPMAXVAL, CLAMPMAXVAL, CLAMPMAXVAL, CLAMPMAXVAL};
-
-void qcms_transform_data_rgb_out_lut_sse1(qcms_transform *transform,
-                                          unsigned char *src,
-                                          unsigned char *dest,
-                                          size_t length)
-{
-    unsigned int i;
-    float (*mat)[4] = transform->matrix;
-    char input_back[32];
-    /* Ensure we have a buffer that's 16 byte aligned regardless of the original
-     * stack alignment. We can't use __attribute__((aligned(16))) or __declspec(align(32))
-     * because they don't work on stack variables. gcc 4.4 does do the right thing
-     * on x86 but that's too new for us right now. For more info: gcc bug #16660 */
-    float const * input = (float*)(((uintptr_t)&input_back[16]) & ~0xf);
-    /* share input and output locations to save having to keep the
-     * locations in separate registers */
-    uint32_t const * output = (uint32_t*)input;
-
-    /* deref *transform now to avoid it in loop */
-    const float *igtbl_r = transform->input_gamma_table_r;
-    const float *igtbl_g = transform->input_gamma_table_g;
-    const float *igtbl_b = transform->input_gamma_table_b;
-
-    /* deref *transform now to avoid it in loop */
-    const uint8_t *otdata_r = &transform->output_table_r->data[0];
-    const uint8_t *otdata_g = &transform->output_table_g->data[0];
-    const uint8_t *otdata_b = &transform->output_table_b->data[0];
-
-    /* input matrix values never change */
-    const __m128 mat0  = _mm_load_ps(mat[0]);
-    const __m128 mat1  = _mm_load_ps(mat[1]);
-    const __m128 mat2  = _mm_load_ps(mat[2]);
-
-    /* these values don't change, either */
-    const __m128 max   = _mm_load_ps(clampMaxValueX4);
-    const __m128 min   = _mm_setzero_ps();
-    const __m128 scale = _mm_load_ps(floatScaleX4);
-
-    /* working variables */
-    __m128 vec_r, vec_g, vec_b, result;
-
-    /* CYA */
-    if (!length)
-        return;
-
-    /* one pixel is handled outside of the loop */
-    length--;
-
-    /* setup for transforming 1st pixel */
-    vec_r = _mm_load_ss(&igtbl_r[src[0]]);
-    vec_g = _mm_load_ss(&igtbl_g[src[1]]);
-    vec_b = _mm_load_ss(&igtbl_b[src[2]]);
-    src += 3;
-
-    /* transform all but final pixel */
-
-    for (i=0; i<length; i++)
-    {
-        /* position values from gamma tables */
-        vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
-        vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
-        vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);
-
-        /* gamma * matrix */
-        vec_r = _mm_mul_ps(vec_r, mat0);
-        vec_g = _mm_mul_ps(vec_g, mat1);
-        vec_b = _mm_mul_ps(vec_b, mat2);
-
-        /* crunch, crunch, crunch */
-        vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
-        vec_r  = _mm_max_ps(min, vec_r);
-        vec_r  = _mm_min_ps(max, vec_r);
-        result = _mm_mul_ps(vec_r, scale);
-
-        /* store calc'd output tables indices */
-        *((__m64 *)&output[0]) = _mm_cvtps_pi32(result);
-        result = _mm_movehl_ps(result, result);
-        *((__m64 *)&output[2]) = _mm_cvtps_pi32(result) ;
-
-        /* load for next loop while store completes */
-        vec_r = _mm_load_ss(&igtbl_r[src[0]]);
-        vec_g = _mm_load_ss(&igtbl_g[src[1]]);
-        vec_b = _mm_load_ss(&igtbl_b[src[2]]);
-        src += 3;
-
-        /* use calc'd indices to output RGB values */
-        dest[OUTPUT_R_INDEX] = otdata_r[output[0]];
-        dest[OUTPUT_G_INDEX] = otdata_g[output[1]];
-        dest[OUTPUT_B_INDEX] = otdata_b[output[2]];
-        dest += RGB_OUTPUT_COMPONENTS;
-    }
-
-    /* handle final (maybe only) pixel */
-
-    vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
-    vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
-    vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);
-
-    vec_r = _mm_mul_ps(vec_r, mat0);
-    vec_g = _mm_mul_ps(vec_g, mat1);
-    vec_b = _mm_mul_ps(vec_b, mat2);
-
-    vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
-    vec_r  = _mm_max_ps(min, vec_r);
-    vec_r  = _mm_min_ps(max, vec_r);
-    result = _mm_mul_ps(vec_r, scale);
-
-    *((__m64 *)&output[0]) = _mm_cvtps_pi32(result);
-    result = _mm_movehl_ps(result, result);
-    *((__m64 *)&output[2]) = _mm_cvtps_pi32(result);
-
-    dest[OUTPUT_R_INDEX] = otdata_r[output[0]];
-    dest[OUTPUT_G_INDEX] = otdata_g[output[1]];
-    dest[OUTPUT_B_INDEX] = otdata_b[output[2]];
-
-    _mm_empty();
-}
-
-void qcms_transform_data_rgba_out_lut_sse1(qcms_transform *transform,
-                                           unsigned char *src,
-                                           unsigned char *dest,
-                                           size_t length)
-{
-    unsigned int i;
-    float (*mat)[4] = transform->matrix;
-    char input_back[32];
-    /* Ensure we have a buffer that's 16 byte aligned regardless of the original
-     * stack alignment. We can't use __attribute__((aligned(16))) or __declspec(align(32))
-     * because they don't work on stack variables. gcc 4.4 does do the right thing
-     * on x86 but that's too new for us right now. For more info: gcc bug #16660 */
-    float const * input = (float*)(((uintptr_t)&input_back[16]) & ~0xf);
-    /* share input and output locations to save having to keep the
-     * locations in separate registers */
-    uint32_t const * output = (uint32_t*)input;
-
-    /* deref *transform now to avoid it in loop */
-    const float *igtbl_r = transform->input_gamma_table_r;
-    const float *igtbl_g = transform->input_gamma_table_g;
-    const float *igtbl_b = transform->input_gamma_table_b;
-
-    /* deref *transform now to avoid it in loop */
-    const uint8_t *otdata_r = &transform->output_table_r->data[0];
-    const uint8_t *otdata_g = &transform->output_table_g->data[0];
-    const uint8_t *otdata_b = &transform->output_table_b->data[0];
-
-    /* input matrix values never change */
-    const __m128 mat0  = _mm_load_ps(mat[0]);
-    const __m128 mat1  = _mm_load_ps(mat[1]);
-    const __m128 mat2  = _mm_load_ps(mat[2]);
-
-    /* these values don't change, either */
-    const __m128 max   = _mm_load_ps(clampMaxValueX4);
-    const __m128 min   = _mm_setzero_ps();
-    const __m128 scale = _mm_load_ps(floatScaleX4);
-
-    /* working variables */
-    __m128 vec_r, vec_g, vec_b, result;
-    unsigned char alpha;
-
-    /* CYA */
-    if (!length)
-        return;
-
-    /* one pixel is handled outside of the loop */
-    length--;
-
-    /* setup for transforming 1st pixel */
-    vec_r = _mm_load_ss(&igtbl_r[src[0]]);
-    vec_g = _mm_load_ss(&igtbl_g[src[1]]);
-    vec_b = _mm_load_ss(&igtbl_b[src[2]]);
-    alpha = src[3];
-    src += 4;
-
-    /* transform all but final pixel */
-
-    for (i=0; i<length; i++)
-    {
-        /* position values from gamma tables */
-        vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
-        vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
-        vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);
-
-        /* gamma * matrix */
-        vec_r = _mm_mul_ps(vec_r, mat0);
-        vec_g = _mm_mul_ps(vec_g, mat1);
-        vec_b = _mm_mul_ps(vec_b, mat2);
-
-        /* store alpha for this pixel; load alpha for next */
-        dest[OUTPUT_A_INDEX] = alpha;
-        alpha   = src[3];
-
-        /* crunch, crunch, crunch */
-        vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
-        vec_r  = _mm_max_ps(min, vec_r);
-        vec_r  = _mm_min_ps(max, vec_r);
-        result = _mm_mul_ps(vec_r, scale);
-
-        /* store calc'd output tables indices */
-        *((__m64 *)&output[0]) = _mm_cvtps_pi32(result);
-        result = _mm_movehl_ps(result, result);
-        *((__m64 *)&output[2]) = _mm_cvtps_pi32(result);
-
-        /* load gamma values for next loop while store completes */
-        vec_r = _mm_load_ss(&igtbl_r[src[0]]);
-        vec_g = _mm_load_ss(&igtbl_g[src[1]]);
-        vec_b = _mm_load_ss(&igtbl_b[src[2]]);
-        src += 4;
-
-        /* use calc'd indices to output RGB values */
-        dest[OUTPUT_R_INDEX] = otdata_r[output[0]];
-        dest[OUTPUT_G_INDEX] = otdata_g[output[1]];
-        dest[OUTPUT_B_INDEX] = otdata_b[output[2]];
-        dest += 4;
-    }
-
-    /* handle final (maybe only) pixel */
-
-    vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
-    vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
-    vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);
-
-    vec_r = _mm_mul_ps(vec_r, mat0);
-    vec_g = _mm_mul_ps(vec_g, mat1);
-    vec_b = _mm_mul_ps(vec_b, mat2);
-
-    dest[OUTPUT_A_INDEX] = alpha;
-
-    vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
-    vec_r  = _mm_max_ps(min, vec_r);
-    vec_r  = _mm_min_ps(max, vec_r);
-    result = _mm_mul_ps(vec_r, scale);
-
-    *((__m64 *)&output[0]) = _mm_cvtps_pi32(result);
-    result = _mm_movehl_ps(result, result);
-    *((__m64 *)&output[2]) = _mm_cvtps_pi32(result);
-
-    dest[OUTPUT_R_INDEX] = otdata_r[output[0]];
-    dest[OUTPUT_G_INDEX] = otdata_g[output[1]];
-    dest[OUTPUT_B_INDEX] = otdata_b[output[2]];
-
-    _mm_empty();
-}
diff --git a/transform-sse2.c b/transform-sse2.c
index 7c814e4..c06db69 100644
--- a/transform-sse2.c
+++ b/transform-sse2.c
@@ -1,33 +1,33 @@
 //  qcms
 //  Copyright (C) 2009 Mozilla Foundation
-//  Copyright (C) 2010 Steve Snyder
+//  Copyright (C) 2015 Intel Corporation
 //
-// 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 
+// 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 
+// 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 
+// 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 <emmintrin.h>
 
 #include "qcmsint.h"
 
 /* pre-shuffled: just load these into XMM reg instead of load-scalar/shufps sequence */
-#define FLOATSCALE  (float)(PRECACHE_OUTPUT_SIZE)
-#define CLAMPMAXVAL ( ((float) (PRECACHE_OUTPUT_SIZE - 1)) / PRECACHE_OUTPUT_SIZE )
+#define FLOATSCALE  (float)(PRECACHE_OUTPUT_SIZE - 1)
+#define CLAMPMAXVAL 1.0f
+
 static const ALIGN float floatScaleX4[4] =
     { FLOATSCALE, FLOATSCALE, FLOATSCALE, FLOATSCALE};
 static const ALIGN float clampMaxValueX4[4] =
@@ -36,7 +36,8 @@
 void qcms_transform_data_rgb_out_lut_sse2(qcms_transform *transform,
                                           unsigned char *src,
                                           unsigned char *dest,
-                                          size_t length)
+                                          size_t length,
+                                          qcms_format_type output_format)
 {
     unsigned int i;
     float (*mat)[4] = transform->matrix;
@@ -72,6 +73,8 @@
 
     /* working variables */
     __m128 vec_r, vec_g, vec_b, result;
+    const int r_out = output_format.r;
+    const int b_out = output_format.b;
 
     /* CYA */
     if (!length)
@@ -101,7 +104,7 @@
         vec_b = _mm_mul_ps(vec_b, mat2);
 
         /* crunch, crunch, crunch */
-        vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
+        vec_r  = _mm_add_ps(vec_g, _mm_add_ps(vec_r, vec_b));
         vec_r  = _mm_max_ps(min, vec_r);
         vec_r  = _mm_min_ps(max, vec_r);
         result = _mm_mul_ps(vec_r, scale);
@@ -116,10 +119,10 @@
         src += 3;
 
         /* use calc'd indices to output RGB values */
-        dest[OUTPUT_R_INDEX] = otdata_r[output[0]];
-        dest[OUTPUT_G_INDEX] = otdata_g[output[1]];
-        dest[OUTPUT_B_INDEX] = otdata_b[output[2]];
-        dest += RGB_OUTPUT_COMPONENTS;
+        dest[r_out] = otdata_r[output[0]];
+        dest[1]     = otdata_g[output[1]];
+        dest[b_out] = otdata_b[output[2]];
+        dest += 3;
     }
 
     /* handle final (maybe only) pixel */
@@ -132,22 +135,23 @@
     vec_g = _mm_mul_ps(vec_g, mat1);
     vec_b = _mm_mul_ps(vec_b, mat2);
 
-    vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
+    vec_r  = _mm_add_ps(vec_g, _mm_add_ps(vec_r, vec_b));
     vec_r  = _mm_max_ps(min, vec_r);
     vec_r  = _mm_min_ps(max, vec_r);
     result = _mm_mul_ps(vec_r, scale);
 
     _mm_store_si128((__m128i*)output, _mm_cvtps_epi32(result));
 
-    dest[OUTPUT_R_INDEX] = otdata_r[output[0]];
-    dest[OUTPUT_G_INDEX] = otdata_g[output[1]];
-    dest[OUTPUT_B_INDEX] = otdata_b[output[2]];
+    dest[r_out] = otdata_r[output[0]];
+    dest[1]     = otdata_g[output[1]];
+    dest[b_out] = otdata_b[output[2]];
 }
 
 void qcms_transform_data_rgba_out_lut_sse2(qcms_transform *transform,
                                            unsigned char *src,
                                            unsigned char *dest,
-                                           size_t length)
+                                           size_t length,
+                                           qcms_format_type output_format)
 {
     unsigned int i;
     float (*mat)[4] = transform->matrix;
@@ -183,6 +187,8 @@
 
     /* working variables */
     __m128 vec_r, vec_g, vec_b, result;
+    const int r_out = output_format.r;
+    const int b_out = output_format.b;
     unsigned char alpha;
 
     /* CYA */
@@ -214,11 +220,11 @@
         vec_b = _mm_mul_ps(vec_b, mat2);
 
         /* store alpha for this pixel; load alpha for next */
-        dest[OUTPUT_A_INDEX] = alpha;
+        dest[3] = alpha;
         alpha   = src[3];
 
         /* crunch, crunch, crunch */
-        vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
+        vec_r  = _mm_add_ps(vec_g, _mm_add_ps(vec_r, vec_b));
         vec_r  = _mm_max_ps(min, vec_r);
         vec_r  = _mm_min_ps(max, vec_r);
         result = _mm_mul_ps(vec_r, scale);
@@ -233,10 +239,10 @@
         src += 4;
 
         /* use calc'd indices to output RGB values */
-        dest[OUTPUT_R_INDEX] = otdata_r[output[0]];
-        dest[OUTPUT_G_INDEX] = otdata_g[output[1]];
-        dest[OUTPUT_B_INDEX] = otdata_b[output[2]];
-        dest += RGBA_OUTPUT_COMPONENTS;
+        dest[r_out] = otdata_r[output[0]];
+        dest[1]     = otdata_g[output[1]];
+        dest[b_out] = otdata_b[output[2]];
+        dest += 4;
     }
 
     /* handle final (maybe only) pixel */
@@ -249,18 +255,204 @@
     vec_g = _mm_mul_ps(vec_g, mat1);
     vec_b = _mm_mul_ps(vec_b, mat2);
 
-    dest[OUTPUT_A_INDEX] = alpha;
+    dest[3] = alpha;
 
-    vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
+    vec_r  = _mm_add_ps(vec_g, _mm_add_ps(vec_r, vec_b));
     vec_r  = _mm_max_ps(min, vec_r);
     vec_r  = _mm_min_ps(max, vec_r);
     result = _mm_mul_ps(vec_r, scale);
 
     _mm_store_si128((__m128i*)output, _mm_cvtps_epi32(result));
 
-    dest[OUTPUT_R_INDEX] = otdata_r[output[0]];
-    dest[OUTPUT_G_INDEX] = otdata_g[output[1]];
-    dest[OUTPUT_B_INDEX] = otdata_b[output[2]];
+    dest[r_out] = otdata_r[output[0]];
+    dest[1]     = otdata_g[output[1]];
+    dest[b_out] = otdata_b[output[2]];
 }
 
+static inline __m128i __mm_swizzle_epi32(__m128i value, int bgra)
+{
+    return bgra ? _mm_shuffle_epi32(value, _MM_SHUFFLE(0, 1, 2, 3)) :
+                  _mm_shuffle_epi32(value, _MM_SHUFFLE(0, 3, 2, 1)) ;
+}
 
+void qcms_transform_data_tetra_clut_rgba_sse2(qcms_transform *transform,
+                                              unsigned char *src,
+                                              unsigned char *dest,
+                                              size_t length,
+                                              qcms_format_type output_format)
+{
+    const int bgra = output_format.r;
+
+    size_t i;
+
+    const int xy_len_3 = 3 * 1;
+    const int x_len_3 = 3 * transform->grid_size;
+    const int len_3 = x_len_3 * transform->grid_size;
+
+    const __m128 __255 = _mm_set1_ps(255.0f);
+    const __m128 __one = _mm_set1_ps(1.0f);
+    const __m128 __000 = _mm_setzero_ps();
+
+    const float* r_table = transform->r_clut;
+    const float* g_table = transform->g_clut;
+    const float* b_table = transform->b_clut;
+
+    int i3, i2, i1, i0;
+
+    __m128 c3;
+    __m128 c2;
+    __m128 c1;
+    __m128 c0;
+
+    if (!(transform->transform_flags & TRANSFORM_FLAG_CLUT_CACHE))
+        qcms_transform_build_clut_cache(transform);
+
+    for (i = 0; i < length; ++i) {
+        unsigned char in_r = *src++;
+        unsigned char in_g = *src++;
+        unsigned char in_b = *src++;
+
+        // initialize the output result with the alpha channel only
+
+        __m128i result = _mm_setr_epi32(*src++, 0, 0, 0);
+
+        // get the input point r.xyz relative to the subcube origin
+
+        float rx = transform->r_cache[in_r];
+        float ry = transform->r_cache[in_g];
+        float rz = transform->r_cache[in_b];
+
+        // load and LUT scale the subcube maximum vertex
+
+        int xn = transform->ceil_cache[in_r] * len_3;
+        int yn = transform->ceil_cache[in_g] * x_len_3;
+        int zn = transform->ceil_cache[in_b] * xy_len_3;
+
+        // load and LUT scale the subcube origin vertex
+
+        int x0 = transform->floor_cache[in_r] * len_3;
+        int y0 = transform->floor_cache[in_g] * x_len_3;
+        int z0 = transform->floor_cache[in_b] * xy_len_3;
+
+        // tetrahedral interpolate the input color r.xyz
+
+#define TETRA_LOOKUP_CLUT(i3, i2, i1, i0) \
+        c0 = _mm_set_ps(b_table[i0], g_table[i0], r_table[i0], 0.f), \
+        c1 = _mm_set_ps(b_table[i1], g_table[i1], r_table[i1], 0.f), \
+        c2 = _mm_set_ps(b_table[i2], g_table[i2], r_table[i2], 0.f), \
+        c3 = _mm_set_ps(b_table[i3], g_table[i3], r_table[i3], 0.f)
+
+        i0 = x0 + y0 + z0;
+
+        if (rx >= ry) {
+
+            if (ry >= rz) {         // rx >= ry && ry >= rz
+
+                i3 = yn + (i1 = xn);
+                i1 += i0 - x0;
+                i2 = i3 + z0;
+                i3 += zn;
+
+                TETRA_LOOKUP_CLUT(i3, i2, i1, i0);
+
+                c3 = _mm_sub_ps(c3, c2);
+                c2 = _mm_sub_ps(c2, c1);
+                c1 = _mm_sub_ps(c1, c0);
+
+            } else if (rx >= rz) {  // rx >= rz && rz >= ry
+
+                i3 = zn + (i1 = xn);
+                i1 += i0 - x0;
+                i2 = i3 + yn;
+                i3 += y0;
+
+                TETRA_LOOKUP_CLUT(i3, i2, i1, i0);
+
+                c2 = _mm_sub_ps(c2, c3);
+                c3 = _mm_sub_ps(c3, c1);
+                c1 = _mm_sub_ps(c1, c0);
+
+            } else {                // rz > rx && rx >= ry
+
+                i2 = xn + (i3 = zn);
+                i3 += i0 - z0;
+                i1 = i2 + y0;
+                i2 += yn;
+
+                TETRA_LOOKUP_CLUT(i3, i2, i1, i0);
+
+                c2 = _mm_sub_ps(c2, c1);
+                c1 = _mm_sub_ps(c1, c3);
+                c3 = _mm_sub_ps(c3, c0);
+            }
+        } else {
+
+            if (rx >= rz) {         // ry > rx && rx >= rz
+
+                i3 = xn + (i2 = yn);
+                i2 += i0 - y0;
+                i1 = i3 + z0;
+                i3 += zn;
+
+                TETRA_LOOKUP_CLUT(i3, i2, i1, i0);
+
+                c3 = _mm_sub_ps(c3, c1);
+                c1 = _mm_sub_ps(c1, c2);
+                c2 = _mm_sub_ps(c2, c0);
+
+            } else if (ry >= rz) {  // ry >= rz && rz > rx
+
+                i3 = zn + (i2 = yn);
+                i2 += i0 - y0;
+                i1 = i3 + xn;
+                i3 += x0;
+
+                TETRA_LOOKUP_CLUT(i3, i2, i1, i0);
+
+                c1 = _mm_sub_ps(c1, c3);
+                c3 = _mm_sub_ps(c3, c2);
+                c2 = _mm_sub_ps(c2, c0);
+
+            } else {                // rz > ry && ry > rx
+
+                i2 = yn + (i3 = zn);
+                i3 += i0 - z0;
+                i1 = i2 + xn;
+                i2 += x0;
+
+                TETRA_LOOKUP_CLUT(i3, i2, i1, i0);
+
+                c1 = _mm_sub_ps(c1, c2);
+                c2 = _mm_sub_ps(c2, c3);
+                c3 = _mm_sub_ps(c3, c0);
+            }
+        }
+
+        // output.xyz = column_matrix(c1, c2, c3) x r.xyz + c0.xyz
+
+        c0 = _mm_add_ps(c0, _mm_mul_ps(c1, _mm_set1_ps(rx)));
+        c0 = _mm_add_ps(c0, _mm_mul_ps(c2, _mm_set1_ps(ry)));
+        c0 = _mm_add_ps(c0, _mm_mul_ps(c3, _mm_set1_ps(rz)));
+
+        // clamp to [0.0..1.0], then scale by 255
+
+        c0 = _mm_max_ps(c0, __000);
+        c0 = _mm_min_ps(c0, __one);
+        c0 = _mm_mul_ps(c0, __255);
+
+        // int(c0) with float rounding, add alpha
+
+        result = _mm_add_epi32(result, _mm_cvtps_epi32(c0));
+
+        // swizzle and repack in result low bytes
+
+        result = __mm_swizzle_epi32(result, bgra);
+        result = _mm_packus_epi16(result, result);
+        result = _mm_packus_epi16(result, result);
+
+        // store into uint32_t* pixel destination
+
+        *(uint32_t *)dest = _mm_cvtsi128_si32(result);
+        dest += 4;
+    }
+}
diff --git a/transform.c b/transform.c
index 51ab83f..17c6555 100644
--- a/transform.c
+++ b/transform.c
@@ -3,22 +3,22 @@
 //  Copyright (C) 2009 Mozilla Corporation
 //  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 
+// 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 
+// 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 
+// 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 <stdlib.h>
@@ -27,6 +27,7 @@
 #include <string.h> //memcpy
 #include "qcmsint.h"
 #include "chain.h"
+#include "halffloat.h"
 #include "matrix.h"
 #include "transform_util.h"
 
@@ -181,32 +182,44 @@
 static struct matrix
 adaption_matrix(struct CIE_XYZ source_illumination, struct CIE_XYZ target_illumination)
 {
+#if defined (_MSC_VER)
+#pragma warning(push)
+/* Disable double to float truncation warning 4305 */
+#pragma warning(disable:4305)
+#endif
 	struct matrix lam_rigg = {{ // Bradford matrix
 	                         {  0.8951,  0.2664, -0.1614 },
 	                         { -0.7502,  1.7135,  0.0367 },
-	                         {  0.0389, -0.0685,  1.0296 }
-	                         }};
+	                         {  0.0389, -0.0685,  1.0296 }},
+											 		 false};
+#if defined (_MSC_VER)
+/* Restore warnings */
+#pragma warning(pop)
+#endif
 	return compute_chromatic_adaption(source_illumination, target_illumination, lam_rigg);
 }
 
 /* from lcms: cmsAdaptMatrixToD50 */
-static struct matrix adapt_matrix_to_D50(struct matrix r, qcms_CIE_xyY source_white_pt)
+static struct matrix adapt_matrix_to_D50(struct matrix r, qcms_CIE_xyY source_white_point)
 {
-	struct CIE_XYZ Dn;
+	struct CIE_XYZ DNN_XYZ;
 	struct matrix Bradford;
 
-	if (source_white_pt.y == 0.0)
+	if (source_white_point.y == 0.0)
 		return matrix_invalid();
 
-	Dn = xyY2XYZ(source_white_pt);
+	DNN_XYZ = xyY2XYZ(source_white_point);
 
-	Bradford = adaption_matrix(Dn, D50_XYZ);
+	Bradford = adaption_matrix(DNN_XYZ, D50_XYZ);
+
 	return matrix_multiply(Bradford, r);
 }
 
 qcms_bool set_rgb_colorants(qcms_profile *profile, qcms_CIE_xyY white_point, qcms_CIE_xyYTRIPLE primaries)
 {
+	struct CIE_XYZ source_white;
 	struct matrix colorants;
+
 	colorants = build_RGB_to_XYZ_transfer_matrix(white_point, primaries);
 	colorants = adapt_matrix_to_D50(colorants, white_point);
 
@@ -226,12 +239,21 @@
 	profile->blueColorant.Y = double_to_s15Fixed16Number(colorants.m[1][2]);
 	profile->blueColorant.Z = double_to_s15Fixed16Number(colorants.m[2][2]);
 
+	/* Store the media white point */
+	source_white = xyY2XYZ(white_point);
+	profile->mediaWhitePoint.X = double_to_s15Fixed16Number(source_white.X);
+	profile->mediaWhitePoint.Y = double_to_s15Fixed16Number(source_white.Y);
+	profile->mediaWhitePoint.Z = double_to_s15Fixed16Number(source_white.Z);
+
 	return true;
 }
 
 #if 0
-static void qcms_transform_data_rgb_out_pow(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+static void qcms_transform_data_rgb_out_pow(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	int i;
 	float (*mat)[4] = transform->matrix;
 	for (i=0; i<length; i++) {
@@ -251,16 +273,19 @@
 		float out_device_g = pow(out_linear_g, transform->out_gamma_g);
 		float out_device_b = pow(out_linear_b, transform->out_gamma_b);
 
-		dest[OUTPUT_R_INDEX] = clamp_u8(255*out_device_r);
-		dest[OUTPUT_G_INDEX] = clamp_u8(255*out_device_g);
-		dest[OUTPUT_B_INDEX] = clamp_u8(255*out_device_b);
-		dest += RGB_OUTPUT_COMPONENTS;
+		dest[r_out] = clamp_u8(out_device_r*255);
+		dest[1]     = clamp_u8(out_device_g*255);
+		dest[b_out] = clamp_u8(out_device_b*255);
+		dest += 3;
 	}
 }
 #endif
 
-static void qcms_transform_data_gray_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+static void qcms_transform_data_gray_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	for (i = 0; i < length; i++) {
 		float out_device_r, out_device_g, out_device_b;
@@ -268,14 +293,14 @@
 
 		float linear = transform->input_gamma_table_gray[device];
 
-                out_device_r = lut_interp_linear(linear, transform->output_gamma_lut_r, transform->output_gamma_lut_r_length);
+		out_device_r = lut_interp_linear(linear, transform->output_gamma_lut_r, transform->output_gamma_lut_r_length);
 		out_device_g = lut_interp_linear(linear, transform->output_gamma_lut_g, transform->output_gamma_lut_g_length);
 		out_device_b = lut_interp_linear(linear, transform->output_gamma_lut_b, transform->output_gamma_lut_b_length);
 
-		dest[OUTPUT_R_INDEX] = clamp_u8(out_device_r*255);
-		dest[OUTPUT_G_INDEX] = clamp_u8(out_device_g*255);
-		dest[OUTPUT_B_INDEX] = clamp_u8(out_device_b*255);
-		dest += RGB_OUTPUT_COMPONENTS;
+		dest[r_out] = clamp_u8(out_device_r*255);
+		dest[1]     = clamp_u8(out_device_g*255);
+		dest[b_out] = clamp_u8(out_device_b*255);
+		dest += 3;
 	}
 }
 
@@ -285,8 +310,11 @@
 	See: ftp://ftp.alvyray.com/Acrobat/17_Nonln.pdf
 */
 
-static void qcms_transform_data_graya_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+static void qcms_transform_data_graya_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	for (i = 0; i < length; i++) {
 		float out_device_r, out_device_g, out_device_b;
@@ -295,21 +323,24 @@
 
 		float linear = transform->input_gamma_table_gray[device];
 
-                out_device_r = lut_interp_linear(linear, transform->output_gamma_lut_r, transform->output_gamma_lut_r_length);
+		out_device_r = lut_interp_linear(linear, transform->output_gamma_lut_r, transform->output_gamma_lut_r_length);
 		out_device_g = lut_interp_linear(linear, transform->output_gamma_lut_g, transform->output_gamma_lut_g_length);
 		out_device_b = lut_interp_linear(linear, transform->output_gamma_lut_b, transform->output_gamma_lut_b_length);
 
-		dest[OUTPUT_R_INDEX] = clamp_u8(out_device_r*255);
-		dest[OUTPUT_G_INDEX] = clamp_u8(out_device_g*255);
-		dest[OUTPUT_B_INDEX] = clamp_u8(out_device_b*255);
-		dest[OUTPUT_A_INDEX] = alpha;
-		dest += RGBA_OUTPUT_COMPONENTS;
+		dest[r_out] = clamp_u8(out_device_r*255);
+		dest[1]     = clamp_u8(out_device_g*255);
+		dest[b_out] = clamp_u8(out_device_b*255);
+		dest[3]     = alpha;
+		dest += 4;
 	}
 }
 
 
-static void qcms_transform_data_gray_out_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+static void qcms_transform_data_gray_out_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	for (i = 0; i < length; i++) {
 		unsigned char device = *src++;
@@ -320,15 +351,19 @@
 		/* we could round here... */
 		gray = linear * PRECACHE_OUTPUT_MAX;
 
-		dest[OUTPUT_R_INDEX] = transform->output_table_r->data[gray];
-		dest[OUTPUT_G_INDEX] = transform->output_table_g->data[gray];
-		dest[OUTPUT_B_INDEX] = transform->output_table_b->data[gray];
-		dest += RGB_OUTPUT_COMPONENTS;
+		dest[r_out] = transform->output_table_r->data[gray];
+		dest[1]     = transform->output_table_g->data[gray];
+		dest[b_out] = transform->output_table_b->data[gray];
+		dest += 3;
 	}
 }
 
-static void qcms_transform_data_graya_out_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+
+static void qcms_transform_data_graya_out_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	for (i = 0; i < length; i++) {
 		unsigned char device = *src++;
@@ -340,16 +375,19 @@
 		/* we could round here... */
 		gray = linear * PRECACHE_OUTPUT_MAX;
 
-		dest[OUTPUT_R_INDEX] = transform->output_table_r->data[gray];
-		dest[OUTPUT_G_INDEX] = transform->output_table_g->data[gray];
-		dest[OUTPUT_B_INDEX] = transform->output_table_b->data[gray];
-		dest[OUTPUT_A_INDEX] = alpha;
-		dest += RGBA_OUTPUT_COMPONENTS;
+		dest[r_out] = transform->output_table_r->data[gray];
+		dest[1]     = transform->output_table_g->data[gray];
+		dest[b_out] = transform->output_table_b->data[gray];
+		dest[3]     = alpha;
+		dest += 4;
 	}
 }
 
-static void qcms_transform_data_rgb_out_lut_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+static void qcms_transform_data_rgb_out_lut_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	float (*mat)[4] = transform->matrix;
 	for (i = 0; i < length; i++) {
@@ -375,15 +413,18 @@
 		g = out_linear_g * PRECACHE_OUTPUT_MAX;
 		b = out_linear_b * PRECACHE_OUTPUT_MAX;
 
-		dest[OUTPUT_R_INDEX] = transform->output_table_r->data[r];
-		dest[OUTPUT_G_INDEX] = transform->output_table_g->data[g];
-		dest[OUTPUT_B_INDEX] = transform->output_table_b->data[b];
-		dest += RGB_OUTPUT_COMPONENTS;
+		dest[r_out] = transform->output_table_r->data[r];
+		dest[1]     = transform->output_table_g->data[g];
+		dest[b_out] = transform->output_table_b->data[b];
+		dest += 3;
 	}
 }
 
-static void qcms_transform_data_rgba_out_lut_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+void qcms_transform_data_rgba_out_lut_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	float (*mat)[4] = transform->matrix;
 	for (i = 0; i < length; i++) {
@@ -410,17 +451,21 @@
 		g = out_linear_g * PRECACHE_OUTPUT_MAX;
 		b = out_linear_b * PRECACHE_OUTPUT_MAX;
 
-		dest[OUTPUT_R_INDEX] = transform->output_table_r->data[r];
-		dest[OUTPUT_G_INDEX] = transform->output_table_g->data[g];
-		dest[OUTPUT_B_INDEX] = transform->output_table_b->data[b];
-		dest[OUTPUT_A_INDEX] = alpha;
-		dest += RGBA_OUTPUT_COMPONENTS;
+		dest[r_out] = transform->output_table_r->data[r];
+		dest[1]     = transform->output_table_g->data[g];
+		dest[b_out] = transform->output_table_b->data[b];
+		dest[3]     = alpha;
+		dest += 4;
 	}
 }
 
 // Not used
-/* 
-static void qcms_transform_data_clut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length) {
+/*
+static void qcms_transform_data_clut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
+{
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	int xy_len = 1;
 	int x_len = transform->grid_size;
@@ -428,7 +473,7 @@
 	float* r_table = transform->r_clut;
 	float* g_table = transform->g_clut;
 	float* b_table = transform->b_clut;
-  
+
 	for (i = 0; i < length; i++) {
 		unsigned char in_r = *src++;
 		unsigned char in_g = *src++;
@@ -441,9 +486,9 @@
 		int x_n = ceil(linear_r * (transform->grid_size-1));
 		int y_n = ceil(linear_g * (transform->grid_size-1));
 		int z_n = ceil(linear_b * (transform->grid_size-1));
-		float x_d = linear_r * (transform->grid_size-1) - x; 
+		float x_d = linear_r * (transform->grid_size-1) - x;
 		float y_d = linear_g * (transform->grid_size-1) - y;
-		float z_d = linear_b * (transform->grid_size-1) - z; 
+		float z_d = linear_b * (transform->grid_size-1) - z;
 
 		float r_x1 = lerp(CLU(r_table,x,y,z), CLU(r_table,x_n,y,z), x_d);
 		float r_x2 = lerp(CLU(r_table,x,y_n,z), CLU(r_table,x_n,y_n,z), x_d);
@@ -469,15 +514,20 @@
 		float b_y2 = lerp(b_x3, b_x4, y_d);
 		float clut_b = lerp(b_y1, b_y2, z_d);
 
-		*dest++ = clamp_u8(clut_r*255.0f);
-		*dest++ = clamp_u8(clut_g*255.0f);
-		*dest++ = clamp_u8(clut_b*255.0f);
-	}	
+		dest[r_out] = clamp_u8(clut_r*255.0f);
+		dest[1]     = clamp_u8(clut_g*255.0f);
+		dest[b_out] = clamp_u8(clut_b*255.0f);
+		dest += 3;
+	}
 }
 */
 
 // Using lcms' tetra interpolation algorithm.
-static void qcms_transform_data_tetra_clut_rgba(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length) {
+void qcms_transform_data_tetra_clut_rgba(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
+{
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	int xy_len = 1;
 	int x_len = transform->grid_size;
@@ -489,22 +539,27 @@
 	float c0_g, c1_g, c2_g, c3_g;
 	float c0_b, c1_b, c2_b, c3_b;
 	float clut_r, clut_g, clut_b;
+
+	if (!(transform->transform_flags & TRANSFORM_FLAG_CLUT_CACHE))
+		qcms_transform_build_clut_cache(transform);
+
 	for (i = 0; i < length; i++) {
 		unsigned char in_r = *src++;
 		unsigned char in_g = *src++;
 		unsigned char in_b = *src++;
 		unsigned char in_a = *src++;
-		float linear_r = in_r/255.0f, linear_g=in_g/255.0f, linear_b = in_b/255.0f;
 
-		int x = floor(linear_r * (transform->grid_size-1));
-		int y = floor(linear_g * (transform->grid_size-1));
-		int z = floor(linear_b * (transform->grid_size-1));
-		int x_n = ceil(linear_r * (transform->grid_size-1));
-		int y_n = ceil(linear_g * (transform->grid_size-1));
-		int z_n = ceil(linear_b * (transform->grid_size-1));
-		float rx = linear_r * (transform->grid_size-1) - x; 
-		float ry = linear_g * (transform->grid_size-1) - y;
-		float rz = linear_b * (transform->grid_size-1) - z; 
+		int x = transform->floor_cache[in_r];
+		int y = transform->floor_cache[in_g];
+		int z = transform->floor_cache[in_b];
+
+		int x_n = transform->ceil_cache[in_r];
+		int y_n = transform->ceil_cache[in_g];
+		int z_n = transform->ceil_cache[in_b];
+
+		float rx = transform->r_cache[in_r];
+		float ry = transform->r_cache[in_g];
+		float rz = transform->r_cache[in_b];
 
 		c0_r = CLU(r_table, x, y, z);
 		c0_g = CLU(g_table, x, y, z);
@@ -521,7 +576,7 @@
 				c1_b = CLU(b_table, x_n, y, z) - c0_b;
 				c2_b = CLU(b_table, x_n, y_n, z) - CLU(b_table, x_n, y, z);
 				c3_b = CLU(b_table, x_n, y_n, z_n) - CLU(b_table, x_n, y_n, z);
-			} else { 
+			} else {
 				if (rx >= rz) { //rx >= rz && rz >= ry
 					c1_r = CLU(r_table, x_n, y, z) - c0_r;
 					c2_r = CLU(r_table, x_n, y_n, z_n) - CLU(r_table, x_n, y, z_n);
@@ -556,7 +611,7 @@
 				c2_b = CLU(b_table, x, y_n, z) - c0_b;
 				c3_b = CLU(b_table, x_n, y_n, z_n) - CLU(b_table, x_n, y_n, z);
 			} else {
-				if (ry >= rz) { //ry >= rz && rz > rx 
+				if (ry >= rz) { //ry >= rz && rz > rx
 					c1_r = CLU(r_table, x_n, y_n, z_n) - CLU(r_table, x, y_n, z_n);
 					c2_r = CLU(r_table, x, y_n, z) - c0_r;
 					c3_r = CLU(r_table, x, y_n, z_n) - CLU(r_table, x, y_n, z);
@@ -579,21 +634,25 @@
 				}
 			}
 		}
-				
+
 		clut_r = c0_r + c1_r*rx + c2_r*ry + c3_r*rz;
 		clut_g = c0_g + c1_g*rx + c2_g*ry + c3_g*rz;
 		clut_b = c0_b + c1_b*rx + c2_b*ry + c3_b*rz;
 
-		dest[OUTPUT_R_INDEX] = clamp_u8(clut_r*255.0f);
-		dest[OUTPUT_G_INDEX] = clamp_u8(clut_g*255.0f);
-		dest[OUTPUT_B_INDEX] = clamp_u8(clut_b*255.0f);
-		dest[OUTPUT_A_INDEX] = in_a;
-		dest += RGBA_OUTPUT_COMPONENTS;
-	}	
+		dest[r_out] = clamp_u8(clut_r*255.0f);
+		dest[1]     = clamp_u8(clut_g*255.0f);
+		dest[b_out] = clamp_u8(clut_b*255.0f);
+		dest[3]     = in_a;
+		dest += 4;
+	}
 }
 
 // Using lcms' tetra interpolation code.
-static void qcms_transform_data_tetra_clut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length) {
+static void qcms_transform_data_tetra_clut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
+{
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	int xy_len = 1;
 	int x_len = transform->grid_size;
@@ -605,21 +664,26 @@
 	float c0_g, c1_g, c2_g, c3_g;
 	float c0_b, c1_b, c2_b, c3_b;
 	float clut_r, clut_g, clut_b;
+
+	if (!(transform->transform_flags & TRANSFORM_FLAG_CLUT_CACHE))
+		qcms_transform_build_clut_cache(transform);
+
 	for (i = 0; i < length; i++) {
 		unsigned char in_r = *src++;
 		unsigned char in_g = *src++;
 		unsigned char in_b = *src++;
-		float linear_r = in_r/255.0f, linear_g=in_g/255.0f, linear_b = in_b/255.0f;
 
-		int x = floor(linear_r * (transform->grid_size-1));
-		int y = floor(linear_g * (transform->grid_size-1));
-		int z = floor(linear_b * (transform->grid_size-1));
-		int x_n = ceil(linear_r * (transform->grid_size-1));
-		int y_n = ceil(linear_g * (transform->grid_size-1));
-		int z_n = ceil(linear_b * (transform->grid_size-1));
-		float rx = linear_r * (transform->grid_size-1) - x; 
-		float ry = linear_g * (transform->grid_size-1) - y;
-		float rz = linear_b * (transform->grid_size-1) - z; 
+		int x = transform->floor_cache[in_r];
+		int y = transform->floor_cache[in_g];
+		int z = transform->floor_cache[in_b];
+
+		int x_n = transform->ceil_cache[in_r];
+		int y_n = transform->ceil_cache[in_g];
+		int z_n = transform->ceil_cache[in_b];
+
+		float rx = transform->r_cache[in_r];
+		float ry = transform->r_cache[in_g];
+		float rz = transform->r_cache[in_b];
 
 		c0_r = CLU(r_table, x, y, z);
 		c0_g = CLU(g_table, x, y, z);
@@ -636,7 +700,7 @@
 				c1_b = CLU(b_table, x_n, y, z) - c0_b;
 				c2_b = CLU(b_table, x_n, y_n, z) - CLU(b_table, x_n, y, z);
 				c3_b = CLU(b_table, x_n, y_n, z_n) - CLU(b_table, x_n, y_n, z);
-			} else { 
+			} else {
 				if (rx >= rz) { //rx >= rz && rz >= ry
 					c1_r = CLU(r_table, x_n, y, z) - c0_r;
 					c2_r = CLU(r_table, x_n, y_n, z_n) - CLU(r_table, x_n, y, z_n);
@@ -671,7 +735,7 @@
 				c2_b = CLU(b_table, x, y_n, z) - c0_b;
 				c3_b = CLU(b_table, x_n, y_n, z_n) - CLU(b_table, x_n, y_n, z);
 			} else {
-				if (ry >= rz) { //ry >= rz && rz > rx 
+				if (ry >= rz) { //ry >= rz && rz > rx
 					c1_r = CLU(r_table, x_n, y_n, z_n) - CLU(r_table, x, y_n, z_n);
 					c2_r = CLU(r_table, x, y_n, z) - c0_r;
 					c3_r = CLU(r_table, x, y_n, z_n) - CLU(r_table, x, y_n, z);
@@ -694,20 +758,23 @@
 				}
 			}
 		}
-				
+
 		clut_r = c0_r + c1_r*rx + c2_r*ry + c3_r*rz;
 		clut_g = c0_g + c1_g*rx + c2_g*ry + c3_g*rz;
 		clut_b = c0_b + c1_b*rx + c2_b*ry + c3_b*rz;
 
-		dest[OUTPUT_R_INDEX] = clamp_u8(clut_r*255.0f);
-		dest[OUTPUT_G_INDEX] = clamp_u8(clut_g*255.0f);
-		dest[OUTPUT_B_INDEX] = clamp_u8(clut_b*255.0f);
-		dest += RGB_OUTPUT_COMPONENTS;
-	}	
+		dest[r_out] = clamp_u8(clut_r*255.0f);
+		dest[1]     = clamp_u8(clut_g*255.0f);
+		dest[b_out] = clamp_u8(clut_b*255.0f);
+		dest += 3;
+	}
 }
 
-static void qcms_transform_data_rgb_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+static void qcms_transform_data_rgb_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	float (*mat)[4] = transform->matrix;
 	for (i = 0; i < length; i++) {
@@ -728,22 +795,25 @@
 		out_linear_g = clamp_float(out_linear_g);
 		out_linear_b = clamp_float(out_linear_b);
 
-		out_device_r = lut_interp_linear(out_linear_r, 
+		out_device_r = lut_interp_linear(out_linear_r,
 				transform->output_gamma_lut_r, transform->output_gamma_lut_r_length);
-		out_device_g = lut_interp_linear(out_linear_g, 
+		out_device_g = lut_interp_linear(out_linear_g,
 				transform->output_gamma_lut_g, transform->output_gamma_lut_g_length);
-		out_device_b = lut_interp_linear(out_linear_b, 
+		out_device_b = lut_interp_linear(out_linear_b,
 				transform->output_gamma_lut_b, transform->output_gamma_lut_b_length);
 
-		dest[OUTPUT_R_INDEX] = clamp_u8(out_device_r*255);
-		dest[OUTPUT_G_INDEX] = clamp_u8(out_device_g*255);
-		dest[OUTPUT_B_INDEX] = clamp_u8(out_device_b*255);
-		dest += RGB_OUTPUT_COMPONENTS;
+		dest[r_out] = clamp_u8(out_device_r*255);
+		dest[1]     = clamp_u8(out_device_g*255);
+		dest[b_out] = clamp_u8(out_device_b*255);
+		dest += 3;
 	}
 }
 
-static void qcms_transform_data_rgba_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+static void qcms_transform_data_rgba_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	unsigned int i;
 	float (*mat)[4] = transform->matrix;
 	for (i = 0; i < length; i++) {
@@ -765,24 +835,27 @@
 		out_linear_g = clamp_float(out_linear_g);
 		out_linear_b = clamp_float(out_linear_b);
 
-		out_device_r = lut_interp_linear(out_linear_r, 
+		out_device_r = lut_interp_linear(out_linear_r,
 				transform->output_gamma_lut_r, transform->output_gamma_lut_r_length);
-		out_device_g = lut_interp_linear(out_linear_g, 
+		out_device_g = lut_interp_linear(out_linear_g,
 				transform->output_gamma_lut_g, transform->output_gamma_lut_g_length);
-		out_device_b = lut_interp_linear(out_linear_b, 
+		out_device_b = lut_interp_linear(out_linear_b,
 				transform->output_gamma_lut_b, transform->output_gamma_lut_b_length);
 
-		dest[OUTPUT_R_INDEX] = clamp_u8(out_device_r*255);
-		dest[OUTPUT_G_INDEX] = clamp_u8(out_device_g*255);
-		dest[OUTPUT_B_INDEX] = clamp_u8(out_device_b*255);
-		dest[OUTPUT_A_INDEX] = alpha;
-		dest += RGBA_OUTPUT_COMPONENTS;
+		dest[r_out] = clamp_u8(out_device_r*255);
+		dest[1]     = clamp_u8(out_device_g*255);
+		dest[b_out] = clamp_u8(out_device_b*255);
+		dest[3]     = alpha;
+		dest += 4;
 	}
 }
 
 #if 0
-static void qcms_transform_data_rgb_out_linear(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+static void qcms_transform_data_rgb_out_linear(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length, qcms_format_type output_format)
 {
+	const int r_out = output_format.r;
+	const int b_out = output_format.b;
+
 	int i;
 	float (*mat)[4] = transform->matrix;
 	for (i = 0; i < length; i++) {
@@ -798,16 +871,25 @@
 		float out_linear_g = mat[0][1]*linear_r + mat[1][1]*linear_g + mat[2][1]*linear_b;
 		float out_linear_b = mat[0][2]*linear_r + mat[1][2]*linear_g + mat[2][2]*linear_b;
 
-		*dest++ = clamp_u8(out_linear_r*255);
-		*dest++ = clamp_u8(out_linear_g*255);
-		*dest++ = clamp_u8(out_linear_b*255);
+		dest[r_out] = clamp_u8(out_linear_r*255);
+		dest[1]     = clamp_u8(out_linear_g*255);
+		dest[b_out] = clamp_u8(out_linear_b*255);
+		dest += 3;
 	}
 }
 #endif
 
+/*
+ * If users create and destroy objects on different threads, even if the same
+ * objects aren't used on different threads at the same time, we can still run
+ * in to trouble with refcounts if they aren't atomic.
+ *
+ * This can lead to us prematurely deleting the precache if threads get unlucky
+ * and write the wrong value to the ref count.
+ */
 static struct precache_output *precache_reference(struct precache_output *p)
 {
-	p->ref_count++;
+	qcms_atomic_increment(p->ref_count);
 	return p;
 }
 
@@ -821,12 +903,12 @@
 
 void precache_release(struct precache_output *p)
 {
-	if (--p->ref_count == 0) {
+	if (qcms_atomic_decrement(p->ref_count) == 0) {
 		free(p);
 	}
 }
 
-#ifdef HAS_POSIX_MEMALIGN
+#ifdef HAVE_POSIX_MEMALIGN
 static qcms_transform *transform_alloc(void)
 {
 	qcms_transform *t;
@@ -930,7 +1012,7 @@
 static void cpuid(uint32_t fxn, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d) {
 
 	uint32_t a_, b_, c_, d_;
-       __asm__ __volatile__ ("xchgl %%ebx, %%esi; cpuid; xchgl %%ebx, %%esi;" 
+       __asm__ __volatile__ ("xchgl %%ebx, %%esi; cpuid; xchgl %%ebx, %%esi;"
                              : "=a" (a_), "=S" (b_), "=c" (c_), "=d" (d_) : "a" (fxn));
 	   *a = a_;
 	   *b = b_;
@@ -979,12 +1061,12 @@
 
 static const struct matrix bradford_matrix = {{	{ 0.8951f, 0.2664f,-0.1614f},
 						{-0.7502f, 1.7135f, 0.0367f},
-						{ 0.0389f,-0.0685f, 1.0296f}}, 
+						{ 0.0389f,-0.0685f, 1.0296f}},
 						false};
 
 static const struct matrix bradford_matrix_inv = {{ { 0.9869929f,-0.1470543f, 0.1599627f},
 						    { 0.4323053f, 0.5183603f, 0.0492912f},
-						    {-0.0085287f, 0.0400428f, 0.9684867f}}, 
+						    {-0.0085287f, 0.0400428f, 0.9684867f}},
 						    false};
 
 // See ICCv4 E.3
@@ -1046,7 +1128,7 @@
 }
 
 /* Replace the current transformation with a LUT transformation using a given number of sample points */
-qcms_transform* qcms_transform_precacheLUT_float(qcms_transform *transform, qcms_profile *in, qcms_profile *out, 
+qcms_transform* qcms_transform_precacheLUT_float(qcms_transform *transform, qcms_profile *in, qcms_profile *out,
                                                  int samples, qcms_data_type in_type)
 {
 	/* The range between which 2 consecutive sample points can be used to interpolate */
@@ -1056,39 +1138,51 @@
 	float* src = NULL;
 	float* dest = NULL;
 	float* lut = NULL;
+	float inverse;
 
 	src = malloc(lutSize*sizeof(float));
 	dest = malloc(lutSize*sizeof(float));
 
 	if (src && dest) {
-		/* Prepare a list of points we want to sample */
+		/* Prepare a list of points we want to sample: x, y, z order */
 		l = 0;
+		inverse = 1 / (float)(samples-1);
 		for (x = 0; x < samples; x++) {
 			for (y = 0; y < samples; y++) {
 				for (z = 0; z < samples; z++) {
-					src[l++] = x / (float)(samples-1);
-					src[l++] = y / (float)(samples-1);
-					src[l++] = z / (float)(samples-1);
+					src[l++] = x * inverse; // r
+					src[l++] = y * inverse; // g
+					src[l++] = z * inverse; // b
 				}
 			}
 		}
 
 		lut = qcms_chain_transform(in, out, src, dest, lutSize);
+
 		if (lut) {
-			transform->r_clut = &lut[0];
-			transform->g_clut = &lut[1];
-			transform->b_clut = &lut[2];
+			transform->r_clut = &lut[0]; // r
+			transform->g_clut = &lut[1]; // g
+			transform->b_clut = &lut[2]; // b
 			transform->grid_size = samples;
+
 			if (in_type == QCMS_DATA_RGBA_8) {
+#if defined(SSE2_ENABLE)
+				if (sse_version_available() >= 2) {
+					transform->transform_fn = qcms_transform_data_tetra_clut_rgba_sse2;
+				} else {
+					transform->transform_fn = qcms_transform_data_tetra_clut_rgba;
+				}
+#else
 				transform->transform_fn = qcms_transform_data_tetra_clut_rgba;
+#endif
 			} else {
 				transform->transform_fn = qcms_transform_data_tetra_clut;
 			}
 		}
 	}
 
-
-	//XXX: qcms_modular_transform_data may return either the src or dest buffer. If so it must not be free-ed
+	// XXX: qcms_modular_transform_data may return the lut in either the src or the
+	// dest buffer. If so, it must not be free-ed.
 	if (src && lut != src) {
 		free(src);
 	}
@@ -1102,6 +1196,89 @@
 	return transform;
 }
 
+/* Create a transform LUT using the given number of sample points. The transform LUT data is stored
+   in the output (cube) in bgra format in zyx sample order. */
+qcms_bool qcms_transform_create_LUT_zyx_bgra(qcms_profile *in, qcms_profile *out, qcms_intent intent,
+                                             int samples, unsigned char* cube)
+{
+	uint16_t z,y,x;
+	uint32_t l,index;
+	uint32_t lutSize = 3 * samples * samples * samples;
+
+	float* src = NULL;
+	float* dest = NULL;
+	float* lut = NULL;
+	float inverse;
+
+	src = malloc(lutSize*sizeof(float));
+	dest = malloc(lutSize*sizeof(float));
+
+	if (src && dest) {
+		/* Prepare a list of points we want to sample: z, y, x order */
+		l = 0;
+		inverse = 1 / (float)(samples-1);
+		for (z = 0; z < samples; z++) {
+			for (y = 0; y < samples; y++) {
+				for (x = 0; x < samples; x++) {
+					src[l++] = x * inverse; // r
+					src[l++] = y * inverse; // g
+					src[l++] = z * inverse; // b
+				}
+			}
+		}
+
+		lut = qcms_chain_transform(in, out, src, dest, lutSize);
+
+		if (lut) {
+			index = l = 0;
+			for (z = 0; z < samples; z++) {
+				for (y = 0; y < samples; y++) {
+					for (x = 0; x < samples; x++) {
+						cube[index++] = (int)floorf(lut[l + 2] * 255.0f + 0.5f); // b
+						cube[index++] = (int)floorf(lut[l + 1] * 255.0f + 0.5f); // g
+						cube[index++] = (int)floorf(lut[l + 0] * 255.0f + 0.5f); // r
+						cube[index++] = 255;                                     // a
+						l += 3;
+					}
+				}
+			}
+		}
+	}
+
+	// XXX: qcms_modular_transform_data may return the lut data in either the src or
+	// dest buffer so free src, dest, and lut with care.
+
+	if (src && lut != src)
+		free(src);
+	if (dest && lut != dest)
+		free(dest);
+
+	if (lut) {
+		free(lut);
+		return true;
+	}
+
+	return false;
+}
+
+void qcms_transform_build_clut_cache(qcms_transform* transform) {
+	const int grid_factor = transform->grid_size - 1;
+	const float grid_scaled = (1.0f / 255.0f) * grid_factor;
+	int i;
+
+#define div_255_ceiling(value) (((value) + 254) / 255)
+
+	for (i = 0; i < 256; i++) {
+		transform->ceil_cache[i] = div_255_ceiling(i * grid_factor);
+		transform->floor_cache[i] = i * grid_factor / 255;
+		transform->r_cache[i] = (i * grid_scaled) - transform->floor_cache[i];
+	}
+
+#undef div_255_ceil
+
+	transform->transform_flags |= TRANSFORM_FLAG_CLUT_CACHE;
+}
+
 #define NO_MEM_TRANSFORM NULL
 
 qcms_transform* qcms_transform_create(
@@ -1109,40 +1286,49 @@
 		qcms_profile *out, qcms_data_type out_type,
 		qcms_intent intent)
 {
+	qcms_transform *transform = NULL;
 	bool precache = false;
+	int i, j;
 
-        qcms_transform *transform = transform_alloc();
-        if (!transform) {
+	transform = transform_alloc();
+	if (!transform) {
 		return NULL;
 	}
-	if (out_type != QCMS_DATA_RGB_8 &&
-                out_type != QCMS_DATA_RGBA_8) {
-            assert(0 && "output type");
-	    transform_free(transform);
-            return NULL;
-        }
 
-	if (out->output_table_r &&
-			out->output_table_g &&
-			out->output_table_b) {
+	if (out_type != QCMS_DATA_RGB_8 && out_type != QCMS_DATA_RGBA_8) {
+		assert(0 && "output type");
+		qcms_transform_release(transform);
+		return NULL;
+	}
+
+	transform->transform_flags = 0;
+
+	if (out->output_table_r && out->output_table_g && out->output_table_b) {
 		precache = true;
 	}
 
 	if (qcms_supports_iccv4 && (in->A2B0 || out->B2A0 || in->mAB || out->mAB)) {
 		// Precache the transformation to a CLUT 33x33x33 in size.
-		// 33 is used by many profiles and works well in pratice. 
+		// 33 is used by many profiles and works well in practice.
 		// This evenly divides 256 into blocks of 8x8x8.
 		// TODO For transforming small data sets of about 200x200 or less
 		// precaching should be avoided.
 		qcms_transform *result = qcms_transform_precacheLUT_float(transform, in, out, 33, in_type);
 		if (!result) {
-            		assert(0 && "precacheLUT failed");
-			transform_free(transform);
+			assert(0 && "precacheLUT failed");
+			qcms_transform_release(transform);
 			return NULL;
 		}
 		return result;
 	}
 
+	/* A matrix-based transform will be selected: check that the PCS
+	   of the input/output profiles are the same, crbug.com/5120682 */
+	if (in->pcs != out->pcs) {
+		qcms_transform_release(transform);
+		return NULL;
+	}
+
 	if (precache) {
 		transform->output_table_r = precache_reference(out->output_table_r);
 		transform->output_table_g = precache_reference(out->output_table_g);
@@ -1152,43 +1338,34 @@
 			qcms_transform_release(transform);
 			return NO_MEM_TRANSFORM;
 		}
+
 		build_output_lut(out->redTRC, &transform->output_gamma_lut_r, &transform->output_gamma_lut_r_length);
 		build_output_lut(out->greenTRC, &transform->output_gamma_lut_g, &transform->output_gamma_lut_g_length);
 		build_output_lut(out->blueTRC, &transform->output_gamma_lut_b, &transform->output_gamma_lut_b_length);
+
 		if (!transform->output_gamma_lut_r || !transform->output_gamma_lut_g || !transform->output_gamma_lut_b) {
 			qcms_transform_release(transform);
 			return NO_MEM_TRANSFORM;
 		}
 	}
 
-        if (in->color_space == RGB_SIGNATURE) {
+	if (in->color_space == RGB_SIGNATURE) {
 		struct matrix in_matrix, out_matrix, result;
 
-		if (in_type != QCMS_DATA_RGB_8 &&
-                    in_type != QCMS_DATA_RGBA_8){
-                	assert(0 && "input type");
-			transform_free(transform);
-                	return NULL;
-            	}
-		if (precache) {
-#ifdef X86
-		    if (sse_version_available() >= 2) {
-			    if (in_type == QCMS_DATA_RGB_8)
-				    transform->transform_fn = qcms_transform_data_rgb_out_lut_sse2;
-			    else
-				    transform->transform_fn = qcms_transform_data_rgba_out_lut_sse2;
+		if (in_type != QCMS_DATA_RGB_8 && in_type != QCMS_DATA_RGBA_8) {
+			assert(0 && "input type");
+			qcms_transform_release(transform);
+			return NULL;
+		}
 
-#if !(defined(_MSC_VER) && defined(_M_AMD64))
-                    /* Microsoft Compiler for x64 doesn't support MMX.
-                     * SSE code uses MMX so that we disable on x64 */
-		    } else
-		    if (sse_version_available() >= 1) {
-			    if (in_type == QCMS_DATA_RGB_8)
-				    transform->transform_fn = qcms_transform_data_rgb_out_lut_sse1;
-			    else
-				    transform->transform_fn = qcms_transform_data_rgba_out_lut_sse1;
-#endif
-		    } else
+		if (precache) {
+#if defined(SSE2_ENABLE)
+			if (sse_version_available() >= 2) {
+				if (in_type == QCMS_DATA_RGB_8)
+					transform->transform_fn = qcms_transform_data_rgb_out_lut_sse2;
+				else
+					transform->transform_fn = qcms_transform_data_rgba_out_lut_sse2;
+			} else
 #endif
 			{
 				if (in_type == QCMS_DATA_RGB_8)
@@ -1207,12 +1384,12 @@
 		transform->input_gamma_table_r = build_input_gamma_table(in->redTRC);
 		transform->input_gamma_table_g = build_input_gamma_table(in->greenTRC);
 		transform->input_gamma_table_b = build_input_gamma_table(in->blueTRC);
+
 		if (!transform->input_gamma_table_r || !transform->input_gamma_table_g || !transform->input_gamma_table_b) {
 			qcms_transform_release(transform);
 			return NO_MEM_TRANSFORM;
 		}
 
-
 		/* build combined colorant matrix */
 		in_matrix = build_colorant_matrix(in);
 		out_matrix = build_colorant_matrix(out);
@@ -1223,6 +1400,17 @@
 		}
 		result = matrix_multiply(out_matrix, in_matrix);
 
+		/* check for NaN values in the matrix and bail if we find any
+		   see also https://bugzilla.mozilla.org/show_bug.cgi?id=1170316 */
+		for (i = 0 ; i < 3 ; ++i) {
+			for (j = 0 ; j < 3 ; ++j) {
+				if (result.m[i][j] != result.m[i][j]) {
+					qcms_transform_release(transform);
+					return NULL;
+				}
+			}
+		}
+
 		/* store the results in column major mode
 		 * this makes doing the multiplication with sse easier */
 		transform->matrix[0][0] = result.m[0][0];
@@ -1235,15 +1423,18 @@
 		transform->matrix[1][2] = result.m[2][1];
 		transform->matrix[2][2] = result.m[2][2];
 
+		/* Flag transform as matrix. */
+		transform->transform_flags |= TRANSFORM_FLAG_MATRIX;
+
 	} else if (in->color_space == GRAY_SIGNATURE) {
-		if (in_type != QCMS_DATA_GRAY_8 &&
-				in_type != QCMS_DATA_GRAYA_8){
+		if (in_type != QCMS_DATA_GRAY_8 && in_type != QCMS_DATA_GRAYA_8) {
 			assert(0 && "input type");
-			transform_free(transform);
+			qcms_transform_release(transform);
 			return NULL;
 		}
 
 		transform->input_gamma_table_gray = build_input_gamma_table(in->grayTRC);
+
 		if (!transform->input_gamma_table_gray) {
 			qcms_transform_release(transform);
 			return NO_MEM_TRANSFORM;
@@ -1264,23 +1455,187 @@
 		}
 	} else {
 		assert(0 && "unexpected colorspace");
-		transform_free(transform);
+		qcms_transform_release(transform);
 		return NULL;
 	}
+
 	return transform;
 }
 
-#if defined(__GNUC__) && !defined(__x86_64__) && !defined(__amd64__)
+/* __force_align_arg_pointer__ is an x86-only attribute, and gcc/clang warns on unused
+ * attributes. Don't use this on ARM or AMD64. __has_attribute can detect the presence
+ * of the attribute but is currently only supported by clang */
+#if defined(__has_attribute)
+#define HAS_FORCE_ALIGN_ARG_POINTER __has_attribute(__force_align_arg_pointer__)
+#elif defined(__GNUC__) && defined(__i386__)
+#define HAS_FORCE_ALIGN_ARG_POINTER 1
+#else
+#define HAS_FORCE_ALIGN_ARG_POINTER 0
+#endif
+
+#if HAS_FORCE_ALIGN_ARG_POINTER
 /* we need this to avoid crashes when gcc assumes the stack is 128bit aligned */
 __attribute__((__force_align_arg_pointer__))
 #endif
 void qcms_transform_data(qcms_transform *transform, void *src, void *dest, size_t length)
 {
-	transform->transform_fn(transform, src, dest, length);
+	static const struct _qcms_format_type output_rgbx = { 0, 2 };
+
+	transform->transform_fn(transform, src, dest, length, output_rgbx);
 }
 
-qcms_bool qcms_supports_iccv4;
+void qcms_transform_data_type(qcms_transform *transform, void *src, void *dest, size_t length, qcms_output_type type)
+{
+	static const struct _qcms_format_type output_rgbx = { 0, 2 };
+	static const struct _qcms_format_type output_bgrx = { 2, 0 };
+
+	transform->transform_fn(transform, src, dest, length, type == QCMS_OUTPUT_BGRX ? output_bgrx : output_rgbx);
+}
+
+#define ENABLE_ICC_V4_PROFILE_SUPPORT false
+
+qcms_bool qcms_supports_iccv4 = ENABLE_ICC_V4_PROFILE_SUPPORT;
+
 void qcms_enable_iccv4()
 {
 	qcms_supports_iccv4 = true;
 }
+
+static inline qcms_bool transform_is_matrix(qcms_transform *t)
+{
+	return (t->transform_flags & TRANSFORM_FLAG_MATRIX) ? true : false;
+}
+
+qcms_bool qcms_transform_is_matrix(qcms_transform *t)
+{
+	return transform_is_matrix(t);
+}
+
+float qcms_transform_get_matrix(qcms_transform *t, unsigned i, unsigned j)
+{
+	assert(transform_is_matrix(t) && i < 3 && j < 3);
+
+	// Return transform matrix element in row major order (permute i and j)
+
+	return t->matrix[j][i];
+}
+
+static inline qcms_bool supported_trc_type(qcms_trc_type type)
+{
+	return (type == QCMS_TRC_HALF_FLOAT || type == QCMS_TRC_USHORT);
+}
+
+const uint16_t half_float_one = 0x3c00;
+
+size_t qcms_transform_get_input_trc_rgba(qcms_transform *t, qcms_profile *in, qcms_trc_type type, unsigned short *data)
+{
+	const size_t size = 256; // The input gamma tables always have 256 entries.
+
+	size_t i;
+
+	if (in->color_space != RGB_SIGNATURE || !supported_trc_type(type))
+		return 0;
+
+	// qcms_profile *in is assumed to be the profile on the input-side of the color transform t.
+	// When a transform is created, the input gamma curve data is stored in the transform ...
+
+	if (!t->input_gamma_table_r || !t->input_gamma_table_g || !t->input_gamma_table_b)
+		return 0;
+
+	// Report the size if no output data is requested. This allows callers to first work out the
+	// the curve size, then provide allocated memory sufficient to store the curve rgba data.
+
+	if (!data)
+		return size;
+
+	switch(type) {
+		case QCMS_TRC_HALF_FLOAT:
+			for (i = 0; i < size; ++i) {
+				*data++ = float_to_half_float(t->input_gamma_table_r[i]); // r
+				*data++ = float_to_half_float(t->input_gamma_table_g[i]); // g
+				*data++ = float_to_half_float(t->input_gamma_table_b[i]); // b
+				*data++ = half_float_one;                                 // a
+			}
+			break;
+		case QCMS_TRC_USHORT:
+			for (i = 0; i < size; ++i) {
+				*data++ = roundf(t->input_gamma_table_r[i] * 65535.0); // r
+				*data++ = roundf(t->input_gamma_table_g[i] * 65535.0); // g
+				*data++ = roundf(t->input_gamma_table_b[i] * 65535.0); // b
+				*data++ = 65535;                                       // a
+			}
+			break;
+		default:
+			/* should not be reached */
+			assert(0);
+	}
+
+	return size;
+}
+
+const float inverse65535 = (float) (1.0 / 65535.0);
+
+size_t qcms_transform_get_output_trc_rgba(qcms_transform *t, qcms_profile *out, qcms_trc_type type, unsigned short *data)
+{
+	size_t size, i;
+
+	if (out->color_space != RGB_SIGNATURE || !supported_trc_type(type))
+		return 0;
+
+	// qcms_profile *out is assumed to be the profile on the output-side of the transform t.
+	// If the transform output gamma curves need building, do that. They're usually built when
+	// the transform was created, but sometimes not due to the output gamma precache ...
+
+	if (!out->redTRC || !out->greenTRC || !out->blueTRC)
+		return 0;
+	if (!t->output_gamma_lut_r)
+		build_output_lut(out->redTRC, &t->output_gamma_lut_r, &t->output_gamma_lut_r_length);
+	if (!t->output_gamma_lut_g)
+		build_output_lut(out->greenTRC, &t->output_gamma_lut_g, &t->output_gamma_lut_g_length);
+	if (!t->output_gamma_lut_b)
+		build_output_lut(out->blueTRC, &t->output_gamma_lut_b, &t->output_gamma_lut_b_length);
+
+	if (!t->output_gamma_lut_r || !t->output_gamma_lut_g || !t->output_gamma_lut_b)
+		return 0;
+
+	// Output gamma tables should have the same size and should have 4096 entries at most (the
+	// minimum is 256). Larger tables are rare and ignored here: fail by returning 0.
+
+	size = t->output_gamma_lut_r_length;
+	if (size != t->output_gamma_lut_g_length)
+		return 0;
+	if (size != t->output_gamma_lut_b_length)
+		return 0;
+	if (size < 256 || size > 4096)
+		return 0;
+
+	// Report the size if no output data is requested. This allows callers to first work out the
+	// the curve size, then provide allocated memory sufficient to store the curve rgba data.
+
+	if (!data)
+		return size;
+
+	switch (type) {
+		case QCMS_TRC_HALF_FLOAT:
+			for (i = 0; i < size; ++i) {
+				*data++ = float_to_half_float(t->output_gamma_lut_r[i] * inverse65535); // r
+				*data++ = float_to_half_float(t->output_gamma_lut_g[i] * inverse65535); // g
+				*data++ = float_to_half_float(t->output_gamma_lut_b[i] * inverse65535); // b
+				*data++ = half_float_one;                                               // a
+			}
+			break;
+		case QCMS_TRC_USHORT:
+			for (i = 0; i < size; ++i) {
+				*data++ = t->output_gamma_lut_r[i]; // r
+				*data++ = t->output_gamma_lut_g[i]; // g
+				*data++ = t->output_gamma_lut_b[i]; // b
+				*data++ = 65535;                    // a
+			}
+			break;
+		default:
+			/* should not be reached */
+			assert(0);
+	}
+
+	return size;
+}
diff --git a/transform_util.c b/transform_util.c
index 1ff8a1e..8b9703d 100644
--- a/transform_util.c
+++ b/transform_util.c
@@ -1,3 +1,24 @@
+//  qcms
+//  Copyright (C) 2009 Mozilla Foundation
+//
+// 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.
+
 #define _ISOC99_SOURCE  /* for INFINITY */
 
 #include <math.h>
@@ -15,8 +36,8 @@
 
 /* value must be a value between 0 and 1 */
 //XXX: is the above a good restriction to have?
-// the output range of this functions is 0..1
-float lut_interp_linear(double input_value, uint16_t *table, int length)
+// the output range of this function is 0..1
+float lut_interp_linear(double input_value, uint16_t *table, size_t length)
 {
 	int upper, lower;
 	float value;
@@ -30,11 +51,11 @@
 }
 
 /* same as above but takes and returns a uint16_t value representing a range from 0..1 */
-uint16_t lut_interp_linear16(uint16_t input_value, uint16_t *table, int length)
+uint16_t lut_interp_linear16(uint16_t input_value, uint16_t *table, size_t length)
 {
 	/* Start scaling input_value to the length of the array: 65535*(length-1).
 	 * We'll divide out the 65535 next */
-	uint32_t value = (input_value * (length - 1));
+	uintptr_t value = (input_value * (length - 1));
 	uint32_t upper = (value + 65534) / 65535; /* equivalent to ceil(value/65535) */
 	uint32_t lower = value / 65535;           /* equivalent to floor(value/65535) */
 	/* interp is the distance from upper to value scaled to 0..65535 */
@@ -48,11 +69,11 @@
 /* same as above but takes an input_value from 0..PRECACHE_OUTPUT_MAX
  * and returns a uint8_t value representing a range from 0..1 */
 static
-uint8_t lut_interp_linear_precache_output(uint32_t input_value, uint16_t *table, int length)
+uint8_t lut_interp_linear_precache_output(uint32_t input_value, uint16_t *table, size_t length)
 {
 	/* Start scaling input_value to the length of the array: PRECACHE_OUTPUT_MAX*(length-1).
 	 * We'll divide out the PRECACHE_OUTPUT_MAX next */
-	uint32_t value = (input_value * (length - 1));
+	uintptr_t value = (input_value * (length - 1));
 
 	/* equivalent to ceil(value/PRECACHE_OUTPUT_MAX) */
 	uint32_t upper = (value + PRECACHE_OUTPUT_MAX-1) / PRECACHE_OUTPUT_MAX;
@@ -72,7 +93,7 @@
 
 /* value must be a value between 0 and 1 */
 //XXX: is the above a good restriction to have?
-float lut_interp_linear_float(float value, float *table, int length)
+float lut_interp_linear_float(float value, float *table, size_t length)
 {
         int upper, lower;
         value = value * (length - 1);
@@ -106,12 +127,12 @@
 	unsigned int i;
 	float gamma_float = u8Fixed8Number_to_float(gamma);
 	for (i = 0; i < 256; i++) {
-                // 0..1^(0..255 + 255/256) will always be between 0 and 1
+		// 0..1^(0..255 + 255/256) will always be between 0 and 1
 		gamma_table[i] = pow(i/255., gamma_float);
 	}
 }
 
-void compute_curve_gamma_table_type2(float gamma_table[256], uint16_t *table, int length)
+void compute_curve_gamma_table_type2(float gamma_table[256], uint16_t *table, size_t length)
 {
 	unsigned int i;
 	for (i = 0; i < 256; i++) {
@@ -168,15 +189,16 @@
                 e = 0;
                 f = 0;
                 interval = -INFINITY;
-        }       
+        }
         for (X = 0; X < 256; X++) {
-                if (X >= interval) {
+                float x = X / 255.0;
+                if (x >= interval) {
                         // XXX The equations are not exactly as definied in the spec but are
                         //     algebraic equivilent.
                         // TODO Should division by 255 be for the whole expression.
-                        gamma_table[X] = clamp_float(pow(a * X / 255. + b, y) + c + e);
+                        gamma_table[X] = clamp_float(pow(a * x + b, y) + c + e);
                 } else {
-                        gamma_table[X] = clamp_float(c * X / 255. + f);
+                        gamma_table[X] = clamp_float(c * x + f);
                 }
         }
 }
@@ -229,6 +251,21 @@
 	return x/256.;
 }
 
+/* The SSE2 code uses min & max which let NaNs pass through.
+   We want to try to prevent that here by ensuring that
+   gamma table is within expected values. */
+void validate_gamma_table(float gamma_table[256])
+{
+	int i;
+	for (i = 0; i < 256; i++) {
+		// Note: we check that the gamma is not in range
+		// instead of out of range so that we catch NaNs
+		if (!(gamma_table[i] >= 0.f && gamma_table[i] <= 1.f)) {
+			gamma_table[i] = 0.f;
+		}
+	}
+}
+
 float *build_input_gamma_table(struct curveType *TRC)
 {
 	float *gamma_table;
@@ -248,7 +285,10 @@
 			}
 		}
 	}
-        return gamma_table;
+
+	validate_gamma_table(gamma_table);
+
+	return gamma_table;
 }
 
 struct matrix build_colorant_matrix(qcms_profile *p)
@@ -271,25 +311,19 @@
  * I think it could be much better. For example, Argyll seems to have better code in
  * icmTable_lookup_bwd and icmTable_setup_bwd. However, for now this is a quick way
  * to a working solution and allows for easy comparing with lcms. */
-uint16_fract_t lut_inverse_interp16(uint16_t Value, uint16_t LutTable[], int length)
+uint16_fract_t lut_inverse_interp16(uint16_t Value, uint16_t LutTable[], int length, int NumZeroes, int NumPoles)
 {
         int l = 1;
         int r = 0x10000;
         int x = 0, res;       // 'int' Give spacing for negative values
-        int NumZeroes, NumPoles;
         int cell0, cell1;
         double val2;
         double y0, y1, x0, x1;
         double a, b, f;
 
         // July/27 2001 - Expanded to handle degenerated curves with an arbitrary
-        // number of elements containing 0 at the begining of the table (Zeroes)
+        // number of elements containing 0 at the beginning of the table (Zeroes)
         // and another arbitrary number of poles (FFFFh) at the end.
-        // First the zero and pole extents are computed, then value is compared.
-
-        NumZeroes = 0;
-        while (LutTable[NumZeroes] == 0 && NumZeroes < length-1)
-                        NumZeroes++;
 
         // There are no zeros at the beginning and we are trying to find a zero, so
         // return anything. It seems zero would be the less destructive choice
@@ -297,28 +331,48 @@
         if (NumZeroes == 0 && Value == 0)
             return 0;
 
-        NumPoles = 0;
-        while (LutTable[length-1- NumPoles] == 0xFFFF && NumPoles < length-1)
-                        NumPoles++;
-
         // Does the curve belong to this case?
         if (NumZeroes > 1 || NumPoles > 1)
-        {               
-                int a, b;
+        {
+                int a, b, sample;
 
-                // Identify if value fall downto 0 or FFFF zone             
+                // Identify if value fall downto 0 or FFFF zone
                 if (Value == 0) return 0;
-               // if (Value == 0xFFFF) return 0xFFFF;
+                // if (Value == 0xFFFF) return 0xFFFF;
+                sample = (length-1) * ((double) Value * (1./65535.));
+                if (LutTable[sample] == 0xffff)
+                    return 0xffff;
 
                 // else restrict to valid zone
 
-                a = ((NumZeroes-1) * 0xFFFF) / (length-1);               
+                a = ((NumZeroes-1) * 0xFFFF) / (length-1);
                 b = ((length-1 - NumPoles) * 0xFFFF) / (length-1);
-                                                                
+
                 l = a - 1;
                 r = b + 1;
+
+                // Ensure a valid binary search range
+
+                if (l < 1)
+                    l = 1;
+                if (r > 0x10000)
+                    r = 0x10000;
+
+                // If the search range is inverted due to degeneracy,
+                // deem LutTable non-invertible in this search range.
+                // Refer to https://bugzil.la/1132467
+
+                if (r <= l)
+                    return 0;
         }
 
+        // For input 0, return that to maintain black level. Note the binary search
+        // does not. For example, it inverts the standard sRGB gamma curve to 7 at
+        // the origin, causing a black level error.
+
+        if (Value == 0 && NumZeroes) {
+            return 0;
+        }
 
         // Seems not a degenerated case... apply binary search
 
@@ -326,12 +380,12 @@
 
                 x = (l + r) / 2;
 
-		res = (int) lut_interp_linear16((uint16_fract_t) (x-1), LutTable, length);
+                res = (int) lut_interp_linear16((uint16_fract_t) (x-1), LutTable, length);
 
                 if (res == Value) {
 
-                    // Found exact match. 
-                    
+                    // Found exact match.
+
                     return (uint16_fract_t) (x - 1);
                 }
 
@@ -341,18 +395,24 @@
 
         // Not found, should we interpolate?
 
-                
         // Get surrounding nodes
-        
+
+        assert(x >= 1);
+
         val2 = (length-1) * ((double) (x - 1) / 65535.0);
 
         cell0 = (int) floor(val2);
         cell1 = (int) ceil(val2);
-           
+
+        assert(cell0 >= 0);
+        assert(cell1 >= 0);
+        assert(cell0 < length);
+        assert(cell1 < length);
+
         if (cell0 == cell1) return (uint16_fract_t) x;
 
         y0 = LutTable[cell0] ;
-        x0 = (65535.0 * cell0) / (length-1); 
+        x0 = (65535.0 * cell0) / (length-1);
 
         y1 = LutTable[cell1] ;
         x1 = (65535.0 * cell1) / (length-1);
@@ -367,8 +427,22 @@
         if (f < 0.0) return (uint16_fract_t) 0;
         if (f >= 65535.0) return (uint16_fract_t) 0xFFFF;
 
-        return (uint16_fract_t) floor(f + 0.5);                        
+        return (uint16_fract_t) floor(f + 0.5);
+}
 
+// December/16 2015 - Moved this code out of lut_inverse_interp16
+// in order to save computation in invert_lut loop.
+static void count_zeroes_and_poles(uint16_t *LutTable, int length, int *NumZeroes, int *NumPoles)
+{
+    int z = 0, p = 0;
+
+    while (LutTable[z] == 0 && z < length - 1)
+    	z++;
+    *NumZeroes = z;
+
+    while (LutTable[length - 1 - p] == 0xFFFF && p < length - 1)
+    	p++;
+    *NumPoles = p;
 }
 
 /*
@@ -384,20 +458,27 @@
  which has an maximum error of about 9855 (pixel difference of ~38.346)
 
  For now, we punt the decision of output size to the caller. */
-static uint16_t *invert_lut(uint16_t *table, int length, int out_length)
+static uint16_t *invert_lut(uint16_t *table, int length, size_t out_length)
 {
-        int i;
+        int NumZeroes;
+        int NumPoles;
+        size_t i;
         /* for now we invert the lut by creating a lut of size out_length
          * and attempting to lookup a value for each entry using lut_inverse_interp16 */
         uint16_t *output = malloc(sizeof(uint16_t)*out_length);
         if (!output)
                 return NULL;
 
+        // December/16 2015 - Compute the input curve zero and pole extents outside
+        // the loop and pass them to lut_inverse_interp16.
+        count_zeroes_and_poles(table, length, &NumZeroes, &NumPoles);
+
         for (i = 0; i < out_length; i++) {
                 double x = ((double) i * 65535.) / (double) (out_length - 1);
                 uint16_fract_t input = floor(x + .5);
-                output[i] = lut_inverse_interp16(input, table, length);
+                output[i] = lut_inverse_interp16(input, table, length, NumZeroes, NumPoles);
         }
+
         return output;
 }
 
@@ -429,7 +510,7 @@
 
 qcms_bool compute_precache(struct curveType *trc, uint8_t *output)
 {
-        
+
         if (trc->type == PARAMETRIC_CURVE_TYPE) {
                         float gamma_table[256];
                         uint16_t gamma_table_uint[256];
@@ -442,9 +523,9 @@
                                 gamma_table_uint[i] = (uint16_t)(gamma_table[i] * 65535);
                         }
 
-                        //XXX: the choice of a minimum of 256 here is not backed by any theory, 
+                        //XXX: the choice of a minimum of 256 here is not backed by any theory,
                         //     measurement or data, howeve r it is what lcms uses.
-                        //     the maximum number we would need is 65535 because that's the 
+                        //     the maximum number we would need is 65535 because that's the
                         //     accuracy used for computing the pre cache table
                         if (inverted_size < 256)
                                 inverted_size = 256;
@@ -462,9 +543,9 @@
                 } else {
                         uint16_t *inverted;
                         int inverted_size = trc->count;
-                        //XXX: the choice of a minimum of 256 here is not backed by any theory, 
+                        //XXX: the choice of a minimum of 256 here is not backed by any theory,
                         //     measurement or data, howeve r it is what lcms uses.
-                        //     the maximum number we would need is 65535 because that's the 
+                        //     the maximum number we would need is 65535 because that's the
                         //     accuracy used for computing the pre cache table
                         if (inverted_size < 256)
                                 inverted_size = 256;
@@ -517,20 +598,25 @@
 {
         if (trc->type == PARAMETRIC_CURVE_TYPE) {
                 float gamma_table[256];
+                uint16_t gamma_table_uint[256];
                 uint16_t i;
-                uint16_t *output = malloc(sizeof(uint16_t)*256);
-
-                if (!output) {
-                        *output_gamma_lut = NULL;
-                        return;
-                }
+                uint16_t *inverted;
+                int inverted_size = 4096;
 
                 compute_curve_gamma_table_type_parametric(gamma_table, trc->parameter, trc->count);
-                *output_gamma_lut_length = 256;
                 for(i = 0; i < 256; i++) {
-                        output[i] = (uint16_t)(gamma_table[i] * 65535);
+                        gamma_table_uint[i] = (uint16_t)(gamma_table[i] * 65535);
                 }
-                *output_gamma_lut = output;
+
+                //XXX: the choice of a minimum of 256 here is not backed by any theory,
+                //     measurement or data, however it is what lcms uses.
+                //     the maximum number we would need is 65535 because that's the
+                //     accuracy used for computing the pre cache table
+                inverted = invert_lut(gamma_table_uint, 256, inverted_size);
+                if (!inverted)
+                        return;
+                *output_gamma_lut = inverted;
+                *output_gamma_lut_length = inverted_size;
         } else {
                 if (trc->count == 0) {
                         *output_gamma_lut = build_linear_table(4096);
@@ -540,7 +626,7 @@
                         *output_gamma_lut = build_pow_table(gamma, 4096);
                         *output_gamma_lut_length = 4096;
                 } else {
-                        //XXX: the choice of a minimum of 256 here is not backed by any theory, 
+                        //XXX: the choice of a minimum of 256 here is not backed by any theory,
                         //     measurement or data, however it is what lcms uses.
                         *output_gamma_lut_length = trc->count;
                         if (*output_gamma_lut_length < 256)
@@ -552,3 +638,36 @@
 
 }
 
+size_t qcms_profile_get_parametric_curve(qcms_profile *profile, qcms_trc_channel channel, float data[7])
+{
+    static const uint32_t COUNT_TO_LENGTH[5] = {1, 3, 4, 5, 7};
+    struct curveType *curve = NULL;
+    size_t size;
+
+    if (profile->color_space != RGB_SIGNATURE)
+        return 0;
+
+    switch(channel) {
+    case QCMS_TRC_RED:
+        curve = profile->redTRC;
+        break;
+    case QCMS_TRC_GREEN:
+        curve = profile->greenTRC;
+        break;
+    case QCMS_TRC_BLUE:
+        curve = profile->blueTRC;
+        break;
+    default:
+        return 0;
+    }
+
+    if (!curve || curve->type != PARAMETRIC_CURVE_TYPE)
+        return 0;
+
+    size = COUNT_TO_LENGTH[curve->count];
+
+    if (data)
+        memcpy(data, curve->parameter, size * sizeof(float));
+
+    return size;
+}
diff --git a/transform_util.h b/transform_util.h
index 8f358a8..f83477a 100644
--- a/transform_util.h
+++ b/transform_util.h
@@ -31,14 +31,14 @@
 //XXX: could use a bettername
 typedef uint16_t uint16_fract_t;
 
-float lut_interp_linear(double value, uint16_t *table, int length);
-float lut_interp_linear_float(float value, float *table, int length);
-uint16_t lut_interp_linear16(uint16_t input_value, uint16_t *table, int length);
+float lut_interp_linear(double input_value, uint16_t *table, size_t length);
+float lut_interp_linear_float(float input_value, float *table, size_t length);
+uint16_t lut_interp_linear16(uint16_t input_value, uint16_t *table, size_t length);
 
 
 static inline float lerp(float a, float b, float t)
 {
-        return a*(1.f-t) + b*t;
+	return a*(1.f-t) + b*t;
 }
 
 unsigned char clamp_u8(float v);
@@ -55,5 +55,4 @@
 struct matrix matrix_invert(struct matrix mat);
 qcms_bool compute_precache(struct curveType *trc, uint8_t *output);
 
-
 #endif
diff --git a/util/Makefile b/util/Makefile
deleted file mode 100644
index 5adee94..0000000
--- a/util/Makefile
+++ /dev/null
@@ -1,3 +0,0 @@
-LDFLAGS= -Wl,-framework,ApplicationServices
-CFLAGS=-g
-all: colorsync-perf
diff --git a/util/colorsync-perf.c b/util/colorsync-perf.c
deleted file mode 100644
index fb1fd6d..0000000
--- a/util/colorsync-perf.c
+++ /dev/null
@@ -1,52 +0,0 @@
-#include <ApplicationServices/ApplicationServices.h>
-#include <dlfcn.h>
-#include <stdio.h>
-
-#define BITMAP_INFO (kCGBitmapByteOrder32Big | kCGImageAlphaNoneSkipLast)
-
-
-int main(int argc, char **argv) {
-	int width = 256;
-	int height = 256*256;
-	char *input_profile_file = "input.icc";
-	char *output_profile_file = "output.icc";
-	if (argc >= 3) {
-		input_profile_file = argv[1];
-		output_profile_file = argv[2];
-	}
-	CGDataProviderRef input_file = CGDataProviderCreateWithFilename(input_profile_file);
-	CGDataProviderRef output_file = CGDataProviderCreateWithFilename(output_profile_file);
-	float range[] = {0, 1., 0, 1., 0, 1.};
-	CGColorSpaceRef output_profile = CGColorSpaceCreateICCBased(3, range, output_file, NULL);
-	CGColorSpaceRef input_profile = CGColorSpaceCreateICCBased(3, range, input_file, NULL);
-	CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
-
-	CGContextRef cin = CGBitmapContextCreate(NULL, width, height,
-			8, 4*width, input_profile, BITMAP_INFO);
-	CGContextRef cout = CGBitmapContextCreate(NULL, width, height,
-			8, 4*width, output_profile, BITMAP_INFO);
-
-	CGRect rect = {{0,0},{width, height}};
-	CGImageRef copy = CGBitmapContextCreateImage(cin);
-#define LENGTH 256*256*256
-	static unsigned char src[LENGTH*3];
-	static unsigned char qoutput[LENGTH*3];
-	static unsigned char loutput[LENGTH*3];
-	int i,j,k,l=0;
-	for (i=0; i<256; i++) {
-		for (j=0; j<256; j++) {
-			for (k=0; k<256; k++) {
-				src[l++] = i;
-				src[l++] = j;
-				src[l++] = k;
-			}
-		}
-	}
-
-	CGDataProviderRef dp = CGDataProviderCreateWithData(NULL, src, height * width * 3, NULL);
-	CGImageRef ref = CGImageCreate(width, height, 8, 24, width * 3, input_profile, BITMAP_INFO, dp, NULL, 1, kCGRenderingIntentDefault);
-	clock_t qcms_start = clock();
-	CGContextDrawImage(cout, rect, ref);
-	clock_t qcms_time = clock() - qcms_start;
-	printf("ColorSync: %ld\n", qcms_time);
-}