Initial code drop
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5761abc
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+*.o
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..76b303b
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,21 @@
+qcms
+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 
+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.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..40d6885
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,19 @@
+
+#COVERAGE_FLAGS=-fprofile-arcs -ftest-coverage 
+#COVERAGE_FLAGS=
+OPT_FLAGS=-O0
+OPT_FLAGS=
+CFLAGS=-Wall $(OPT_FLAGS) $(COVERAGE_FLAGS) -Wdeclaration-after-statement -ggdb `pkg-config --cflags lcms`
+LDFLAGS=`pkg-config --libs lcms`
+
+QCMS_SRC=iccread.c transform.c
+QCMS_OBJS=iccread.o transform.o
+
+PROGRAMS=profile-gen test test-invalid lcms-compare dump-profile div-test coverage malloc-fail invalid-coverage
+
+all: $(PROGRAMS)
+
+$(PROGRAMS): $(QCMS_OBJS)
+
+clean:
+	rm -f $(PROGRAMS) $(QCMS_OBJS)
diff --git a/README b/README
new file mode 100644
index 0000000..e3d95a3
--- /dev/null
+++ b/README
@@ -0,0 +1,9 @@
+qcms
+====
+
+Quick color management.
+
+Current limitations
+-----------
+- Only supports RGB and Gray colorspaces. e.g. no support for CMYK yet.
+- Only packed RGB and RGBA, K, and KA.
diff --git a/coverage.c b/coverage.c
new file mode 100644
index 0000000..09e0f7f
--- /dev/null
+++ b/coverage.c
@@ -0,0 +1,122 @@
+#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
new file mode 100644
index 0000000..4e4a009
--- /dev/null
+++ b/div-test.c
@@ -0,0 +1,33 @@
+#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
new file mode 100644
index 0000000..5844b38
--- /dev/null
+++ b/dump-profile.c
@@ -0,0 +1,29 @@
+#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));
+		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/iccread.c b/iccread.c
new file mode 100644
index 0000000..c721fbe
--- /dev/null
+++ b/iccread.c
@@ -0,0 +1,785 @@
+//  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.
+
+#include <math.h>
+#include <assert.h>
+#include <stdlib.h>
+#include "qcmsint.h"
+
+//XXX: use a better typename
+typedef uint32_t __be32;
+typedef uint16_t __be16;
+
+#if 0
+not used yet
+/* __builtin_bswap isn't available in older gccs
+ * so open code it for now */
+static __be32 cpu_to_be32(int32_t v)
+{
+#ifdef IS_LITTLE_ENDIAN
+	return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v & 0xff0000) >> 8) | ((v & 0xff000000) >> 24);
+	//return __builtin_bswap32(v);
+	return v;
+#endif
+}
+#endif
+
+static uint32_t be32_to_cpu(__be32 v)
+{
+#ifdef IS_LITTLE_ENDIAN
+	return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v & 0xff0000) >> 8) | ((v & 0xff000000) >> 24);
+	//return __builtin_bswap32(v);
+#else
+	return v;
+#endif
+}
+
+static uint32_t be16_to_cpu(__be16 v)
+{
+#ifdef IS_LITTLE_ENDIAN
+	return ((v & 0xff) << 8) | ((v & 0xff00) >> 8);
+#else
+	return v;
+#endif
+}
+
+/* a wrapper around the memory that we are going to parse
+ * into a qcms_profile */
+struct mem_source
+{
+	const unsigned char *buf;
+	size_t size;
+	qcms_bool valid;
+	const char *invalid_reason;
+};
+
+static void invalid_source(struct mem_source *mem, const char *reason)
+{
+	mem->valid = false;
+	mem->invalid_reason = reason;
+}
+
+static uint32_t read_u32(struct mem_source *mem, size_t offset)
+{
+	if (offset + 4 > mem->size) {
+		invalid_source(mem, "Invalid offset");
+		return 0;
+	} else {
+		return be32_to_cpu(*(__be32*)(mem->buf + offset));
+	}
+}
+
+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));
+	}
+}
+
+static uint8_t read_u8(struct mem_source *mem, size_t offset)
+{
+	if (offset + 1 > mem->size) {
+		invalid_source(mem, "Invalid offset");
+		return 0;
+	} else {
+		return *(uint8_t*)(mem->buf + offset);
+	}
+}
+
+static s15Fixed16Number read_s15Fixed16Number(struct mem_source *mem, size_t offset)
+{
+	return read_u32(mem, offset);
+}
+
+#if 0
+static uInt16Number read_uInt16Number(struct mem_source *mem, size_t offset)
+{
+	return read_u16(mem, offset);
+}
+#endif
+
+#define BAD_VALUE_PROFILE NULL
+#define INVALID_PROFILE NULL
+#define NO_MEM_PROFILE NULL
+
+/* An arbitrary 4MB limit on profile size */
+#define MAX_PROFILE_SIZE 1024*1024*4
+#define MAX_TAG_COUNT 1024
+
+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)
+{
+	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);
+	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)
+		invalid_source(src, "Invalid reserved bytes");
+}
+
+#define INPUT_DEVICE_PROFILE   0x73636e72 // 'scnr'
+#define DISPLAY_DEVICE_PROFILE 0x6d6e7472 // 'mntr'
+#define OUTPUT_DEVICE_PROFILE  0x70727472 // 'prtr'
+#define DEVICE_LINK_PROFILE    0x6c696e6b // 'link'
+#define COLOR_SPACE_PROFILE    0x73706163 // 'spac'
+#define ABSTRACT_PROFILE       0x61627374 // 'abst'
+#define NAMED_COLOR_PROFILE    0x6e6d636c // 'nmcl'
+
+static void read_class_signature(qcms_profile *profile, struct mem_source *mem)
+{
+	profile->class = read_u32(mem, 12);
+	switch (profile->class) {
+		case DISPLAY_DEVICE_PROFILE:
+		case INPUT_DEVICE_PROFILE:
+			break;
+		case OUTPUT_DEVICE_PROFILE:
+		default:
+			invalid_source(mem, "Invalid  Profile/Device Class signature");
+	}
+}
+
+static void read_color_space(qcms_profile *profile, struct mem_source *mem)
+{
+	profile->color_space = read_u32(mem, 16);
+	switch (profile->color_space) {
+		case RGB_SIGNATURE:
+		case GRAY_SIGNATURE:
+			break;
+		default:
+			invalid_source(mem, "Unsupported colorspace");
+	}
+}
+
+struct tag
+{
+	uint32_t signature;
+	uint32_t offset;
+	uint32_t size;
+};
+
+struct tag_index {
+	uint32_t count;
+	struct tag *tags;
+};
+
+static struct tag_index read_tag_table(qcms_profile *profile, struct mem_source *mem)
+{
+	struct tag_index index = {0, NULL};
+	int i;
+
+	index.count = read_u32(mem, 128);
+	if (index.count > MAX_TAG_COUNT) {
+		invalid_source(mem, "max number of tags exceeded");
+		return index;
+	}
+
+	index.tags = malloc(sizeof(struct tag)*index.count);
+	if (index.tags) {
+		for (i = 0; i < index.count; i++) {
+			index.tags[i].signature = read_u32(mem, 128 + 4 + 4*i*3);
+			index.tags[i].offset    = read_u32(mem, 128 + 4 + 4*i*3 + 4);
+			index.tags[i].size      = read_u32(mem, 128 + 4 + 4*i*3 + 8);
+		}
+	}
+
+	return index;
+}
+
+// Checks a profile for obvious inconsistencies and returns
+// 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];
+       unsigned i;
+
+       // Sum the values
+       sum[0] = s15Fixed16Number_to_float(profile->redColorant.X) +
+	       s15Fixed16Number_to_float(profile->greenColorant.X) +
+	       s15Fixed16Number_to_float(profile->blueColorant.X);
+       sum[1] = s15Fixed16Number_to_float(profile->redColorant.Y) +
+	       s15Fixed16Number_to_float(profile->greenColorant.Y) +
+	       s15Fixed16Number_to_float(profile->blueColorant.Y);
+       sum[2] = s15Fixed16Number_to_float(profile->redColorant.Z) +
+	       s15Fixed16Number_to_float(profile->greenColorant.Z) +
+	       s15Fixed16Number_to_float(profile->blueColorant.Z);
+
+       // Build our target vector (see mozilla bug 460629)
+       target[0] = 0.96420;
+       target[1] = 1.00000;
+       target[2] = 0.82491;
+
+       // 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;
+
+       // 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;
+       }
+
+       // All Good
+       return false;
+}
+
+#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
+
+static struct tag *find_tag(struct tag_index index, uint32_t tag_id)
+{
+	int i;
+	struct tag *tag = NULL;
+	for (i = 0; i < index.count; i++) {
+		if (index.tags[i].signature == tag_id) {
+			return &index.tags[i];
+		}
+	}
+	return tag;
+}
+
+#define XYZ_TYPE   0x58595a20 // 'XYZ '
+#define CURVE_TYPE 0x63757276 // 'curv'
+#define LUT16_TYPE 0x6d667432 // 'mft2'
+#define LUT8_TYPE  0x6d667431 // 'mft1'
+
+static struct XYZNumber read_tag_XYZType(struct mem_source *src, struct tag_index index, uint32_t tag_id)
+{
+	struct XYZNumber num = {0};
+	struct tag *tag = find_tag(index, tag_id);
+	if (tag) {
+		uint32_t offset = tag->offset;
+
+		uint32_t type = read_u32(src, offset);
+		if (type != XYZ_TYPE)
+			invalid_source(src, "unexpected type, expected XYZ");
+		num.X = read_s15Fixed16Number(src, offset+8);
+		num.Y = read_s15Fixed16Number(src, offset+12);
+		num.Z = read_s15Fixed16Number(src, offset+16);
+	} else {
+		invalid_source(src, "missing xyztag");
+	}
+	return num;
+}
+
+static struct curveType *read_tag_curveType(struct mem_source *src, struct tag_index index, uint32_t tag_id)
+{
+	struct tag *tag = find_tag(index, tag_id);
+	struct curveType *curve = NULL;
+	if (tag) {
+		uint32_t offset = tag->offset;
+		uint32_t type = read_u32(src, offset);
+		uint32_t count = read_u32(src, offset+8);
+		int i;
+
+		if (type != CURVE_TYPE) {
+			invalid_source(src, "unexpected type, expected CURV");
+			return NULL;
+		}
+
+#define MAX_CURVE_ENTRIES 40000 //arbitrary
+		if (count > MAX_CURVE_ENTRIES) {
+			invalid_source(src, "curve size too large");
+			return NULL;
+		}
+		curve = malloc(sizeof(struct curveType) + sizeof(uInt16Number)*count);
+		if (!curve)
+			return NULL;
+
+		curve->count = count;
+		for (i=0; i<count; i++) {
+			curve->data[i] = read_u16(src, offset + 12 + i *2);
+		}
+	} else {
+		invalid_source(src, "missing curvetag");
+	}
+
+	return curve;
+}
+
+/* This function's not done yet */
+static struct lutType *read_tag_lutType(struct mem_source *src, struct tag_index index, uint32_t tag_id)
+{
+	struct tag *tag = find_tag(index, tag_id);
+	uint32_t offset = tag->offset;
+	uint32_t type = read_u32(src, offset);
+	uint16_t num_input_table_entries;
+	uint16_t num_output_table_entries;
+	uint8_t in_chan, grid_points, out_chan;
+	uint32_t clut_size;
+	struct lutType *lut;
+	int i;
+
+	num_input_table_entries  = read_u16(src, offset + 48);
+	num_output_table_entries = read_u16(src, offset + 50);
+
+	in_chan     = read_u8(src, offset + 8);
+	out_chan    = read_u8(src, offset + 9);
+	grid_points = read_u8(src, offset + 10);
+
+	if (!src->valid)
+		return NULL;
+
+	clut_size = in_chan * grid_points * out_chan;
+#define MAX_CLUT_SIZE 10000 // arbitrary
+	if (clut_size > MAX_CLUT_SIZE) {
+		return NULL;
+	}
+
+	if (type != LUT16_TYPE && type != LUT8_TYPE)
+		return NULL;
+
+	lut = malloc(sizeof(struct lutType) + (clut_size + num_input_table_entries + num_output_table_entries)*sizeof(uint8_t));
+	if (!lut)
+		return NULL;
+	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->e00 = read_s15Fixed16Number(src, offset+12);
+	lut->e01 = read_s15Fixed16Number(src, offset+16);
+	lut->e02 = read_s15Fixed16Number(src, offset+20);
+	lut->e10 = read_s15Fixed16Number(src, offset+24);
+	lut->e11 = read_s15Fixed16Number(src, offset+28);
+	lut->e12 = read_s15Fixed16Number(src, offset+32);
+	lut->e20 = read_s15Fixed16Number(src, offset+36);
+	lut->e21 = read_s15Fixed16Number(src, offset+40);
+	lut->e22 = read_s15Fixed16Number(src, offset+44);
+
+	//TODO: finish up
+	for (i = 0; i < lut->num_input_table_entries; i++) {
+	}
+	return lut;
+}
+
+static void read_rendering_intent(qcms_profile *profile, struct mem_source *src)
+{
+	profile->rendering_intent = read_u32(src, 64);
+	switch (profile->rendering_intent) {
+		case QCMS_INTENT_PERCEPTUAL:
+		case QCMS_INTENT_SATURATION:
+		case QCMS_INTENT_RELATIVE_COLORIMETRIC:
+		case QCMS_INTENT_ABSOLUTE_COLORIMETRIC:
+			break;
+		default:
+			invalid_source(src, "unknown rendering intent");
+	}
+}
+
+qcms_profile *qcms_profile_create(void)
+{
+	return calloc(sizeof(qcms_profile), 1);
+}
+
+/* build sRGB gamma table */
+/* based on cmsBuildParametricGamma() */
+static uint16_t *build_sRGB_gamma_table(int num_entries)
+{
+	int i;
+	/* taken from lcms: Build_sRGBGamma() */
+	double gamma = 2.4;
+	double a = 1./1.055;
+	double b = 0.055/1.055;
+	double c = 1./12.92;
+	double d = 0.04045;
+
+	uint16_t *table = malloc(sizeof(uint16_t) * num_entries);
+	if (!table)
+		return NULL;
+
+	for (i=0; i<num_entries; i++) {
+		double x = (double)i / (num_entries-1);
+		double y, output;
+		// IEC 61966-2.1 (sRGB)
+		// Y = (aX + b)^Gamma | X >= d
+		// Y = cX             | X < d
+		if (x >= d) {
+			double e = (a*x + b);
+			if (e > 0)
+				y = pow(e, gamma);
+			else
+				y = 0;
+		} else {
+			y = c*x;
+		}
+
+		// Saturate -- this could likely move to a separate function
+		output = y * 65535. + .5;
+		if (output > 65535.)
+			output = 65535;
+		if (output < 0)
+			output = 0;
+		table[i] = (uint16_t)floor(output);
+	}
+	return table;
+}
+
+static struct curveType *curve_from_table(uint16_t *table, int num_entries)
+{
+	struct curveType *curve;
+	int i;
+	curve = malloc(sizeof(struct curveType) + sizeof(uInt16Number)*num_entries);
+	if (!curve)
+		return NULL;
+	curve->count = num_entries;
+	for (i = 0; i < num_entries; i++) {
+		curve->data[i] = table[i];
+	}
+	return curve;
+}
+
+static uint16_t float_to_u8Fixed8Number(float a)
+{
+	if (a > (255. + 255./256))
+		return 0xffff;
+	else if (a < 0.)
+		return 0;
+	else
+		return floor(a*256. + .5);
+}
+
+static struct curveType *curve_from_gamma(float gamma)
+{
+	struct curveType *curve;
+	int num_entries = 1;
+	curve = malloc(sizeof(struct curveType) + sizeof(uInt16Number)*num_entries);
+	if (!curve)
+		return NULL;
+	curve->count = num_entries;
+	curve->data[0] = float_to_u8Fixed8Number(gamma);
+	return curve;
+}
+
+static void qcms_profile_fini(qcms_profile *profile)
+{
+	free(profile->redTRC);
+	free(profile->blueTRC);
+	free(profile->greenTRC);
+	free(profile->grayTRC);
+	free(profile);
+}
+
+//XXX: it would be nice if we had a way of ensuring
+// everything in a profile was initialized regardless of how it was created
+
+//XXX: should this also be taking a black_point?
+/* similar to CGColorSpaceCreateCalibratedRGB */
+qcms_profile* qcms_profile_create_rgb_with_gamma(
+		qcms_CIE_xyY white_point,
+		qcms_CIE_xyYTRIPLE primaries,
+		float gamma)
+{
+	qcms_profile* profile = qcms_profile_create();
+	if (!profile)
+		return NO_MEM_PROFILE;
+
+	//XXX: should store the whitepoint
+	if (!set_rgb_colorants(profile, white_point, primaries)) {
+		qcms_profile_fini(profile);
+		return INVALID_PROFILE;
+	}
+
+	profile->redTRC = curve_from_gamma(gamma);
+	profile->blueTRC = curve_from_gamma(gamma);
+	profile->greenTRC = curve_from_gamma(gamma);
+
+	if (!profile->redTRC || !profile->blueTRC || !profile->greenTRC) {
+		qcms_profile_fini(profile);
+		return NO_MEM_PROFILE;
+	}
+	profile->class = DISPLAY_DEVICE_PROFILE;
+	profile->rendering_intent = QCMS_INTENT_PERCEPTUAL;
+	profile->color_space = RGB_SIGNATURE;
+	return profile;
+}
+
+qcms_profile* qcms_profile_create_rgb_with_table(
+		qcms_CIE_xyY white_point,
+		qcms_CIE_xyYTRIPLE primaries,
+		uint16_t *table, int num_entries)
+{
+	qcms_profile* profile = qcms_profile_create();
+	if (!profile)
+		return NO_MEM_PROFILE;
+
+	//XXX: should store the whitepoint
+	if (!set_rgb_colorants(profile, white_point, primaries)) {
+		qcms_profile_fini(profile);
+		return INVALID_PROFILE;
+	}
+
+	profile->redTRC = curve_from_table(table, num_entries);
+	profile->blueTRC = curve_from_table(table, num_entries);
+	profile->greenTRC = curve_from_table(table, num_entries);
+
+	if (!profile->redTRC || !profile->blueTRC || !profile->greenTRC) {
+		qcms_profile_fini(profile);
+		return NO_MEM_PROFILE;
+	}
+	profile->class = DISPLAY_DEVICE_PROFILE;
+	profile->rendering_intent = QCMS_INTENT_PERCEPTUAL;
+	profile->color_space = RGB_SIGNATURE;
+	return profile;
+}
+
+/* from lcms: cmsWhitePointFromTemp */
+/* tempK must be >= 4000. and <= 25000.
+ * similar to argyll: icx_DTEMP2XYZ() */
+static qcms_CIE_xyY white_point_from_temp(int temp_K)
+{
+	qcms_CIE_xyY white_point;
+	double x, y;
+	double T, T2, T3;
+	// double M1, M2;
+
+	// No optimization provided.
+	T = temp_K;
+	T2 = T*T;            // Square
+	T3 = T2*T;           // Cube
+
+	// For correlated color temperature (T) between 4000K and 7000K:
+	if (T >= 4000. && T <= 7000.) {
+		x = -4.6070*(1E9/T3) + 2.9678*(1E6/T2) + 0.09911*(1E3/T) + 0.244063;
+	} else {
+		// or for correlated color temperature (T) between 7000K and 25000K:
+		if (T > 7000.0 && T <= 25000.0) {
+			x = -2.0064*(1E9/T3) + 1.9018*(1E6/T2) + 0.24748*(1E3/T) + 0.237040;
+		} else {
+			assert(0 && "invalid temp");
+		}
+	}
+
+	// Obtain y(x)
+
+	y = -3.000*(x*x) + 2.870*x - 0.275;
+
+	// wave factors (not used, but here for futures extensions)
+
+	// M1 = (-1.3515 - 1.7703*x + 5.9114 *y)/(0.0241 + 0.2562*x - 0.7341*y);
+	// M2 = (0.0300 - 31.4424*x + 30.0717*y)/(0.0241 + 0.2562*x - 0.7341*y);
+
+	// Fill white_point struct
+	white_point.x = x;
+	white_point.y = y;
+	white_point.Y = 1.0;
+
+	return white_point;
+}
+
+qcms_profile* qcms_profile_sRGB(void)
+{
+	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}
+	};
+	qcms_CIE_xyY D65;
+
+	D65 = white_point_from_temp(6504);
+
+	table = build_sRGB_gamma_table(1024);
+
+	if (!table)
+		return NO_MEM_PROFILE;
+
+	profile = qcms_profile_create_rgb_with_table(D65, Rec709Primaries, table, 1024);
+	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)
+{
+	uint32_t length;
+	struct mem_source source;
+	struct mem_source *src = &source;
+	struct tag_index index;
+	qcms_profile *profile;
+
+	source.buf = mem;
+	source.size = size;
+	source.valid = true;
+	length = read_u32(src, 0);
+	if (length <= size) {
+		// shrink the area that we can read if appropriate
+		source.size = length;
+	} else {
+		return INVALID_PROFILE;
+	}
+
+	profile = qcms_profile_create();
+	if (!profile)
+		return NO_MEM_PROFILE;
+
+	check_CMM_type_signature(src);
+	check_profile_version(src);
+	read_class_signature(profile, src);
+	read_rendering_intent(profile, src);
+	read_color_space(profile, src);
+	//TODO read rest of profile stuff
+
+	if (!src->valid)
+		goto invalid_profile;
+
+	index = read_tag_table(profile, src);
+	if (!src->valid || !index.tags)
+		goto invalid_tag_table;
+
+	if (profile->class == DISPLAY_DEVICE_PROFILE || profile->class == INPUT_DEVICE_PROFILE) {
+		if (profile->color_space == RGB_SIGNATURE) {
+
+			profile->redColorant = read_tag_XYZType(src, index, TAG_rXYZ);
+			profile->blueColorant = read_tag_XYZType(src, index, TAG_bXYZ);
+			profile->greenColorant = read_tag_XYZType(src, index, TAG_gXYZ);
+
+			if (!src->valid)
+				goto invalid_tag_table;
+
+			profile->redTRC = read_tag_curveType(src, index, TAG_rTRC);
+			profile->blueTRC = read_tag_curveType(src, index, TAG_bTRC);
+			profile->greenTRC = read_tag_curveType(src, index, TAG_gTRC);
+
+			if (!profile->redTRC || !profile->blueTRC || !profile->greenTRC)
+				goto invalid_tag_table;
+
+		} else if (profile->color_space == GRAY_SIGNATURE) {
+
+			profile->grayTRC = read_tag_curveType(src, index, TAG_kTRC);
+			if (!profile->grayTRC)
+				goto invalid_tag_table;
+
+		} else {
+			goto invalid_tag_table;
+		}
+	} else if (0 && profile->class == OUTPUT_DEVICE_PROFILE) {
+		profile->A2B0 = read_tag_lutType(src, index, TAG_A2B0);
+	} else {
+		goto invalid_tag_table;
+	}
+
+	if (!src->valid)
+		goto invalid_tag_table;
+
+	free(index.tags);
+
+	return profile;
+
+invalid_tag_table:
+	free(index.tags);
+invalid_profile:
+	qcms_profile_fini(profile);
+	return INVALID_PROFILE;
+}
+
+qcms_intent qcms_profile_get_rendering_intent(qcms_profile *profile)
+{
+	return profile->rendering_intent;
+}
+
+icColorSpaceSignature
+qcms_profile_get_color_space(qcms_profile *profile)
+{
+	return profile->color_space;
+}
+
+void qcms_profile_release(qcms_profile *profile)
+{
+	if (profile->output_table_r)
+		precache_release(profile->output_table_r);
+	if (profile->output_table_g)
+		precache_release(profile->output_table_g);
+	if (profile->output_table_b)
+		precache_release(profile->output_table_b);
+
+	qcms_profile_fini(profile);
+}
+
+#include <stdio.h>
+qcms_profile* qcms_profile_from_file(FILE *file)
+{
+	uint32_t length, remaining_length;
+	qcms_profile *profile;
+	size_t read_length;
+	__be32 length_be;
+	void *data;
+
+	fread(&length_be, sizeof(length), 1, file);
+	length = be32_to_cpu(length_be);
+	if (length > MAX_PROFILE_SIZE)
+		return BAD_VALUE_PROFILE;
+
+	/* allocate room for the entire profile */
+	data = malloc(length);
+	if (!data)
+		return NO_MEM_PROFILE;
+
+	/* copy in length to the front so that the buffer will contain the entire profile */
+	*((__be32*)data) = length_be;
+	remaining_length = length - sizeof(length_be);
+
+	/* read the rest profile */
+	read_length = fread((unsigned char*)data + sizeof(length_be), 1, remaining_length, file);
+	if (read_length != remaining_length)
+		return INVALID_PROFILE;
+
+	profile = qcms_profile_from_memory(data, length);
+	free(data);
+	return profile;
+}
+
+qcms_profile* qcms_profile_from_path(const char *path)
+{
+	qcms_profile *profile = NULL;
+	FILE *file = fopen(path, "r");
+	if (file) {
+		profile = qcms_profile_from_file(file);
+		fclose(file);
+	}
+	return profile;
+}
diff --git a/invalid-coverage.c b/invalid-coverage.c
new file mode 100644
index 0000000..312515b
--- /dev/null
+++ b/invalid-coverage.c
@@ -0,0 +1,158 @@
+#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;
+}
+
+
+int main()
+{
+	qcms_profile_release(qcms_profile_sRGB());
+
+	buf = calloc(1500, 1);
+	assert(!qcms_profile_from_memory(buf, 1500));
+	// invalid size
+	write_u32(0, 2500);
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	// proper size
+	write_u32(0, 1500);
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+#define INPUT_DEVICE_PROFILE   0x73636e72 // 'scnr'
+	write_u32(12, INPUT_DEVICE_PROFILE);
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u8(8, 0x3); // invalid major revision
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u8(8, 0x2); // major revision
+	write_u8(9, 0x55); // invalid minor revision
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	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, 1500));
+	write_u8(10, 0); // reserved 1
+
+	write_u8(64, 0x32); // invalid rendering intent
+	assert(!qcms_profile_from_memory(buf, 1500));
+	write_u8(64, 0); // invalid rendering intent
+
+#define RGB_SIGNATURE  0x52474220
+#define GRAY_SIGNATURE 0x47524159
+	write_u32(16, RGB_SIGNATURE);
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(128, 15000); // tag count
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(128, 15); // tag count
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+     #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
+
+	write_u32(128 + 4, TAG_rXYZ); // tag
+	assert(!qcms_profile_from_memory(buf, 1500));
+	write_u32(128 + 4 + 4, 1000); // offset
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(128 + 4 + 4*1*3, TAG_gXYZ); // tag
+	assert(!qcms_profile_from_memory(buf, 1500));
+	write_u32(128 + 4 + 4*1*3 + 4, 1000); // offset
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(128 + 4 + 4*2*3, TAG_bXYZ); // tag
+	assert(!qcms_profile_from_memory(buf, 1500));
+	write_u32(128 + 4 + 4*2*3 + 4, 1000); // offset
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+#define XYZ_TYPE   0x58595a20 // 'XYZ '
+#define CURVE_TYPE 0x63757276 // 'curv'
+#define LUT16_TYPE 0x6d667432 // 'mft2'
+#define LUT8_TYPE  0x6d667431 // 'mft1'
+
+	write_u32(1000, XYZ_TYPE);
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(128 + 4 + 4*3*3, TAG_rTRC); // tag
+	assert(!qcms_profile_from_memory(buf, 1500));
+	write_u32(128 + 4 + 4*3*3 + 4, 1100); // offset
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(128 + 4 + 4*4*3, TAG_gTRC); // tag
+	assert(!qcms_profile_from_memory(buf, 1500));
+	write_u32(128 + 4 + 4*4*3 + 4, 1100); // offset
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(128 + 4 + 4*5*3, TAG_bTRC); // tag
+	assert(!qcms_profile_from_memory(buf, 1500));
+	write_u32(128 + 4 + 4*5*3 + 4, 1100); // offset
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+
+	write_u32(1100, CURVE_TYPE);
+	qcms_profile_release(qcms_profile_from_memory(buf, 1500));
+
+	write_u32(1108, 100000); // curve count
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(1108, 1); // curve count
+	qcms_profile_release(qcms_profile_from_memory(buf, 1500));
+
+	/* test out gray profiles */
+	write_u32(16, GRAY_SIGNATURE);
+	assert(!qcms_profile_from_memory(buf, 1500));
+
+	write_u32(128 + 4 + 4*6*3, TAG_kTRC); // tag
+	assert(!qcms_profile_from_memory(buf, 1500));
+	write_u32(128 + 4 + 4*6*3 + 4, 1100); // offset
+	qcms_profile_release(qcms_profile_from_memory(buf, 1500));
+
+	return 0;
+}
+
diff --git a/lcms-compare.c b/lcms-compare.c
new file mode 100644
index 0000000..69b9bf1
--- /dev/null
+++ b/lcms-compare.c
@@ -0,0 +1,97 @@
+#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);
+	//transform = qcms_create_transform(output_profile, input_profile);
+	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
new file mode 100644
index 0000000..7b9ecf5
--- /dev/null
+++ b/malloc-fail.c
@@ -0,0 +1,132 @@
+#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 white_point = { 0, 0, 1.};
+	qcms_CIE_xyYTRIPLE primaries = { {.9, .3, 1.}, {.2, .4, 1.}, {.7, .4, 1.}};
+
+	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);
+}
+
+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
new file mode 100644
index 0000000..d45e89c
--- /dev/null
+++ b/qcms.h
@@ -0,0 +1,153 @@
+#ifndef QCMS_H
+#define QCMS_H
+
+#ifdef  __cplusplus
+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 */
+typedef enum {
+	QCMS_INTENT_DEFAULT = 0,
+	QCMS_INTENT_PERCEPTUAL = 0,
+	QCMS_INTENT_RELATIVE_COLORIMETRIC = 1,
+	QCMS_INTENT_SATURATION = 2,
+	QCMS_INTENT_ABSOLUTE_COLORIMETRIC = 3
+} qcms_intent;
+
+//XXX: I don't really like the _DATA_ prefix
+typedef enum {
+	QCMS_DATA_RGB_8,
+	QCMS_DATA_RGBA_8,
+	QCMS_DATA_GRAY_8,
+	QCMS_DATA_GRAYA_8
+} qcms_data_type;
+
+/* the names for the following two types are sort of ugly */
+typedef struct
+{
+	double x;
+	double y;
+	double Y;
+} qcms_CIE_xyY;
+
+typedef struct
+{
+	qcms_CIE_xyY red;
+	qcms_CIE_xyY green;
+	qcms_CIE_xyY blue;
+} qcms_CIE_xyYTRIPLE;
+
+qcms_profile* qcms_profile_create_rgb_with_gamma(
+		qcms_CIE_xyY white_point,
+		qcms_CIE_xyYTRIPLE primaries,
+		float gamma);
+
+qcms_profile* qcms_profile_from_memory(const void *mem, size_t size);
+
+qcms_profile* qcms_profile_from_file(FILE *file);
+qcms_profile* qcms_profile_from_path(const char *path);
+qcms_profile* qcms_profile_sRGB(void);
+void qcms_profile_release(qcms_profile *profile);
+
+qcms_bool qcms_profile_is_bogus(qcms_profile *profile);
+qcms_intent qcms_profile_get_rendering_intent(qcms_profile *profile);
+icColorSpaceSignature qcms_profile_get_color_space(qcms_profile *profile);
+
+void qcms_profile_precache_output_transform(qcms_profile *profile);
+
+qcms_transform* qcms_transform_create(
+		qcms_profile *in, qcms_data_type in_type,
+		qcms_profile* out, qcms_data_type out_type,
+		qcms_intent intent);
+
+void qcms_transform_release(qcms_transform *);
+
+void qcms_transform_data(qcms_transform *transform, void *src, void *dest, size_t length);
+
+
+
+#ifdef  __cplusplus
+}
+#endif
+
+#endif
diff --git a/qcmsint.h b/qcmsint.h
new file mode 100644
index 0000000..0fb02e2
--- /dev/null
+++ b/qcmsint.h
@@ -0,0 +1,142 @@
+#include "qcms.h"
+#include "qcmstypes.h"
+
+/* used as a 16bit lookup table for the output transformation.
+ * we refcount them so we only need to have one around per output
+ * profile, instead of duplicating them per transform */
+struct precache_output
+{
+	int ref_count;
+	uint8_t data[65535];
+};
+
+#ifdef _MSC_VER
+#define ALIGN __declspec(align(16))
+#else
+#define ALIGN __attribute__(( aligned (16) ))
+#endif
+
+struct _qcms_transform {
+	float ALIGN matrix[3][4];
+	float *input_gamma_table_r;
+	float *input_gamma_table_g;
+	float *input_gamma_table_b;
+
+	float *input_gamma_table_gray;
+
+	float out_gamma_r;
+	float out_gamma_g;
+	float out_gamma_b;
+
+	float out_gamma_gray;
+
+	uint16_t *output_gamma_lut_r;
+	uint16_t *output_gamma_lut_g;
+	uint16_t *output_gamma_lut_b;
+
+	uint16_t *output_gamma_lut_gray;
+
+	size_t output_gamma_lut_r_length;
+	size_t output_gamma_lut_g_length;
+	size_t output_gamma_lut_b_length;
+
+	size_t output_gamma_lut_gray_length;
+
+	struct precache_output *output_table_r;
+	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);
+};
+
+typedef int32_t s15Fixed16Number;
+typedef uint16_t uInt16Number;
+
+struct XYZNumber {
+	s15Fixed16Number X;
+	s15Fixed16Number Y;
+	s15Fixed16Number Z;
+};
+
+struct curveType {
+	uint32_t count;
+	uInt16Number data[0];
+};
+
+struct lutType {
+	uint8_t num_input_channels;
+	uint8_t num_output_channels;
+	uint8_t num_clut_grid_points;
+
+	s15Fixed16Number e00;
+	s15Fixed16Number e01;
+	s15Fixed16Number e02;
+	s15Fixed16Number e10;
+	s15Fixed16Number e11;
+	s15Fixed16Number e12;
+	s15Fixed16Number e20;
+	s15Fixed16Number e21;
+	s15Fixed16Number e22;
+
+	uint16_t num_input_table_entries;
+	uint16_t num_output_table_entries;
+
+	uint16_t *input_table;
+	uint16_t *clut_table;
+	uint16_t *output_table;
+};
+#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.
+struct tag_value {
+	uint32_t type;
+	union {
+		struct {
+			uint32_t reserved;
+			struct {
+				s15Fixed16Number X;
+				s15Fixed16Number Y;
+				s15Fixed16Number Z;
+			} XYZNumber;
+		} XYZType;
+	};
+}; // I guess we need to pack this?
+#endif
+
+#define RGB_SIGNATURE  0x52474220
+#define GRAY_SIGNATURE 0x47524159
+
+struct _qcms_profile {
+	uint32_t class;
+	uint32_t color_space;
+	qcms_intent rendering_intent;
+	struct XYZNumber redColorant;
+	struct XYZNumber blueColorant;
+	struct XYZNumber greenColorant;
+	struct curveType *redTRC;
+	struct curveType *blueTRC;
+	struct curveType *greenTRC;
+	struct curveType *grayTRC;
+	struct lutType *A2B0;
+
+	struct precache_output *output_table_r;
+	struct precache_output *output_table_g;
+	struct precache_output *output_table_b;
+};
+
+#ifdef _MSC_VER
+#define inline _inline
+#endif
+
+static inline float s15Fixed16Number_to_float(s15Fixed16Number a)
+{
+	return ((int32_t)a)/65536.;
+}
+
+static inline s15Fixed16Number double_to_s15Fixed16Number(double v)
+{
+	return (int32_t)(v*65536);
+}
+
+void precache_release(struct precache_output *p);
+qcms_bool set_rgb_colorants(qcms_profile *profile, qcms_CIE_xyY white_point, qcms_CIE_xyYTRIPLE primaries);
diff --git a/qcmstypes.h b/qcmstypes.h
new file mode 100644
index 0000000..25ffa57
--- /dev/null
+++ b/qcmstypes.h
@@ -0,0 +1,84 @@
+#ifndef QCMS_TYPES_H
+#define QCMS_TYPES_H
+
+#ifdef MOZ_QCMS
+
+#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>
+#else
+typedef PRInt8 int8_t;
+typedef PRUint8 uint8_t;
+typedef PRInt16 int16_t;
+typedef PRUint16 uint16_t;
+typedef PRInt32 int32_t;
+typedef PRUint32 uint32_t;
+typedef PRInt64 int64_t;
+typedef PRUint64 uint64_t;
+
+#ifdef __OS2__
+/* OS/2's stdlib typdefs uintptr_t. So we'll just include that so we don't collide */
+#include <stdlib.h>
+#elif defined(__FreeBSD__)
+/* FreeBSD typedefs uintptr_t in /usr/include/sys/types.h */
+#else
+typedef PRUptrdiff uintptr_t;
+#endif
+#endif
+
+#else // MOZ_QCMS
+
+#if BYTE_ORDER == LITTLE_ENDIAN
+#define IS_LITTLE_ENDIAN
+#elif BYTE_ORDER == BIG_ENDIAN
+#define IS_BIG_ENDIAN
+#endif
+
+/* all of the platforms that we use _MSC_VER on are little endian
+ * so this is sufficient for now */
+#ifdef _MSC_VER
+#define IS_LITTLE_ENDIAN
+#endif
+
+#ifdef __OS2__
+#define IS_LITTLE_ENDIAN
+#endif
+
+#if !defined(IS_LITTLE_ENDIAN) && !defined(IS_BIG_ENDIAN)
+#error Unknown endianess
+#endif
+
+#if defined (_SVR4) || defined (SVR4) || defined (__OpenBSD__) || defined (_sgi) || defined (__sun) || defined (sun) || defined (__digital__)
+#  include <inttypes.h>
+#elif defined (_MSC_VER)
+typedef __int8 int8_t;
+typedef unsigned __int8 uint8_t;
+typedef __int16 int16_t;
+typedef unsigned __int16 uint16_t;
+typedef __int32 int32_t;
+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>
+#else
+#  include <stdint.h>
+#endif
+
+#endif
+
+typedef qcms_bool bool;
+#define true 1
+#define false 0
+
+#endif
diff --git a/sum.h b/sum.h
new file mode 100644
index 0000000..15c949e
--- /dev/null
+++ b/sum.h
@@ -0,0 +1,414 @@
+/*
+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
new file mode 100644
index 0000000..7a1b9a3
--- /dev/null
+++ b/test-invalid.c
@@ -0,0 +1,11 @@
+#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.c b/test.c
new file mode 100644
index 0000000..f9c6955
--- /dev/null
+++ b/test.c
@@ -0,0 +1,51 @@
+#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.c b/transform.c
new file mode 100644
index 0000000..5fa5015
--- /dev/null
+++ b/transform.c
@@ -0,0 +1,1616 @@
+//  qcms
+//  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 
+// 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 <stdlib.h>
+#include <math.h>
+#include <assert.h>
+#include "qcmsint.h"
+
+#if defined(_M_IX86) || defined(__i386__) || defined(__x86_64__) || defined(_M_AMD64)
+#define X86
+#endif
+
+//XXX: could use a bettername
+typedef uint16_t uint16_fract_t;
+
+/* value must be a value between 0 and 1 */
+//XXX: is the above a good restriction to have?
+float lut_interp_linear(double value, uint16_t *table, int length)
+{
+	int upper, lower;
+	value = value * (length - 1);
+	upper = ceil(value);
+	lower = floor(value);
+	//XXX: can we be more performant here?
+	value = table[upper]*(1. - (upper - value)) + table[lower]*(upper - value);
+	/* scale the value */
+	return value * (1./65535.);
+}
+
+/* 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)
+{
+	uint32_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) */
+	uint32_t interp = value % 65535;
+
+	value = (table[upper]*(interp) + table[lower]*(65535 - interp))/65535;
+
+	return value;
+}
+
+void compute_curve_gamma_table_type1(float gamma_table[256], double gamma)
+{
+	unsigned int i;
+	for (i = 0; i < 256; i++) {
+		gamma_table[i] = pow(i/255., gamma);
+	}
+}
+
+void compute_curve_gamma_table_type2(float gamma_table[256], uint16_t *table, int length)
+{
+	unsigned int i;
+	for (i = 0; i < 256; i++) {
+		gamma_table[i] = lut_interp_linear(i/255., table, length);
+	}
+}
+
+void compute_curve_gamma_table_type0(float gamma_table[256])
+{
+	unsigned int i;
+	for (i = 0; i < 256; i++) {
+		gamma_table[i] = i/255.;
+	}
+}
+
+unsigned char clamp_u8(float v)
+{
+	if (v > 255.)
+		return 255;
+	else if (v < 0)
+		return 0;
+	else
+		return floor(v+.5);
+}
+
+struct vector {
+	float v[3];
+};
+
+struct matrix {
+	float m[3][3];
+	bool invalid;
+};
+
+struct vector matrix_eval(struct matrix mat, struct vector v)
+{
+	struct vector result;
+	result.v[0] = mat.m[0][0]*v.v[0] + mat.m[0][1]*v.v[1] + mat.m[0][2]*v.v[2];
+	result.v[1] = mat.m[1][0]*v.v[0] + mat.m[1][1]*v.v[1] + mat.m[1][2]*v.v[2];
+	result.v[2] = mat.m[2][0]*v.v[0] + mat.m[2][1]*v.v[1] + mat.m[2][2]*v.v[2];
+	return result;
+}
+
+//XXX: should probably pass by reference and we could
+//probably reuse this computation in matrix_invert
+float matrix_det(struct matrix mat)
+{
+	float det;
+	det = mat.m[0][0]*mat.m[1][1]*mat.m[2][2] +
+		mat.m[0][1]*mat.m[1][2]*mat.m[2][0] +
+		mat.m[0][2]*mat.m[1][0]*mat.m[2][1] -
+		mat.m[0][0]*mat.m[1][2]*mat.m[2][1] -
+		mat.m[0][1]*mat.m[1][0]*mat.m[2][2] -
+		mat.m[0][2]*mat.m[1][1]*mat.m[2][0];
+	return det;
+}
+
+/* from pixman and cairo and Mathematics for Game Programmers */
+/* lcms uses gauss-jordan elimination with partial pivoting which is
+ * less efficient and not as numerically stable. See Mathematics for
+ * Game Programmers. */
+struct matrix matrix_invert(struct matrix mat)
+{
+	struct matrix dest_mat;
+	int i,j;
+	static int a[3] = { 2, 2, 1 };
+	static int b[3] = { 1, 0, 0 };
+
+	/* inv  (A) = 1/det (A) * adj (A) */
+	float det = matrix_det(mat);
+
+	if (det == 0) {
+		dest_mat.invalid = true;
+	} else {
+		dest_mat.invalid = false;
+	}
+
+	det = 1/det;
+
+	for (j = 0; j < 3; j++) {
+		for (i = 0; i < 3; i++) {
+			double p;
+			int ai = a[i];
+			int aj = a[j];
+			int bi = b[i];
+			int bj = b[j];
+
+			p = mat.m[ai][aj] * mat.m[bi][bj] -
+				mat.m[ai][bj] * mat.m[bi][aj];
+			if (((i + j) & 1) != 0)
+				p = -p;
+
+			dest_mat.m[j][i] = det * p;
+		}
+	}
+	return dest_mat;
+}
+
+struct matrix matrix_identity(void)
+{
+	struct matrix i;
+	i.m[0][0] = 1;
+	i.m[0][1] = 0;
+	i.m[0][2] = 0;
+	i.m[1][0] = 0;
+	i.m[1][1] = 1;
+	i.m[1][2] = 0;
+	i.m[2][0] = 0;
+	i.m[2][1] = 0;
+	i.m[2][2] = 1;
+	i.invalid = false;
+	return i;
+}
+
+static struct matrix matrix_invalid(void)
+{
+	struct matrix inv = matrix_identity();
+	inv.invalid = true;
+	return inv;
+}
+
+
+/* from pixman */
+/* MAT3per... */
+struct matrix matrix_multiply(struct matrix a, struct matrix b)
+{
+	struct matrix result;
+	int dx, dy;
+	int o;
+	for (dy = 0; dy < 3; dy++) {
+		for (dx = 0; dx < 3; dx++) {
+			double v = 0;
+			for (o = 0; o < 3; o++) {
+				v += a.m[dy][o] * b.m[o][dx];
+			}
+			result.m[dy][dx] = v;
+		}
+	}
+	result.invalid = a.invalid || b.invalid;
+	return result;
+}
+
+float u8Fixed8Number_to_float(uint16_t x)
+{
+	// 0x0000 = 0.
+	// 0x0100 = 1.
+	// 0xffff = 255  + 255/256
+	return x/256.;
+}
+
+float *build_input_gamma_table(struct curveType *TRC)
+{
+	float *gamma_table = malloc(sizeof(float)*256);
+	if (gamma_table) {
+		if (TRC->count == 0) {
+			compute_curve_gamma_table_type0(gamma_table);
+		} else if (TRC->count == 1) {
+			compute_curve_gamma_table_type1(gamma_table, u8Fixed8Number_to_float(TRC->data[0]));
+		} else {
+			compute_curve_gamma_table_type2(gamma_table, TRC->data, TRC->count);
+		}
+	}
+	return gamma_table;
+}
+
+struct matrix build_colorant_matrix(qcms_profile *p)
+{
+	struct matrix result;
+	result.m[0][0] = s15Fixed16Number_to_float(p->redColorant.X);
+	result.m[0][1] = s15Fixed16Number_to_float(p->greenColorant.X);
+	result.m[0][2] = s15Fixed16Number_to_float(p->blueColorant.X);
+	result.m[1][0] = s15Fixed16Number_to_float(p->redColorant.Y);
+	result.m[1][1] = s15Fixed16Number_to_float(p->greenColorant.Y);
+	result.m[1][2] = s15Fixed16Number_to_float(p->blueColorant.Y);
+	result.m[2][0] = s15Fixed16Number_to_float(p->redColorant.Z);
+	result.m[2][1] = s15Fixed16Number_to_float(p->greenColorant.Z);
+	result.m[2][2] = s15Fixed16Number_to_float(p->blueColorant.Z);
+	result.invalid = false;
+	return result;
+}
+
+/* The following code is copied nearly directly from lcms.
+ * 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)
+{
+        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)
+        // 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
+	/* I'm not sure that this makes sense, but oh well... */
+        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;
+
+                // Identify if value fall downto 0 or FFFF zone             
+                if (Value == 0) return 0;
+               // if (Value == 0xFFFF) return 0xFFFF;
+
+                // else restrict to valid zone
+
+                a = ((NumZeroes-1) * 0xFFFF) / (length-1);               
+                b = ((length-1 - NumPoles) * 0xFFFF) / (length-1);
+                                                                
+                l = a - 1;
+                r = b + 1;
+        }
+
+
+        // Seems not a degenerated case... apply binary search
+
+        while (r > l) {
+
+                x = (l + r) / 2;
+
+		res = (int) lut_interp_linear16((uint16_fract_t) (x-1), LutTable, length);
+
+                if (res == Value) {
+
+                    // Found exact match. 
+                    
+                    return (uint16_fract_t) (x - 1);
+                }
+
+                if (res > Value) r = x - 1;
+                else l = x + 1;
+        }
+
+        // Not found, should we interpolate?
+
+                
+        // Get surrounding nodes
+        
+        val2 = (length-1) * ((double) (x - 1) / 65535.0);
+
+        cell0 = (int) floor(val2);
+        cell1 = (int) ceil(val2);
+           
+        if (cell0 == cell1) return (uint16_fract_t) x;
+
+        y0 = LutTable[cell0] ;
+        x0 = (65535.0 * cell0) / (length-1); 
+
+        y1 = LutTable[cell1] ;
+        x1 = (65535.0 * cell1) / (length-1);
+
+        a = (y1 - y0) / (x1 - x0);
+        b = y0 - a * x0;
+
+        if (fabs(a) < 0.01) return (uint16_fract_t) x;
+
+        f = ((Value - b) / a);
+
+        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);                        
+        
+}
+
+// Build a White point, primary chromas transfer matrix from RGB to CIE XYZ
+// This is just an approximation, I am not handling all the non-linear
+// aspects of the RGB to XYZ process, and assumming that the gamma correction
+// has transitive property in the tranformation chain.
+//
+// the alghoritm:
+//
+//            - First I build the absolute conversion matrix using
+//              primaries in XYZ. This matrix is next inverted
+//            - Then I eval the source white point across this matrix
+//              obtaining the coeficients of the transformation
+//            - Then, I apply these coeficients to the original matrix
+static struct matrix build_RGB_to_XYZ_transfer_matrix(qcms_CIE_xyY white, qcms_CIE_xyYTRIPLE primrs)
+{
+	struct matrix primaries;
+	struct matrix primaries_invert;
+	struct matrix result;
+	struct vector white_point;
+	struct vector coefs;
+
+	double xn, yn;
+	double xr, yr;
+	double xg, yg;
+	double xb, yb;
+
+	xn = white.x;
+	yn = white.y;
+
+	if (yn == 0.0)
+		return matrix_invalid();
+
+	xr = primrs.red.x;
+	yr = primrs.red.y;
+	xg = primrs.green.x;
+	yg = primrs.green.y;
+	xb = primrs.blue.x;
+	yb = primrs.blue.y;
+
+	primaries.m[0][0] = xr;
+	primaries.m[0][1] = xg;
+	primaries.m[0][2] = xb;
+
+	primaries.m[1][0] = yr;
+	primaries.m[1][1] = yg;
+	primaries.m[1][2] = yb;
+
+	primaries.m[2][0] = 1 - xr - yr;
+	primaries.m[2][1] = 1 - xg - yg;
+	primaries.m[2][2] = 1 - xb - yb;
+	primaries.invalid = false;
+
+	white_point.v[0] = xn/yn;
+	white_point.v[1] = 1.;
+	white_point.v[2] = (1.0-xn-yn)/yn;
+
+	primaries_invert = matrix_invert(primaries);
+
+	coefs = matrix_eval(primaries_invert, white_point);
+
+	result.m[0][0] = coefs.v[0]*xr;
+	result.m[0][1] = coefs.v[1]*xg;
+	result.m[0][2] = coefs.v[2]*xb;
+
+	result.m[1][0] = coefs.v[0]*yr;
+	result.m[1][1] = coefs.v[1]*yg;
+	result.m[1][2] = coefs.v[2]*yb;
+
+	result.m[2][0] = coefs.v[0]*(1.-xr-yr);
+	result.m[2][1] = coefs.v[1]*(1.-xg-yg);
+	result.m[2][2] = coefs.v[2]*(1.-xb-yb);
+	result.invalid = primaries_invert.invalid;
+
+	return result;
+}
+
+struct CIE_XYZ {
+	double X;
+	double Y;
+	double Z;
+};
+
+/* CIE Illuminant D50 */
+static const struct CIE_XYZ D50_XYZ = {
+	0.9642,
+	1.0000,
+	0.8249
+};
+
+/* from lcms: xyY2XYZ()
+ * corresponds to argyll: icmYxy2XYZ() */
+static struct CIE_XYZ xyY2XYZ(qcms_CIE_xyY source)
+{
+	struct CIE_XYZ dest;
+	dest.X = (source.x / source.y) * source.Y;
+	dest.Y = source.Y;
+	dest.Z = ((1 - source.x - source.y) / source.y) * source.Y;
+	return dest;
+}
+
+/* from lcms: ComputeChromaticAdaption */
+// Compute chromatic adaption matrix using chad as cone matrix
+static struct matrix
+compute_chromatic_adaption(struct CIE_XYZ source_white_point,
+                           struct CIE_XYZ dest_white_point,
+                           struct matrix chad)
+{
+	struct matrix chad_inv;
+	struct vector cone_source_XYZ, cone_source_rgb;
+	struct vector cone_dest_XYZ, cone_dest_rgb;
+	struct matrix cone, tmp;
+
+	tmp = chad;
+	chad_inv = matrix_invert(tmp);
+
+	cone_source_XYZ.v[0] = source_white_point.X;
+	cone_source_XYZ.v[1] = source_white_point.Y;
+	cone_source_XYZ.v[2] = source_white_point.Z;
+
+	cone_dest_XYZ.v[0] = dest_white_point.X;
+	cone_dest_XYZ.v[1] = dest_white_point.Y;
+	cone_dest_XYZ.v[2] = dest_white_point.Z;
+
+	cone_source_rgb = matrix_eval(chad, cone_source_XYZ);
+	cone_dest_rgb   = matrix_eval(chad, cone_dest_XYZ);
+
+	cone.m[0][0] = cone_dest_rgb.v[0]/cone_source_rgb.v[0];
+	cone.m[0][1] = 0;
+	cone.m[0][2] = 0;
+	cone.m[1][0] = 0;
+	cone.m[1][1] = cone_dest_rgb.v[1]/cone_source_rgb.v[1];
+	cone.m[1][2] = 0;
+	cone.m[2][0] = 0;
+	cone.m[2][1] = 0;
+	cone.m[2][2] = cone_dest_rgb.v[2]/cone_source_rgb.v[2];
+	cone.invalid = false;
+
+	// Normalize
+	return matrix_multiply(chad_inv, matrix_multiply(cone, chad));
+}
+
+/* from lcms: cmsAdaptionMatrix */
+// Returns the final chrmatic adaptation from illuminant FromIll to Illuminant ToIll
+// Bradford is assumed
+static struct matrix
+adaption_matrix(struct CIE_XYZ source_illumination, struct CIE_XYZ target_illumination)
+{
+	struct matrix lam_rigg = {{ // Bradford matrix
+	                         {  0.8951,  0.2664, -0.1614 },
+	                         { -0.7502,  1.7135,  0.0367 },
+	                         {  0.0389, -0.0685,  1.0296 }
+	                         }};
+	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)
+{
+	struct CIE_XYZ Dn;
+	struct matrix Bradford;
+
+	if (source_white_pt.y == 0.0)
+		return matrix_invalid();
+
+	Dn = xyY2XYZ(source_white_pt);
+
+	Bradford = adaption_matrix(Dn, 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 matrix colorants;
+	colorants = build_RGB_to_XYZ_transfer_matrix(white_point, primaries);
+	colorants = adapt_matrix_to_D50(colorants, white_point);
+
+	if (colorants.invalid)
+		return false;
+
+	/* note: there's a transpose type of operation going on here */
+	profile->redColorant.X = double_to_s15Fixed16Number(colorants.m[0][0]);
+	profile->redColorant.Y = double_to_s15Fixed16Number(colorants.m[1][0]);
+	profile->redColorant.Z = double_to_s15Fixed16Number(colorants.m[2][0]);
+
+	profile->greenColorant.X = double_to_s15Fixed16Number(colorants.m[0][1]);
+	profile->greenColorant.Y = double_to_s15Fixed16Number(colorants.m[1][1]);
+	profile->greenColorant.Z = double_to_s15Fixed16Number(colorants.m[2][1]);
+
+	profile->blueColorant.X = double_to_s15Fixed16Number(colorants.m[0][2]);
+	profile->blueColorant.Y = double_to_s15Fixed16Number(colorants.m[1][2]);
+	profile->blueColorant.Z = double_to_s15Fixed16Number(colorants.m[2][2]);
+
+	return true;
+}
+
+static uint16_t *invert_lut(uint16_t *table, int length)
+{
+	int i;
+	/* for now we invert the lut by creating a lut of the same size
+	 * and attempting to lookup a value for each entry using lut_inverse_interp16 */
+	uint16_t *output = malloc(sizeof(uint16_t)*length);
+	if (!output)
+		return NULL;
+
+	for (i = 0; i < length; i++) {
+		double x = ((double) i * 65535.) / (double) (length - 1);
+		uint16_fract_t input = floor(x + .5);
+		output[i] = lut_inverse_interp16(input, table, length);
+	}
+	return output;
+}
+
+static uint16_t *build_linear_table(int length)
+{
+	int i;
+	uint16_t *output = malloc(sizeof(uint16_t)*length);
+	if (!output)
+		return NULL;
+
+	for (i = 0; i < length; i++) {
+		double x = ((double) i * 65535.) / (double) (length - 1);
+		uint16_fract_t input = floor(x + .5);
+		output[i] = input;
+	}
+	return output;
+}
+
+static uint16_t *build_pow_table(float gamma, int length)
+{
+	int i;
+	uint16_t *output = malloc(sizeof(uint16_t)*length);
+	if (!output)
+		return NULL;
+
+	for (i = 0; i < length; i++) {
+		uint16_fract_t result;
+		double x = ((double) i) / (double) (length - 1);
+		x = pow(x, gamma);
+                //XXX turn this conversion into a function
+		result = floor(x*65535. + .5);
+		output[i] = result;
+	}
+	return output;
+}
+
+static float clamp_float(float a)
+{
+	if (a > 1.)
+		return 1.;
+	else if (a < 0)
+		return 0;
+	else
+		return a;
+}
+
+#if 0
+static void qcms_transform_data_rgb_out_pow(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	float (*mat)[4] = transform->matrix;
+	for (i=0; i<length; i++) {
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+
+		float linear_r = transform->input_gamma_table_r[device_r];
+		float linear_g = transform->input_gamma_table_g[device_g];
+		float linear_b = transform->input_gamma_table_b[device_b];
+
+		float out_linear_r = mat[0][0]*linear_r + mat[1][0]*linear_g + mat[2][0]*linear_b;
+		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;
+
+		float out_device_r = pow(out_linear_r, transform->out_gamma_r);
+		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++ = clamp_u8(255*out_device_r);
+		*dest++ = clamp_u8(255*out_device_g);
+		*dest++ = clamp_u8(255*out_device_b);
+	}
+}
+#endif
+
+static void qcms_transform_data_gray_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	for (i = 0; i < length; i++) {
+		float out_device_r, out_device_g, out_device_b;
+		unsigned char device = *src++;
+
+		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_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++ = clamp_u8(out_device_r*255);
+		*dest++ = clamp_u8(out_device_g*255);
+		*dest++ = clamp_u8(out_device_b*255);
+	}
+}
+
+static void qcms_transform_data_graya_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	for (i = 0; i < length; i++) {
+		float out_device_r, out_device_g, out_device_b;
+		unsigned char device = *src++;
+		unsigned char alpha = *src++;
+
+		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_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++ = clamp_u8(out_device_r*255);
+		*dest++ = clamp_u8(out_device_g*255);
+		*dest++ = clamp_u8(out_device_b*255);
+		*dest++ = alpha;
+	}
+}
+
+
+static void qcms_transform_data_gray_out_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	for (i = 0; i < length; i++) {
+		unsigned char device = *src++;
+		uint16_t gray;
+
+		float linear = transform->input_gamma_table_gray[device];
+
+		/* we could round here... */
+		gray = linear * 65535.;
+
+		*dest++ = transform->output_table_r->data[gray];
+		*dest++ = transform->output_table_g->data[gray];
+		*dest++ = transform->output_table_b->data[gray];
+	}
+}
+
+static void qcms_transform_data_graya_out_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	for (i = 0; i < length; i++) {
+		unsigned char device = *src++;
+		unsigned char alpha = *src++;
+		uint16_t gray;
+
+		float linear = transform->input_gamma_table_gray[device];
+
+		/* we could round here... */
+		gray = linear * 65535.;
+
+		*dest++ = transform->output_table_r->data[gray];
+		*dest++ = transform->output_table_g->data[gray];
+		*dest++ = transform->output_table_b->data[gray];
+		*dest++ = alpha;
+	}
+}
+
+static const ALIGN float floatScale = 65536.0f;
+static const ALIGN float * const floatScaleAddr = &floatScale; // Win32 ASM doesn't know how to take addressOf inline
+
+static const ALIGN float clampMaxValue = ((float) (65536 - 1)) / 65536.0f;
+
+#ifdef X86
+#if 0
+#include <emmintrin.h>
+void qcms_transform_data_rgb_out_lut_sse_intrin(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	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 *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* output = (uint32_t*)input;
+	for (i=0; i<length; i++) {
+		const float *clampMax = &clampMaxValue;
+
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+
+		__m128 xmm1 = _mm_load_ps(mat[0]);
+		__m128 xmm2 = _mm_load_ps(mat[1]);
+		__m128 xmm3 = _mm_load_ps(mat[2]);
+
+		__m128 vec_r = _mm_load_ss(&transform->input_gamma_table_r[device_r]);
+		vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
+		__m128 vec_g = _mm_load_ss(&transform->input_gamma_table_r[device_g]);
+		vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
+		__m128 vec_b = _mm_load_ss(&transform->input_gamma_table_r[device_b]);
+		vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);
+
+		vec_r = _mm_mul_ps(vec_r, xmm1);
+		vec_g = _mm_mul_ps(vec_g, xmm2);
+		vec_b = _mm_mul_ps(vec_b, xmm3);
+
+		vec_r = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
+
+		__m128 max = _mm_load_ss(&clampMax);
+		max = _mm_shuffle_ps(max, max, 0);
+		__m128 min = _mm_setzero_ps();
+
+		vec_r = _mm_max_ps(min, vec_r);
+		vec_r = _mm_min_ps(max, vec_r);
+
+		__m128 scale = _mm_load_ss(&floatScale);
+		scale = _mm_shuffle_ps(scale, scale, 0);
+		__m128 result = _mm_mul_ps(vec_r, scale);
+
+		__m128i out = _mm_cvtps_epi32(result);
+		_mm_store_si128((__m128i*)input, out);
+
+		*dest++ = transform->output_table_r->data[output[0]];
+		*dest++ = transform->output_table_g->data[output[1]];
+		*dest++ = transform->output_table_b->data[output[2]];
+	}
+}
+#endif
+
+#if defined(_MSC_VER) && defined(_M_AMD64)
+#include <emmintrin.h>
+#endif
+
+static void qcms_transform_data_rgb_out_lut_sse(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	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 *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* output = (uint32_t*)input;
+	for (i = 0; i < length; i++) {
+		const float *clampMax = &clampMaxValue;
+
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+
+		input[0] = transform->input_gamma_table_r[device_r];
+		input[1] = transform->input_gamma_table_g[device_g];
+		input[2] = transform->input_gamma_table_b[device_b];
+
+#ifdef __GNUC__
+		__asm(
+                      "movaps (%0), %%xmm1;\n\t"          // Move the first matrix column to xmm1
+                      "movaps 16(%0), %%xmm2;\n\t"        // Move the second matrix column to xmm2
+                      "movaps 32(%0), %%xmm3;\n\t"        // move the third matrix column to xmm3
+                      "movaps (%3), %%xmm0;\n\t"        // Move the vector to xmm0
+
+                                                          // Note - We have to copy and then shuffle because of the weird
+                                                          // semantics of shufps
+                                                          //
+                      "movaps %%xmm0, %%xmm4;\n\t"        // Copy the vector to xmm4
+                      "shufps $0, %%xmm4, %%xmm4;\n\t"    // Shuffle to repeat the first vector element repeated 4 times
+                      "mulps %%xmm4, %%xmm1;\n\t"         // Multiply the first vector element by the first matrix column
+                      "movaps %%xmm0, %%xmm5; \n\t"       // Copy the vector to xmm5
+                      "shufps $0x55, %%xmm5, %%xmm5;\n\t" // Shuffle to repeat the second vector element repeated 4 times
+                      "mulps %%xmm5, %%xmm2;\n\t"         // Multiply the second vector element by the seccond matrix column 
+                      "movaps %%xmm0, %%xmm6;\n\t"        // Copy the vector to xmm6
+                      "shufps $0xAA, %%xmm6, %%xmm6;\n\t" // Shuffle to repeat the third vector element repeated 4 times
+                      "mulps %%xmm6, %%xmm3;\n\t"         // Multiply the third vector element by the third matrix column
+
+                      "addps %%xmm3, %%xmm2;\n\t"         // Sum (second + third) columns
+                      "addps %%xmm2, %%xmm1;\n\t"         // Sum ((second + third) + first) columns
+
+                      "movss (%1), %%xmm7;\n\t"        // load the floating point representation of 65535/65536 
+                      "shufps $0, %%xmm7, %%xmm7;\n\t" // move it into all of the four slots
+                      "minps %%xmm7, %%xmm1;\n\t"      // clamp the vector to 1.0 max
+                      "xorps %%xmm6, %%xmm6;\n\t"       // get us cleared bitpatern, which is 0.0f
+                      "maxps %%xmm6, %%xmm1;\n\t"      // clamp the vector to 0.0 min
+                      "movss (%2), %%xmm5;\n\t"        // load the floating point scale factor
+                      "shufps $0, %%xmm5, %%xmm5;\n\t" // put it in all four slots
+                      "mulps %%xmm5, %%xmm1;\n\t"      // multiply by the scale factor
+                      "cvtps2dq %%xmm1, %%xmm1;\n\t"   // convert to integers
+                      "movdqa %%xmm1, (%3);\n\t"       // store
+
+                      : 
+                      : "r" (mat), "r" (clampMax), "r" (&floatScale), "r" (input)
+                      : "memory"
+/* older versions of gcc don't know about these registers so only include them as constraints
+   if gcc knows about them */
+#ifdef __SSE2__
+                        , "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7"
+#endif
+                      );
+#elif defined(_MSC_VER) && defined(_M_IX86)
+                __asm {
+                      mov      eax, mat
+                      mov      ecx, clampMax
+                      mov      edx, floatScaleAddr
+		      mov      ebx, input
+
+                      movaps   xmm1, [eax]
+                      movaps   xmm2, [eax + 16]
+                      movaps   xmm3, [eax + 32]
+                      movaps   xmm0, [ebx]
+
+                      movaps   xmm4, xmm0
+                      shufps   xmm4, xmm4, 0
+                      mulps    xmm1, xmm4
+                      movaps   xmm5, xmm0
+                      shufps   xmm5, xmm5, 0x55
+                      mulps    xmm2, xmm5
+                      movaps   xmm6, xmm0
+                      shufps   xmm6, xmm6, 0xAA
+                      mulps    xmm3, xmm6
+
+                      addps    xmm2, xmm3
+                      addps    xmm1, xmm2
+
+                      movss    xmm7, [ecx]
+                      shufps   xmm7, xmm7, 0
+                      minps    xmm1, xmm7
+                      xorps    xmm6, xmm6
+                      maxps    xmm1, xmm6
+                      movss    xmm5, [edx]
+                      shufps   xmm5, xmm5, 0
+                      mulps    xmm1, xmm5
+                      cvtps2dq xmm1, xmm1
+                      movdqa   [ebx], xmm1
+                }
+#elif defined(_MSC_VER) && defined(_M_AMD64)
+                {
+                        __m128 xmm0, xmm1, xmm2, xmm3, xmm5, xmm6, xmm7;
+
+                        xmm1 = _mm_load_ps((__m128*)mat);
+                        xmm2 = _mm_load_ps(((__m128*)mat) + 1);
+                        xmm3 = _mm_load_ps(((__m128*)mat) + 2);
+                        xmm0 = _mm_load_ps((__m128*)input);
+
+                        xmm1 = _mm_mul_ps(xmm1, _mm_shuffle_ps(xmm0, xmm0, _MM_SHUFFLE(0,0,0,0)));
+                        xmm2 = _mm_mul_ps(xmm2, _mm_shuffle_ps(xmm0, xmm0, _MM_SHUFFLE(1,1,1,1)));
+                        xmm3 = _mm_mul_ps(xmm3, _mm_shuffle_ps(xmm0, xmm0, _MM_SHUFFLE(2,2,2,2)));
+
+                        xmm1 = _mm_add_ps(xmm1, _mm_add_ps(xmm2, xmm3));
+
+                        xmm7 = _mm_load_ss(clampMax);
+                        xmm7 = _mm_shuffle_ps(xmm7, xmm7, _MM_SHUFFLE(0,0,0,0));
+                        xmm1 = _mm_min_ps(xmm1, xmm7);
+                        xmm6 = _mm_xor_ps(xmm6, xmm6);
+                        xmm1 = _mm_max_ps(xmm1, xmm6);
+                        xmm5 = _mm_load_ss(&floatScale);
+                        xmm5 = _mm_shuffle_ps(xmm5, xmm5, _MM_SHUFFLE(0,0,0,0));
+                        xmm1 = _mm_mul_ps(xmm1, xmm5);
+                        _mm_store_si128((__m128i*)input, _mm_cvtps_epi32(xmm1));
+                }
+#else
+#error "Unknown platform"
+#endif
+
+		*dest++ = transform->output_table_r->data[output[0]];
+		*dest++ = transform->output_table_g->data[output[1]];
+		*dest++ = transform->output_table_b->data[output[2]];
+	}
+}
+
+static void qcms_transform_data_rgba_out_lut_sse(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	float (*mat)[4] = transform->matrix;
+        char input_back[32];
+	/* align input on 16 byte boundary */
+        float *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* output = (uint32_t*)input;
+	for (i = 0; i < length; i++) {
+		const float *clampMax = &clampMaxValue;
+
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+		unsigned char alpha = *src++;
+
+		input[0] = transform->input_gamma_table_r[device_r];
+		input[1] = transform->input_gamma_table_g[device_g];
+		input[2] = transform->input_gamma_table_b[device_b];
+
+#ifdef __GNUC__
+		__asm(
+                      "movaps (%0), %%xmm1;\n\t"          // Move the first matrix column to xmm1
+                      "movaps 16(%0), %%xmm2;\n\t"        // Move the second matrix column to xmm2
+                      "movaps 32(%0), %%xmm3;\n\t"        // move the third matrix column to xmm3
+                      "movaps (%3), %%xmm0;\n\t"        // Move the vector to xmm0
+
+                                                          // Note - We have to copy and then shuffle because of the weird
+                                                          // semantics of shufps
+                                                          //
+                      "movaps %%xmm0, %%xmm4;\n\t"        // Copy the vector to xmm4
+                      "shufps $0, %%xmm4, %%xmm4;\n\t"    // Shuffle to repeat the first vector element repeated 4 times
+                      "mulps %%xmm4, %%xmm1;\n\t"         // Multiply the first vector element by the first matrix column
+                      "movaps %%xmm0, %%xmm5; \n\t"       // Copy the vector to xmm5
+                      "shufps $0x55, %%xmm5, %%xmm5;\n\t" // Shuffle to repeat the second vector element repeated 4 times
+                      "mulps %%xmm5, %%xmm2;\n\t"         // Multiply the second vector element by the seccond matrix column 
+                      "movaps %%xmm0, %%xmm6;\n\t"        // Copy the vector to xmm6
+                      "shufps $0xAA, %%xmm6, %%xmm6;\n\t" // Shuffle to repeat the third vector element repeated 4 times
+                      "mulps %%xmm6, %%xmm3;\n\t"         // Multiply the third vector element by the third matrix column
+
+                      "addps %%xmm3, %%xmm2;\n\t"         // Sum (second + third) columns
+                      "addps %%xmm2, %%xmm1;\n\t"         // Sum ((second + third) + first) columns
+
+                      "movss (%1), %%xmm7;\n\t"        // load the floating point representation of 65535/65536 
+                      "shufps $0, %%xmm7, %%xmm7;\n\t" // move it into all of the four slots
+                      "minps %%xmm7, %%xmm1;\n\t"      // clamp the vector to 1.0 max
+                      "xorps %%xmm6, %%xmm6;\n\t"       // get us cleared bitpatern, which is 0.0f
+                      "maxps %%xmm6, %%xmm1;\n\t"      // clamp the vector to 0.0 min
+                      "movss (%2), %%xmm5;\n\t"        // load the floating point scale factor
+                      "shufps $0, %%xmm5, %%xmm5;\n\t" // put it in all four slots
+                      "mulps %%xmm5, %%xmm1;\n\t"      // multiply by the scale factor
+                      "cvtps2dq %%xmm1, %%xmm1;\n\t"   // convert to integers
+                      "movdqa %%xmm1, (%3);\n\t"       // store
+
+                      : 
+                      : "r" (mat), "r" (clampMax), "r" (&floatScale), "r" (input)
+                      : "memory"
+/* older versions of gcc don't know about these registers so only include them as constraints
+   if gcc knows about them */
+#ifdef __SSE2__
+                        , "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7"
+#endif
+                      );
+#elif defined(_MSC_VER) && defined(_M_IX86)
+                __asm {
+                      mov      eax, mat
+                      mov      ecx, clampMax
+                      mov      edx, floatScaleAddr
+		      mov      ebx, input
+
+                      movaps   xmm1, [eax]
+                      movaps   xmm2, [eax + 16]
+                      movaps   xmm3, [eax + 32]
+                      movaps   xmm0, [ebx]
+
+                      movaps   xmm4, xmm0
+                      shufps   xmm4, xmm4, 0
+                      mulps    xmm1, xmm4
+                      movaps   xmm5, xmm0
+                      shufps   xmm5, xmm5, 0x55
+                      mulps    xmm2, xmm5
+                      movaps   xmm6, xmm0
+                      shufps   xmm6, xmm6, 0xAA
+                      mulps    xmm3, xmm6
+
+                      addps    xmm2, xmm3
+                      addps    xmm1, xmm2
+
+                      movss    xmm7, [ecx]
+                      shufps   xmm7, xmm7, 0
+                      minps    xmm1, xmm7
+                      xorps    xmm6, xmm6
+                      maxps    xmm1, xmm6
+                      movss    xmm5, [edx]
+                      shufps   xmm5, xmm5, 0
+                      mulps    xmm1, xmm5
+                      cvtps2dq xmm1, xmm1
+                      movdqa   [ebx], xmm1
+                }
+#elif defined(_MSC_VER) && defined(_M_AMD64)
+                {
+                        __m128 xmm0, xmm1, xmm2, xmm3, xmm5, xmm6, xmm7;
+
+                        xmm1 = _mm_load_ps((__m128*)mat);
+                        xmm2 = _mm_load_ps(((__m128*)mat) + 1);
+                        xmm3 = _mm_load_ps(((__m128*)mat) + 2);
+                        xmm0 = _mm_load_ps((__m128*)input);
+
+                        xmm1 = _mm_mul_ps(xmm1, _mm_shuffle_ps(xmm0, xmm0, _MM_SHUFFLE(0,0,0,0)));
+                        xmm2 = _mm_mul_ps(xmm2, _mm_shuffle_ps(xmm0, xmm0, _MM_SHUFFLE(1,1,1,1)));
+                        xmm3 = _mm_mul_ps(xmm3, _mm_shuffle_ps(xmm0, xmm0, _MM_SHUFFLE(2,2,2,2)));
+
+                        xmm1 = _mm_add_ps(xmm1, _mm_add_ps(xmm2, xmm3));
+
+                        xmm7 = _mm_load_ss(clampMax);
+                        xmm7 = _mm_shuffle_ps(xmm7, xmm7, _MM_SHUFFLE(0,0,0,0));
+                        xmm1 = _mm_min_ps(xmm1, xmm7);
+                        xmm6 = _mm_xor_ps(xmm6, xmm6);
+                        xmm1 = _mm_max_ps(xmm1, xmm6);
+                        xmm5 = _mm_load_ss(&floatScale);
+                        xmm5 = _mm_shuffle_ps(xmm5, xmm5, _MM_SHUFFLE(0,0,0,0));
+                        xmm1 = _mm_mul_ps(xmm1, xmm5);
+                        _mm_store_si128((__m128i*)input, _mm_cvtps_epi32(xmm1));
+                }
+#else
+#error "Unknown platform"
+#endif
+
+		*dest++ = transform->output_table_r->data[output[0]];
+		*dest++ = transform->output_table_g->data[output[1]];
+		*dest++ = transform->output_table_b->data[output[2]];
+		*dest++ = alpha;
+	}
+}
+#endif
+
+static void qcms_transform_data_rgb_out_lut_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	float (*mat)[4] = transform->matrix;
+	for (i = 0; i < length; i++) {
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+		uint16_t r, g, b;
+
+		float linear_r = transform->input_gamma_table_r[device_r];
+		float linear_g = transform->input_gamma_table_g[device_g];
+		float linear_b = transform->input_gamma_table_b[device_b];
+
+		float out_linear_r = mat[0][0]*linear_r + mat[1][0]*linear_g + mat[2][0]*linear_b;
+		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;
+
+		out_linear_r = clamp_float(out_linear_r);
+		out_linear_g = clamp_float(out_linear_g);
+		out_linear_b = clamp_float(out_linear_b);
+
+		/* we could round here... */
+		r = out_linear_r * 65535.;
+		g = out_linear_g * 65535.;
+		b = out_linear_b * 65535.;
+
+		*dest++ = transform->output_table_r->data[r];
+		*dest++ = transform->output_table_g->data[g];
+		*dest++ = transform->output_table_b->data[b];
+	}
+}
+
+static void qcms_transform_data_rgba_out_lut_precache(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	float (*mat)[4] = transform->matrix;
+	for (i = 0; i < length; i++) {
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+		unsigned char alpha = *src++;
+		uint16_t r, g, b;
+
+		float linear_r = transform->input_gamma_table_r[device_r];
+		float linear_g = transform->input_gamma_table_g[device_g];
+		float linear_b = transform->input_gamma_table_b[device_b];
+
+		float out_linear_r = mat[0][0]*linear_r + mat[1][0]*linear_g + mat[2][0]*linear_b;
+		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;
+
+		out_linear_r = clamp_float(out_linear_r);
+		out_linear_g = clamp_float(out_linear_g);
+		out_linear_b = clamp_float(out_linear_b);
+
+		/* we could round here... */
+		r = out_linear_r * 65535.;
+		g = out_linear_g * 65535.;
+		b = out_linear_b * 65535.;
+
+		*dest++ = transform->output_table_r->data[r];
+		*dest++ = transform->output_table_g->data[g];
+		*dest++ = transform->output_table_b->data[b];
+		*dest++ = alpha;
+	}
+}
+
+static void qcms_transform_data_rgb_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	float (*mat)[4] = transform->matrix;
+	for (i = 0; i < length; i++) {
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+		float out_device_r, out_device_g, out_device_b;
+
+		float linear_r = transform->input_gamma_table_r[device_r];
+		float linear_g = transform->input_gamma_table_g[device_g];
+		float linear_b = transform->input_gamma_table_b[device_b];
+
+		float out_linear_r = mat[0][0]*linear_r + mat[1][0]*linear_g + mat[2][0]*linear_b;
+		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;
+
+		out_linear_r = clamp_float(out_linear_r);
+		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, transform->output_gamma_lut_r, transform->output_gamma_lut_r_length);
+		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, transform->output_gamma_lut_b, transform->output_gamma_lut_b_length);
+
+		*dest++ = clamp_u8(out_device_r*255);
+		*dest++ = clamp_u8(out_device_g*255);
+		*dest++ = clamp_u8(out_device_b*255);
+	}
+}
+
+static void qcms_transform_data_rgba_out_lut(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	float (*mat)[4] = transform->matrix;
+	for (i = 0; i < length; i++) {
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+		unsigned char alpha = *src++;
+		float out_device_r, out_device_g, out_device_b;
+
+		float linear_r = transform->input_gamma_table_r[device_r];
+		float linear_g = transform->input_gamma_table_g[device_g];
+		float linear_b = transform->input_gamma_table_b[device_b];
+
+		float out_linear_r = mat[0][0]*linear_r + mat[1][0]*linear_g + mat[2][0]*linear_b;
+		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;
+
+		out_linear_r = clamp_float(out_linear_r);
+		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, transform->output_gamma_lut_r, transform->output_gamma_lut_r_length);
+		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, transform->output_gamma_lut_b, transform->output_gamma_lut_b_length);
+
+		*dest++ = clamp_u8(out_device_r*255);
+		*dest++ = clamp_u8(out_device_g*255);
+		*dest++ = clamp_u8(out_device_b*255);
+		*dest++ = alpha;
+	}
+}
+
+#if 0
+static void qcms_transform_data_rgb_out_linear(qcms_transform *transform, unsigned char *src, unsigned char *dest, size_t length)
+{
+	int i;
+	float (*mat)[4] = transform->matrix;
+	for (i = 0; i < length; i++) {
+		unsigned char device_r = *src++;
+		unsigned char device_g = *src++;
+		unsigned char device_b = *src++;
+
+		float linear_r = transform->input_gamma_table_r[device_r];
+		float linear_g = transform->input_gamma_table_g[device_g];
+		float linear_b = transform->input_gamma_table_b[device_b];
+
+		float out_linear_r = mat[0][0]*linear_r + mat[1][0]*linear_g + mat[2][0]*linear_b;
+		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);
+	}
+}
+#endif
+
+static struct precache_output *precache_reference(struct precache_output *p)
+{
+	p->ref_count++;
+	return p;
+}
+
+static struct precache_output *precache_create()
+{
+	struct precache_output *p = malloc(sizeof(struct precache_output));
+	if (p)
+		p->ref_count = 1;
+	return p;
+}
+
+void precache_release(struct precache_output *p)
+{
+	if (--p->ref_count == 0) {
+		free(p);
+	}
+}
+
+#ifdef HAS_POSIX_MEMALIGN
+static qcms_transform *transform_alloc(void)
+{
+	qcms_transform *t;
+	if (!posix_memalign(&t, 16, sizeof(*t))) {
+		return t;
+	} else {
+		return NULL;
+	}
+}
+static void transform_free(qcms_transform *t)
+{
+	free(t);
+}
+#else
+static qcms_transform *transform_alloc(void)
+{
+	/* transform needs to be aligned on a 16byte boundrary */
+	char *original_block = calloc(sizeof(qcms_transform) + sizeof(void*) + 16, 1);
+	/* make room for a pointer to the block returned by calloc */
+	void *transform_start = original_block + sizeof(void*);
+	/* align transform_start */
+	qcms_transform *transform_aligned = (qcms_transform*)(((uintptr_t)transform_start + 15) & ~0xf);
+
+	/* store a pointer to the block returned by calloc so that we can free it later */
+	void **(original_block_ptr) = (void**)transform_aligned;
+	if (!original_block)
+		return NULL;
+	original_block_ptr--;
+	*original_block_ptr = original_block;
+
+	return transform_aligned;
+}
+static void transform_free(qcms_transform *t)
+{
+	/* get at the pointer to the unaligned block returned by calloc */
+	void **p = (void**)t;
+	p--;
+	free(*p);
+}
+#endif
+
+void qcms_transform_release(qcms_transform *t)
+{
+	/* ensure we only free the gamma tables once even if there are
+	 * multiple references to the same data */
+
+	if (t->output_table_r)
+		precache_release(t->output_table_r);
+	if (t->output_table_g)
+		precache_release(t->output_table_g);
+	if (t->output_table_b)
+		precache_release(t->output_table_b);
+
+	free(t->input_gamma_table_r);
+	if (t->input_gamma_table_g != t->input_gamma_table_r)
+		free(t->input_gamma_table_g);
+	if (t->input_gamma_table_g != t->input_gamma_table_r &&
+	    t->input_gamma_table_g != t->input_gamma_table_b)
+		free(t->input_gamma_table_b);
+
+	free(t->input_gamma_table_gray);
+
+	free(t->output_gamma_lut_r);
+	free(t->output_gamma_lut_g);
+	free(t->output_gamma_lut_b);
+
+	transform_free(t);
+}
+
+static void compute_precache_pow(uint8_t *output, float gamma)
+{
+	uint32_t v = 0;
+	for (v = 0; v <= 0xffff; v++) {
+		//XXX: don't do integer/float conversion... and round?
+		output[v] = 255. * pow(v/65535., gamma);
+	}
+}
+
+void compute_precache_lut(uint8_t *output, uint16_t *table, int length)
+{
+	uint32_t v = 0;
+	for (v = 0; v <= 0xffff; v++) {
+		//XXX: don't do integer/float conversion... round?
+		output[v] = lut_interp_linear16(v, table, length) >> 8;
+	}
+}
+
+void compute_precache_linear(uint8_t *output)
+{
+	uint32_t v = 0;
+	for (v = 0; v <= 0xffff; v++) {
+		//XXX: round?
+		output[v] = v >> 8;
+	}
+}
+
+qcms_bool compute_precache(struct curveType *trc, uint8_t *output)
+{
+	if (trc->count == 0) {
+		compute_precache_linear(output);
+	} else if (trc->count == 1) {
+		compute_precache_pow(output, 1./u8Fixed8Number_to_float(trc->data[0]));
+	} else {
+		uint16_t *inverted = invert_lut(trc->data, trc->count);
+		if (!inverted)
+			return false;
+		compute_precache_lut(output, inverted, trc->count);
+		free(inverted);
+	}
+	return true;
+}
+
+
+// Determine if we can build with SSE2 (this was partly copied from jmorecfg.h in
+// mozilla/jpeg)
+ // -------------------------------------------------------------------------
+#if defined(_M_IX86) && defined(_MSC_VER)
+#define HAS_CPUID
+/* Get us a CPUID function. Avoid clobbering EBX because sometimes it's the PIC
+   register - I'm not sure if that ever happens on windows, but cpuid isn't
+   on the critical path so we just preserve the register to be safe and to be
+   consistent with the non-windows version. */
+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 {
+              xchg   ebx, esi
+              mov    eax, fxn
+              cpuid
+              mov    a_, eax
+              mov    b_, ebx
+              mov    c_, ecx
+              mov    d_, edx
+              xchg   ebx, esi
+       }
+       *a = a_;
+       *b = b_;
+       *c = c_;
+       *d = d_;
+}
+#elif defined(__GNUC__) && defined(__i386__)
+#define HAS_CPUID
+/* Get us a CPUID function. We can't use ebx because it's the PIC register on
+   some platforms, so we use ESI instead and save ebx to avoid clobbering it. */
+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;" 
+                             : "=a" (a_), "=S" (b_), "=c" (c_), "=d" (d_) : "a" (fxn));
+	   *a = a_;
+	   *b = b_;
+	   *c = c_;
+	   *d = d_;
+}
+#endif
+
+// -------------------------Runtime SSE2 Detection-----------------------------
+
+#define SSE2_EDX_MASK (1UL << 26)
+static qcms_bool sse2_available(void)
+{
+#if defined(__x86_64__) || defined(_M_AMD64)
+       return true;
+#elif defined(HAS_CPUID)
+       static int has_sse2 = -1;
+       uint32_t a, b, c, d;
+       uint32_t function = 0x00000001;
+
+       if (has_sse2 == -1) {
+              has_sse2 = 0;
+	      cpuid(function, &a, &b, &c, &d);
+              if (d & SSE2_EDX_MASK)
+                     has_sse2 = 1;
+              else
+                     has_sse2 = 0;
+       }
+
+       return has_sse2;
+#endif
+       return false;
+}
+
+
+void build_output_lut(struct curveType *trc,
+		uint16_t **output_gamma_lut, size_t *output_gamma_lut_length)
+{
+	if (trc->count == 0) {
+		*output_gamma_lut = build_linear_table(4096);
+		*output_gamma_lut_length = 4096;
+	} else if (trc->count == 1) {
+		float gamma = 1./u8Fixed8Number_to_float(trc->data[0]);
+		*output_gamma_lut = build_pow_table(gamma, 4096);
+		*output_gamma_lut_length = 4096;
+	} else {
+		*output_gamma_lut = invert_lut(trc->data, trc->count);
+		*output_gamma_lut_length = trc->count;
+	}
+
+}
+
+void qcms_profile_precache_output_transform(qcms_profile *profile)
+{
+	/* we only support precaching on rgb profiles */
+	if (profile->color_space != RGB_SIGNATURE)
+		return;
+
+	if (!profile->output_table_r) {
+		profile->output_table_r = precache_create();
+		if (profile->output_table_r &&
+				!compute_precache(profile->redTRC, profile->output_table_r->data)) {
+			precache_release(profile->output_table_r);
+			profile->output_table_r = NULL;
+		}
+	}
+	if (!profile->output_table_g) {
+		profile->output_table_g = precache_create();
+		if (profile->output_table_g &&
+				!compute_precache(profile->greenTRC, profile->output_table_g->data)) {
+			precache_release(profile->output_table_g);
+			profile->output_table_g = NULL;
+		}
+	}
+	if (!profile->output_table_b) {
+		profile->output_table_b = precache_create();
+		if (profile->output_table_b &&
+				!compute_precache(profile->blueTRC, profile->output_table_b->data)) {
+			precache_release(profile->output_table_g);
+			profile->output_table_g = NULL;
+		}
+	}
+}
+
+#define NO_MEM_TRANSFORM NULL
+
+qcms_transform* qcms_transform_create(
+		qcms_profile *in, qcms_data_type in_type,
+		qcms_profile* out, qcms_data_type out_type,
+		qcms_intent intent)
+{
+	bool precache = false;
+
+        qcms_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");
+	    free(transform);
+            return NULL;
+        }
+
+	if (out->output_table_r &&
+			out->output_table_g &&
+			out->output_table_b) {
+		precache = true;
+	}
+
+	if (precache) {
+		transform->output_table_r = precache_reference(out->output_table_r);
+		transform->output_table_g = precache_reference(out->output_table_g);
+		transform->output_table_b = precache_reference(out->output_table_b);
+	} else {
+		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) {
+            struct matrix in_matrix, out_matrix, result;
+
+            if (in_type != QCMS_DATA_RGB_8 &&
+                    in_type != QCMS_DATA_RGBA_8){
+                assert(0 && "input type");
+		free(transform);
+                return NULL;
+            }
+	    if (precache) {
+#ifdef X86
+		    if (sse2_available()) {
+			    if (in_type == QCMS_DATA_RGB_8)
+				    transform->transform_fn = qcms_transform_data_rgb_out_lut_sse;
+			    else
+				    transform->transform_fn = qcms_transform_data_rgba_out_lut_sse;
+
+		    } else
+#endif
+		    {
+			    if (in_type == QCMS_DATA_RGB_8)
+				    transform->transform_fn = qcms_transform_data_rgb_out_lut_precache;
+			    else
+				    transform->transform_fn = qcms_transform_data_rgba_out_lut_precache;
+		    }
+	    } else {
+		    if (in_type == QCMS_DATA_RGB_8)
+			    transform->transform_fn = qcms_transform_data_rgb_out_lut;
+		    else
+			    transform->transform_fn = qcms_transform_data_rgba_out_lut;
+	    }
+
+            //XXX: avoid duplicating tables if we can
+            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);
+            out_matrix = matrix_invert(out_matrix);
+            if (out_matrix.invalid) {
+                qcms_transform_release(transform);
+                return NULL;
+            }
+            result = matrix_multiply(out_matrix, in_matrix);
+
+            /* store the results in column major mode
+             * this makes doing the multiplication with sse easier */
+            transform->matrix[0][0] = result.m[0][0];
+            transform->matrix[1][0] = result.m[0][1];
+            transform->matrix[2][0] = result.m[0][2];
+            transform->matrix[0][1] = result.m[1][0];
+            transform->matrix[1][1] = result.m[1][1];
+            transform->matrix[2][1] = result.m[1][2];
+            transform->matrix[0][2] = result.m[2][0];
+            transform->matrix[1][2] = result.m[2][1];
+            transform->matrix[2][2] = result.m[2][2];
+
+        } else if (in->color_space == GRAY_SIGNATURE) {
+            if (in_type != QCMS_DATA_GRAY_8 &&
+                    in_type != QCMS_DATA_GRAYA_8){
+                assert(0 && "input type");
+		free(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;
+	    }
+
+	    if (precache) {
+		    if (in_type == QCMS_DATA_GRAY_8) {
+			    transform->transform_fn = qcms_transform_data_gray_out_precache;
+		    } else {
+			    transform->transform_fn = qcms_transform_data_graya_out_precache;
+		    }
+	    } else {
+		    if (in_type == QCMS_DATA_GRAY_8) {
+			    transform->transform_fn = qcms_transform_data_gray_out_lut;
+		    } else {
+			    transform->transform_fn = qcms_transform_data_graya_out_lut;
+		    }
+	    }
+	} else {
+		assert(0 && "unexpected colorspace");
+	}
+	return transform;
+}
+
+void qcms_transform_data(qcms_transform *transform, void *src, void *dest, size_t length)
+{
+	transform->transform_fn(transform, src, dest, length);
+}