shithub: jp2

Download patch

ref: 0d62e74e14ccf4e123d5c2d7af76cb02e695c0ee
author: Sigrid Solveig Haflínudóttir <ftrvxmtrx@gmail.com>
date: Mon Nov 23 13:00:52 EST 2020

first

diff: cannot open b/jasper//null: file does not exist: 'b/jasper//null'
--- /dev/null
+++ b/LICENSE
@@ -1,0 +1,51 @@
+JasPer License Version 2.0
+
+Copyright (c) 2001-2016 Michael David Adams
+Copyright (c) 1999-2000 Image Power, Inc.
+Copyright (c) 1999-2000 The University of British Columbia
+
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person (the
+"User") 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, 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:
+
+1.  The above copyright notices and this permission notice (which
+includes the disclaimer below) shall be included in all copies or
+substantial portions of the Software.
+
+2.  The name of a copyright holder shall not be used to endorse or
+promote products derived from the Software without specific prior
+written permission.
+
+THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+"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 OF THIRD PARTY RIGHTS.  IN NO
+EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+
--- /dev/null
+++ b/README.md
@@ -1,0 +1,5 @@
+# jp2
+
+JPEG2000 decoder for Plan 9.
+
+It's a stripped down port of Jasper library.
--- /dev/null
+++ b/jas_cm.c
@@ -1,0 +1,1253 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Color Management
+ *
+ * $Id$
+ */
+
+#include "jasper/jas_cm.h"
+#include "jasper/jas_icc.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+
+static jas_cmprof_t *jas_cmprof_create(void);
+static void jas_cmshapmatlut_cleanup(jas_cmshapmatlut_t *);
+static jas_cmreal_t jas_cmshapmatlut_lookup(const jas_cmshapmatlut_t *lut, jas_cmreal_t x);
+
+static void jas_cmpxform_destroy(jas_cmpxform_t *pxform);
+static jas_cmpxform_t *jas_cmpxform_copy(jas_cmpxform_t *pxform);
+
+static void jas_cmshapmat_destroy(jas_cmpxform_t *pxform);
+static int jas_cmshapmat_apply(const jas_cmpxform_t *pxform, const jas_cmreal_t *in,
+  jas_cmreal_t *out, unsigned cnt);
+
+static int jas_cmputint(long **bufptr, int sgnd, unsigned prec, long val);
+static int jas_cmgetint(const long **bufptr, int sgnd, unsigned prec, long *val);
+static int jas_cmpxformseq_append(jas_cmpxformseq_t *pxformseq,
+  jas_cmpxformseq_t *othpxformseq);
+static int jas_cmpxformseq_appendcnvt(jas_cmpxformseq_t *pxformseq,
+  unsigned, unsigned);
+static int jas_cmpxformseq_resize(jas_cmpxformseq_t *pxformseq, unsigned n);
+
+static int mono(const jas_iccprof_t *prof, int op, jas_cmpxformseq_t **pxformseq);
+static int triclr(const jas_iccprof_t *prof, int op, jas_cmpxformseq_t **retpxformseq);
+
+static void jas_cmpxformseq_destroy(jas_cmpxformseq_t *pxformseq);
+static int jas_cmpxformseq_delete(jas_cmpxformseq_t *pxformseq, unsigned i);
+static jas_cmpxformseq_t *jas_cmpxformseq_create(void);
+static jas_cmpxformseq_t *jas_cmpxformseq_copy(jas_cmpxformseq_t *pxformseq);
+static int jas_cmshapmat_invmat(jas_cmreal_t out[3][4], jas_cmreal_t in[3][4]);
+static int jas_cmpxformseq_insertpxform(jas_cmpxformseq_t *pxformseq,
+  int i, jas_cmpxform_t *pxform);
+
+#define	SEQFWD(intent)	(intent)
+#define	SEQREV(intent)	(4 + (intent))
+#define	SEQSIM(intent)	(8 + (intent))
+#define	SEQGAM		12
+
+#define fwdpxformseq(prof, intent) \
+  (((prof)->pxformseqs[SEQFWD(intent)]) ? \
+  ((prof)->pxformseqs[SEQFWD(intent)]) : \
+  ((prof)->pxformseqs[SEQFWD(0)]))
+
+#define revpxformseq(prof, intent) \
+  (((prof)->pxformseqs[SEQREV(intent)]) ? \
+  ((prof)->pxformseqs[SEQREV(intent)]) : \
+  ((prof)->pxformseqs[SEQREV(0)]))
+
+#define simpxformseq(prof, intent) \
+  (((prof)->pxformseqs[SEQSIM(intent)]) ? \
+  ((prof)->pxformseqs[SEQSIM(intent)]) : \
+  ((prof)->pxformseqs[SEQSIM(0)]))
+
+#define gampxformseq(prof)	((prof)->pxformseqs[SEQGAM])
+
+static jas_clrspc_t icctoclrspc(jas_iccsig_t iccclrspc, int refflag);
+static jas_cmpxform_t *jas_cmpxform_create0(void);
+static jas_cmpxform_t *jas_cmpxform_createshapmat(void);
+static void jas_cmshapmatlut_init(jas_cmshapmatlut_t *lut);
+static int jas_cmshapmatlut_set(jas_cmshapmatlut_t *lut, const jas_icccurv_t *curv);
+
+static const jas_cmpxformops_t shapmat_ops = {jas_cmshapmat_destroy, jas_cmshapmat_apply, 0};
+static jas_cmprof_t *jas_cmprof_createsycc(void);
+
+/******************************************************************************\
+* Color profile class.
+\******************************************************************************/
+
+jas_cmprof_t *jas_cmprof_createfromclrspc(jas_clrspc_t clrspc)
+{
+	jas_iccprof_t *iccprof;
+	jas_cmprof_t *prof;
+
+	iccprof = 0;
+	switch (clrspc) {
+	case JAS_CLRSPC_SYCBCR:
+		if (!(prof = jas_cmprof_createsycc()))
+			goto error;
+		break;
+	default:
+		if (!(iccprof = jas_iccprof_createfromclrspc(clrspc)))
+			goto error;
+		if (!(prof = jas_cmprof_createfromiccprof(iccprof)))
+			goto error;
+		jas_iccprof_destroy(iccprof);
+		if (!jas_clrspc_isgeneric(clrspc))
+			prof->clrspc = clrspc;
+		break;
+	}
+	return prof;
+error:
+	if (iccprof)
+		jas_iccprof_destroy(iccprof);
+	return 0;
+}
+
+static jas_cmprof_t *jas_cmprof_createsycc()
+{
+	jas_cmprof_t *prof;
+	jas_cmpxform_t *fwdpxform = NULL;
+	jas_cmpxform_t *revpxform = NULL;
+	jas_cmshapmat_t *fwdshapmat;
+	jas_cmshapmat_t *revshapmat;
+
+	if (!(prof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)))
+		goto error;
+	prof->clrspc = JAS_CLRSPC_SYCBCR;
+	assert(prof->numchans == 3 && prof->numrefchans == 3);
+	assert(prof->refclrspc == JAS_CLRSPC_CIEXYZ);
+	if (!(fwdpxform = jas_cmpxform_createshapmat()))
+		goto error;
+	fwdpxform->numinchans = 3;
+	fwdpxform->numoutchans = 3;
+	fwdshapmat = &fwdpxform->data.shapmat;
+	fwdshapmat->mono = 0;
+	fwdshapmat->order = 0;
+	fwdshapmat->useluts = 0;
+	fwdshapmat->usemat = 1;
+	fwdshapmat->mat[0][0] = 1.0;
+	fwdshapmat->mat[0][1] = 0.0;
+	fwdshapmat->mat[0][2] = 1.402;
+	fwdshapmat->mat[1][0] = 1.0;
+	fwdshapmat->mat[1][1] = -0.34413;
+	fwdshapmat->mat[1][2] = -0.71414;
+	fwdshapmat->mat[2][0] = 1.0;
+	fwdshapmat->mat[2][1] = 1.772;
+	fwdshapmat->mat[2][2] = 0.0;
+	fwdshapmat->mat[0][3] = -0.5 * (1.402);
+	fwdshapmat->mat[1][3] = -0.5 * (-0.34413 - 0.71414);
+	fwdshapmat->mat[2][3] = -0.5 * (1.772);
+	if (!(revpxform = jas_cmpxform_createshapmat()))
+		goto error;
+	revpxform->numinchans = 3;
+	revpxform->numoutchans = 3;
+	revshapmat = &revpxform->data.shapmat;
+	revshapmat->mono = 0;
+	revshapmat->order = 1;
+	revshapmat->useluts = 0;
+	revshapmat->usemat = 1;
+	jas_cmshapmat_invmat(revshapmat->mat, fwdshapmat->mat);
+
+	for (unsigned i = 0; i < JAS_CMXFORM_NUMINTENTS; ++i) {
+		unsigned j = SEQFWD(i);
+		if (prof->pxformseqs[j]) {
+			if (jas_cmpxformseq_insertpxform(prof->pxformseqs[j], 0,
+			  fwdpxform))
+				goto error;
+		}
+		j = SEQREV(i);
+		if (prof->pxformseqs[j]) {
+			if (jas_cmpxformseq_insertpxform(prof->pxformseqs[j],
+			  -1, revpxform))
+				goto error;
+		}
+	}
+
+	jas_cmpxform_destroy(fwdpxform);
+	jas_cmpxform_destroy(revpxform);
+	return prof;
+error:
+	if (fwdpxform)
+		jas_cmpxform_destroy(fwdpxform);
+	if (revpxform)
+		jas_cmpxform_destroy(revpxform);
+	return 0;
+}
+
+jas_cmprof_t *jas_cmprof_createfromiccprof(const jas_iccprof_t *iccprof)
+{
+	jas_cmprof_t *prof;
+	jas_icchdr_t icchdr;
+	jas_cmpxformseq_t *fwdpxformseq;
+	jas_cmpxformseq_t *revpxformseq;
+
+	fwdpxformseq = 0;
+	revpxformseq = 0;
+
+	if (!(prof = jas_cmprof_create()))
+		goto error;
+	jas_iccprof_gethdr(iccprof, &icchdr);
+	if (!(prof->iccprof = jas_iccprof_copy(iccprof)))
+		goto error;
+	prof->clrspc = icctoclrspc(icchdr.colorspc, 0);
+	prof->refclrspc = icctoclrspc(icchdr.refcolorspc, 1);
+	prof->numchans = jas_clrspc_numchans(prof->clrspc);
+	prof->numrefchans = jas_clrspc_numchans(prof->refclrspc);
+
+	if (prof->numchans == 1) {
+		if (mono(prof->iccprof, 0, &fwdpxformseq))
+			goto error;
+		if (mono(prof->iccprof, 1, &revpxformseq))
+			goto error;
+	} else if (prof->numchans == 3) {
+		if (triclr(prof->iccprof, 0, &fwdpxformseq))
+			goto error;
+		if (triclr(prof->iccprof, 1, &revpxformseq))
+			goto error;
+	}
+	prof->pxformseqs[SEQFWD(0)] = fwdpxformseq;
+	prof->pxformseqs[SEQREV(0)] = revpxformseq;
+
+#if 0
+	if (prof->numchans > 1) {
+		lut(prof->iccprof, 0, PER, &pxformseq);
+		pxformseqs_set(prof, SEQFWD(PER), pxformseq);
+		lut(prof->iccprof, 1, PER, &pxformseq);
+		pxformseqs_set(prof, SEQREV(PER), pxformseq);
+		lut(prof->iccprof, 0, CLR, &pxformseq);
+		pxformseqs_set(prof, SEQREV(CLR), pxformseq);
+		lut(prof->iccprof, 1, CLR, &pxformseq);
+		pxformseqs_set(prof, SEQREV(CLR), pxformseq);
+		lut(prof->iccprof, 0, SAT, &pxformseq);
+		pxformseqs_set(prof, SEQREV(SAT), pxformseq);
+		lut(prof->iccprof, 1, SAT, &pxformseq);
+		pxformseqs_set(prof, SEQREV(SAT), pxformseq);
+	}
+#endif
+
+	return prof;
+
+error:
+	if (fwdpxformseq) {
+		jas_cmpxformseq_destroy(fwdpxformseq);
+	}
+	if (revpxformseq) {
+		jas_cmpxformseq_destroy(revpxformseq);
+	}
+	if (prof) {
+		jas_cmprof_destroy(prof);
+	}
+
+	return 0;
+}
+
+static jas_cmprof_t *jas_cmprof_create()
+{
+	jas_cmprof_t *prof;
+	if (!(prof = jas_malloc(sizeof(jas_cmprof_t))))
+		return 0;
+	memset(prof, 0, sizeof(jas_cmprof_t));
+	prof->iccprof = 0;
+	for (unsigned i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i)
+		prof->pxformseqs[i] = 0;
+	return prof;
+}
+
+void jas_cmprof_destroy(jas_cmprof_t *prof)
+{ 
+	for (unsigned i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i) {
+		if (prof->pxformseqs[i]) {
+			jas_cmpxformseq_destroy(prof->pxformseqs[i]);
+			prof->pxformseqs[i] = 0;
+		}
+	}
+	if (prof->iccprof)
+		jas_iccprof_destroy(prof->iccprof);
+	jas_free(prof);
+}
+
+jas_cmprof_t *jas_cmprof_copy(const jas_cmprof_t *prof)
+{
+	jas_cmprof_t *newprof;
+
+	if (!(newprof = jas_cmprof_create()))
+		goto error;
+	newprof->clrspc = prof->clrspc;
+	newprof->numchans = prof->numchans;
+	newprof->refclrspc = prof->refclrspc;
+	newprof->numrefchans = prof->numrefchans;
+	newprof->iccprof = jas_iccprof_copy(prof->iccprof);
+	for (unsigned i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i) {
+		if (prof->pxformseqs[i]) {
+			if (!(newprof->pxformseqs[i] = jas_cmpxformseq_copy(prof->pxformseqs[i])))
+				goto error;
+		}
+	}
+	return newprof;
+error:
+	if (newprof)
+		jas_cmprof_destroy(newprof);
+	return 0;
+}
+
+/******************************************************************************\
+* Transform class.
+\******************************************************************************/
+
+jas_cmxform_t *jas_cmxform_create(const jas_cmprof_t *inprof, const jas_cmprof_t *outprof,
+  const jas_cmprof_t *prfprof, jas_cmxform_op_t op, jas_cmxform_intent_t intent, jas_cmxform_optm_t optimize)
+{
+	jas_cmxform_t *xform;
+	jas_cmpxformseq_t *inpxformseq;
+	jas_cmpxformseq_t *outpxformseq;
+	jas_cmpxformseq_t *altoutpxformseq;
+	jas_cmpxformseq_t *prfpxformseq;
+
+	/* Avoid compiler warnings about unused parameters. */
+	(void)optimize;
+
+	const jas_cmxform_intent_t prfintent = intent;
+
+	if (!(xform = jas_malloc(sizeof(jas_cmxform_t))))
+		goto error;
+	if (!(xform->pxformseq = jas_cmpxformseq_create()))
+		goto error;
+
+	switch (op) {
+	case JAS_CMXFORM_OP_FWD:
+		inpxformseq = fwdpxformseq(inprof, intent);
+		outpxformseq = revpxformseq(outprof, intent);
+		if (!inpxformseq || !outpxformseq)
+			goto error;
+		if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) ||
+		  jas_cmpxformseq_appendcnvt(xform->pxformseq,
+		  inprof->refclrspc, outprof->refclrspc) ||
+		  jas_cmpxformseq_append(xform->pxformseq, outpxformseq))
+			goto error;
+		xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
+		xform->numoutchans = jas_clrspc_numchans(outprof->clrspc);
+		break;
+	case JAS_CMXFORM_OP_REV:
+		outpxformseq = fwdpxformseq(outprof, intent);
+		inpxformseq = revpxformseq(inprof, intent);
+		if (!outpxformseq || !inpxformseq)
+			goto error;
+		if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq) ||
+		  jas_cmpxformseq_appendcnvt(xform->pxformseq,
+		  outprof->refclrspc, inprof->refclrspc) ||
+		  jas_cmpxformseq_append(xform->pxformseq, inpxformseq))
+			goto error;
+		xform->numinchans = jas_clrspc_numchans(outprof->clrspc);
+		xform->numoutchans = jas_clrspc_numchans(inprof->clrspc);
+		break;
+	case JAS_CMXFORM_OP_PROOF:
+		assert(prfprof);
+		inpxformseq = fwdpxformseq(inprof, intent);
+		prfpxformseq = fwdpxformseq(prfprof, prfintent);
+		if (!inpxformseq || !prfpxformseq)
+			goto error;
+		outpxformseq = simpxformseq(outprof, intent);
+		altoutpxformseq = 0;
+		if (!outpxformseq) {
+			outpxformseq = revpxformseq(outprof, intent);
+			altoutpxformseq = fwdpxformseq(outprof, intent);
+			if (!outpxformseq || !altoutpxformseq)
+				goto error;
+		}
+		if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) ||
+		  jas_cmpxformseq_appendcnvt(xform->pxformseq,
+		  inprof->refclrspc, outprof->refclrspc))
+			goto error;
+		if (altoutpxformseq) {
+			if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq) ||
+			  jas_cmpxformseq_append(xform->pxformseq, altoutpxformseq))
+				goto error;
+		} else {
+			if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq))
+				goto error;
+		}
+		if (jas_cmpxformseq_appendcnvt(xform->pxformseq,
+		  outprof->refclrspc, inprof->refclrspc) ||
+		  jas_cmpxformseq_append(xform->pxformseq, prfpxformseq))
+			goto error;
+		xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
+		xform->numoutchans = jas_clrspc_numchans(prfprof->clrspc);
+		break;
+	case JAS_CMXFORM_OP_GAMUT:
+		inpxformseq = fwdpxformseq(inprof, intent);
+		outpxformseq = gampxformseq(outprof);
+		if (!inpxformseq || !outpxformseq)
+			goto error;
+		if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) ||
+		  jas_cmpxformseq_appendcnvt(xform->pxformseq,
+		  inprof->refclrspc, outprof->refclrspc) ||
+		  jas_cmpxformseq_append(xform->pxformseq, outpxformseq))
+			goto error;
+		xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
+		xform->numoutchans = 1;
+		break;
+	}
+	return xform;
+error:
+	if (xform)
+		jas_cmxform_destroy(xform);
+	return 0;
+}
+
+#define	APPLYBUFSIZ	2048
+int jas_cmxform_apply(const jas_cmxform_t *xform, const jas_cmpixmap_t *in, jas_cmpixmap_t *out)
+{
+	jas_cmreal_t buf[2][APPLYBUFSIZ];
+	jas_cmreal_t *inbuf;
+	jas_cmreal_t *outbuf;
+	jas_cmreal_t scale;
+	long v;
+
+	if (xform->numinchans > in->numcmpts || xform->numoutchans > out->numcmpts)
+		goto error;
+
+	const jas_cmcmptfmt_t *fmt = &in->cmptfmts[0];
+	const unsigned width = fmt->width;
+	const unsigned height = fmt->height;
+	for (unsigned i = 1; i < xform->numinchans; ++i) {
+		fmt = &in->cmptfmts[i];
+		if (fmt->width != width || fmt->height != height) {
+			goto error;
+		}
+	}
+	for (unsigned i = 0; i < xform->numoutchans; ++i) {
+		fmt = &out->cmptfmts[i];
+		if (fmt->width != width || fmt->height != height) {
+			goto error;
+		}
+	}
+
+	unsigned maxchans = 0;
+	const jas_cmpxformseq_t *pxformseq = xform->pxformseq;
+	for (unsigned i = 0; i < pxformseq->numpxforms; ++i) {
+		const jas_cmpxform_t *pxform = pxformseq->pxforms[i];
+		if (pxform->numinchans > maxchans) {
+			maxchans = pxform->numinchans;
+		}
+		if (pxform->numoutchans > maxchans) {
+			maxchans = pxform->numoutchans;
+		}
+	}
+
+	if (maxchans == 0)
+		/* avoid division by zero */
+		goto error;
+
+	const unsigned bufmax = APPLYBUFSIZ / maxchans;
+	assert(bufmax > 0);
+
+	const unsigned total = width * height;
+	unsigned n = 0;
+	while (n < total) {
+
+		inbuf = &buf[0][0];
+		const unsigned m = JAS_MIN(total - n, bufmax);
+
+		for (unsigned i = 0; i < xform->numinchans; ++i) {
+			fmt = &in->cmptfmts[i];
+			scale = (double)((1 << fmt->prec) - 1);
+			const unsigned bias = fmt->sgnd ? (1 << (fmt->prec - 1)) : 0;
+			const long *dataptr = &fmt->buf[n];
+			jas_cmreal_t *bufptr = &inbuf[i];
+			for (unsigned j = 0; j < m; ++j) {
+				if (jas_cmgetint(&dataptr, fmt->sgnd, fmt->prec, &v))
+					goto error;
+				*bufptr = (jas_cmreal_t)(v - bias) / scale;
+				bufptr += xform->numinchans;
+			}
+		}
+
+		inbuf = &buf[0][0];
+		outbuf = inbuf;
+		for (unsigned i = 0; i < pxformseq->numpxforms; ++i) {
+			const jas_cmpxform_t *pxform = pxformseq->pxforms[i];
+			if (pxform->numoutchans > pxform->numinchans) {
+				outbuf = (inbuf == &buf[0][0]) ? &buf[1][0] : &buf[0][0];
+			} else {
+				outbuf = inbuf;
+			}
+			if ((*pxform->ops->apply)(pxform, inbuf, outbuf, m))
+				goto error;
+			inbuf = outbuf;
+		}
+
+		for (unsigned i = 0; i < xform->numoutchans; ++i) {
+			fmt = &out->cmptfmts[i];
+			scale = (double)((1 << fmt->prec) - 1);
+			const unsigned bias = fmt->sgnd ? (1 << (fmt->prec - 1)) : 0;
+			const jas_cmreal_t *bufptr = &outbuf[i];
+			long *dataptr = &fmt->buf[n];
+			for (unsigned j = 0; j < m; ++j) {
+				v = (long)((*bufptr) * scale + bias);
+				bufptr += xform->numoutchans;
+				if (jas_cmputint(&dataptr, fmt->sgnd, fmt->prec, v))
+					goto error;
+			}
+		}
+	
+		n += m;
+	}
+	
+	return 0;
+error:
+	return -1;
+}
+
+void jas_cmxform_destroy(jas_cmxform_t *xform)
+{
+	if (xform->pxformseq)
+		jas_cmpxformseq_destroy(xform->pxformseq);
+	jas_free(xform);
+}
+
+/******************************************************************************\
+* Primitive transform sequence class.
+\******************************************************************************/
+
+static jas_cmpxformseq_t *jas_cmpxformseq_create()
+{
+	jas_cmpxformseq_t *pxformseq;
+	if (!(pxformseq = jas_malloc(sizeof(jas_cmpxformseq_t))))
+		goto error;
+	pxformseq->pxforms = 0;
+	pxformseq->numpxforms = 0;
+	pxformseq->maxpxforms = 0;
+	if (jas_cmpxformseq_resize(pxformseq, 16))
+		goto error;
+	return pxformseq;
+error:
+	if (pxformseq)
+		jas_cmpxformseq_destroy(pxformseq);
+	return 0;
+}
+
+static jas_cmpxformseq_t *jas_cmpxformseq_copy(jas_cmpxformseq_t *pxformseq)
+{
+	jas_cmpxformseq_t *newpxformseq;
+
+	if (!(newpxformseq = jas_cmpxformseq_create()))
+		goto error;
+	if (jas_cmpxformseq_append(newpxformseq, pxformseq))
+		goto error;
+	return newpxformseq;
+error:
+	if (newpxformseq)
+		jas_cmpxformseq_destroy(newpxformseq);
+	return 0;
+}
+
+static void jas_cmpxformseq_destroy(jas_cmpxformseq_t *pxformseq)
+{
+	while (pxformseq->numpxforms > 0)
+		jas_cmpxformseq_delete(pxformseq, pxformseq->numpxforms - 1);
+	if (pxformseq->pxforms)
+		jas_free(pxformseq->pxforms);
+	jas_free(pxformseq);
+}
+
+static int jas_cmpxformseq_delete(jas_cmpxformseq_t *pxformseq, unsigned i)
+{
+	assert(i < pxformseq->numpxforms);
+	assert(i == pxformseq->numpxforms - 1);
+	jas_cmpxform_destroy(pxformseq->pxforms[i]);
+	pxformseq->pxforms[i] = 0;
+	--pxformseq->numpxforms;
+	return 0;
+}
+
+static int jas_cmpxformseq_appendcnvt(jas_cmpxformseq_t *pxformseq,
+  unsigned dstclrspc, unsigned srcclrspc)
+{
+	if (dstclrspc == srcclrspc)
+		return 0;
+	abort();
+	/* Avoid compiler warnings about unused parameters. */
+	USED(pxformseq);
+	return -1;
+}
+
+static int jas_cmpxformseq_insertpxform(jas_cmpxformseq_t *pxformseq,
+  int _i, jas_cmpxform_t *pxform)
+{
+	jas_cmpxform_t *tmppxform;
+	const unsigned i = _i >= 0 ? (unsigned)_i : pxformseq->numpxforms;
+	assert(i <= pxformseq->numpxforms);
+	if (pxformseq->numpxforms >= pxformseq->maxpxforms) {
+		if (jas_cmpxformseq_resize(pxformseq, pxformseq->numpxforms +
+		  16))
+			goto error;
+	}
+	assert(pxformseq->numpxforms < pxformseq->maxpxforms);
+	if (!(tmppxform = jas_cmpxform_copy(pxform)))
+		goto error;
+	const unsigned n = pxformseq->numpxforms - i;
+	if (n > 0) {
+		memmove(&pxformseq->pxforms[i + 1], &pxformseq->pxforms[i],
+		  n * sizeof(jas_cmpxform_t *));
+	}
+	pxformseq->pxforms[i] = tmppxform;
+	++pxformseq->numpxforms;
+	return 0;
+error:
+	return -1;
+}
+
+static int jas_cmpxformseq_append(jas_cmpxformseq_t *pxformseq,
+  jas_cmpxformseq_t *othpxformseq)
+{
+	jas_cmpxform_t *pxform;
+	jas_cmpxform_t *othpxform;
+	const unsigned n = pxformseq->numpxforms + othpxformseq->numpxforms;
+	if (n > pxformseq->maxpxforms) {
+		if (jas_cmpxformseq_resize(pxformseq, n))
+			goto error;
+	}
+	for (unsigned i = 0; i < othpxformseq->numpxforms; ++i) {
+		othpxform = othpxformseq->pxforms[i];
+		if (!(pxform = jas_cmpxform_copy(othpxform)))
+			goto error;
+		pxformseq->pxforms[pxformseq->numpxforms] = pxform;
+		++pxformseq->numpxforms;
+	}
+	return 0;
+error:
+	return -1;
+}
+
+static int jas_cmpxformseq_resize(jas_cmpxformseq_t *pxformseq, unsigned n)
+{
+	jas_cmpxform_t **p;
+	assert(n >= pxformseq->numpxforms);
+	p = (!pxformseq->pxforms) ? jas_alloc2(n, sizeof(jas_cmpxform_t *)) :
+	  jas_realloc2(pxformseq->pxforms, n, sizeof(jas_cmpxform_t *));
+	if (!p) {
+		return -1;
+	}
+	pxformseq->pxforms = p;
+	pxformseq->maxpxforms = n;
+	return 0;
+}
+
+/******************************************************************************\
+* Primitive transform class.
+\******************************************************************************/
+
+static jas_cmpxform_t *jas_cmpxform_create0()
+{
+	jas_cmpxform_t *pxform;
+	if (!(pxform = jas_malloc(sizeof(jas_cmpxform_t))))
+		return 0;
+	memset(pxform, 0, sizeof(jas_cmpxform_t));
+	pxform->refcnt = 0;
+	pxform->ops = 0;
+	return pxform;
+}
+
+static void jas_cmpxform_destroy(jas_cmpxform_t *pxform)
+{
+	if (--pxform->refcnt <= 0) {
+		(*pxform->ops->destroy)(pxform);
+		jas_free(pxform);
+	}
+}
+
+static jas_cmpxform_t *jas_cmpxform_copy(jas_cmpxform_t *pxform)
+{
+	++pxform->refcnt;
+	return pxform;
+}
+
+/******************************************************************************\
+* Shaper matrix class.
+\******************************************************************************/
+
+static jas_cmpxform_t *jas_cmpxform_createshapmat()
+{
+	jas_cmpxform_t *pxform;
+	jas_cmshapmat_t *shapmat;
+	if (!(pxform = jas_cmpxform_create0()))
+		return 0;
+	pxform->ops = &shapmat_ops;
+	shapmat = &pxform->data.shapmat;
+	shapmat->mono = 0;
+	shapmat->order = 0;
+	shapmat->useluts = 0;
+	shapmat->usemat = 0;
+	for (unsigned i = 0; i < 3; ++i)
+		jas_cmshapmatlut_init(&shapmat->luts[i]);
+	for (unsigned i = 0; i < 3; ++i) {
+		for (unsigned j = 0; j < 4; ++j)
+			shapmat->mat[i][j] = 0.0;
+	}
+	++pxform->refcnt;
+	return pxform;
+}
+
+static void jas_cmshapmat_destroy(jas_cmpxform_t *pxform)
+{
+	jas_cmshapmat_t *shapmat = &pxform->data.shapmat;
+	for (unsigned i = 0; i < 3; ++i)
+		jas_cmshapmatlut_cleanup(&shapmat->luts[i]);
+}
+
+static int jas_cmshapmat_apply(const jas_cmpxform_t *pxform, const jas_cmreal_t *in,
+  jas_cmreal_t *out, unsigned cnt)
+{
+	const jas_cmshapmat_t *shapmat = &pxform->data.shapmat;
+	jas_cmreal_t *dst;
+	jas_cmreal_t a0;
+	jas_cmreal_t a1;
+	jas_cmreal_t a2;
+	jas_cmreal_t b0;
+	jas_cmreal_t b1;
+	jas_cmreal_t b2;
+	const jas_cmreal_t *src = in;
+	dst = out;
+	if (!shapmat->mono) {
+		while (cnt-- > 0) {
+			a0 = *src++;
+			a1 = *src++;
+			a2 = *src++;
+			if (!shapmat->order && shapmat->useluts) {
+				a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+				a1 = jas_cmshapmatlut_lookup(&shapmat->luts[1], a1);
+				a2 = jas_cmshapmatlut_lookup(&shapmat->luts[2], a2);
+			}
+			if (shapmat->usemat) {
+				b0 = shapmat->mat[0][0] * a0
+				  + shapmat->mat[0][1] * a1
+				  + shapmat->mat[0][2] * a2
+				  + shapmat->mat[0][3];
+				b1 = shapmat->mat[1][0] * a0
+				  + shapmat->mat[1][1] * a1
+				  + shapmat->mat[1][2] * a2
+				  + shapmat->mat[1][3];
+				b2 = shapmat->mat[2][0] * a0
+				  + shapmat->mat[2][1] * a1
+				  + shapmat->mat[2][2] * a2
+				  + shapmat->mat[2][3];
+				a0 = b0;
+				a1 = b1;
+				a2 = b2;
+			}
+			if (shapmat->order && shapmat->useluts) {
+				a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+				a1 = jas_cmshapmatlut_lookup(&shapmat->luts[1], a1);
+				a2 = jas_cmshapmatlut_lookup(&shapmat->luts[2], a2);
+			}
+			*dst++ = a0;
+			*dst++ = a1;
+			*dst++ = a2;
+		}
+	} else {
+		if (!shapmat->order) {
+			while (cnt-- > 0) {
+				a0 = *src++;
+				if (shapmat->useluts)
+					a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+				a2 = a0 * shapmat->mat[2][0];
+				a1 = a0 * shapmat->mat[1][0];
+				a0 = a0 * shapmat->mat[0][0];
+				*dst++ = a0;
+				*dst++ = a1;
+				*dst++ = a2;
+			}
+		} else {
+assert(0);
+			while (cnt-- > 0) {
+				a0 = *src++;
+				src++;
+				src++;
+				a0 = a0 * shapmat->mat[0][0];
+				if (shapmat->useluts)
+					a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+				*dst++ = a0;
+			}
+		}
+	}
+
+	return 0;
+}
+
+static void jas_cmshapmatlut_init(jas_cmshapmatlut_t *lut)
+{
+	lut->data = 0;
+	lut->size = 0;
+}
+
+static void jas_cmshapmatlut_cleanup(jas_cmshapmatlut_t *lut)
+{
+	if (lut->data) {
+		jas_free(lut->data);
+		lut->data = 0;
+	}
+	lut->size = 0;
+}
+
+static double gammafn(double x, double gamma)
+{
+	if (x == 0.0)
+		return 0.0;
+	return pow(x, gamma);
+}
+
+static int jas_cmshapmatlut_set(jas_cmshapmatlut_t *lut, const jas_icccurv_t *curv)
+{
+	jas_cmreal_t gamma;
+	jas_cmshapmatlut_cleanup(lut);
+	if (curv->numents == 0) {
+		lut->size = 2;
+		if (!(lut->data = jas_alloc2(lut->size, sizeof(jas_cmreal_t))))
+			goto error;
+		lut->data[0] = 0.0;
+		lut->data[1] = 1.0;
+	} else if (curv->numents == 1) {
+		lut->size = 256;
+		if (!(lut->data = jas_alloc2(lut->size, sizeof(jas_cmreal_t))))
+			goto error;
+		gamma = (jas_cmreal_t)curv->ents[0] / 256.0;
+		for (unsigned i = 0; i < lut->size; ++i) {
+			lut->data[i] = gammafn(i / (double) (lut->size - 1), gamma);
+		}
+	} else {
+		lut->size = curv->numents;
+		if (!(lut->data = jas_alloc2(lut->size, sizeof(jas_cmreal_t))))
+			goto error;
+		for (unsigned i = 0; i < lut->size; ++i) {
+			lut->data[i] = (jas_cmreal_t)curv->ents[i] / 65535.0;
+		}
+	}
+	return 0;
+error:
+	return -1;
+}
+
+static jas_cmreal_t jas_cmshapmatlut_lookup(const jas_cmshapmatlut_t *lut, jas_cmreal_t x)
+{
+	jas_cmreal_t t;
+	t = x * (lut->size - 1);
+	const int lo = (int)floor(t);
+	if (lo < 0)
+		return lut->data[0];
+	const unsigned hi = (unsigned)ceil(t);
+	if (hi >= lut->size)
+		return lut->data[lut->size - 1];
+	return lut->data[lo] + (t - lo) * (lut->data[hi] - lut->data[lo]);
+}
+
+static int jas_cmshapmatlut_invert(jas_cmshapmatlut_t *invlut,
+  const jas_cmshapmatlut_t *lut, unsigned n)
+{
+	jas_cmreal_t ax;
+	jas_cmreal_t ay;
+	jas_cmreal_t bx;
+	jas_cmreal_t by;
+	jas_cmreal_t sx;
+	jas_cmreal_t sy;
+	assert(n >= 2);
+	if (invlut->data) {
+		jas_free(invlut->data);
+		invlut->data = 0;
+	}
+	/* The sample values should be nondecreasing. */
+	for (unsigned i = 1; i < lut->size; ++i) {
+		if (lut->data[i - 1] > lut->data[i]) {
+			assert(0);
+			return -1;
+		}
+	}
+	if (!(invlut->data = jas_alloc2(n, sizeof(jas_cmreal_t))))
+		return -1;
+	invlut->size = n;
+	for (unsigned i = 0; i < invlut->size; ++i) {
+		sy = ((double) i) / (invlut->size - 1);
+		sx = 1.0;
+		for (unsigned j = 0; j < lut->size; ++j) {
+			ay = lut->data[j];
+			if (sy == ay) {
+				unsigned k;
+				for (k = j + 1; k < lut->size; ++k) {
+					by = lut->data[k];
+					if (by != sy)
+						break;
+#if 0
+assert(0);
+#endif
+				}
+				if (k < lut->size) {
+					--k;
+					ax = ((double) j) / (lut->size - 1);
+					bx = ((double) k) / (lut->size - 1);
+					sx = (ax + bx) / 2.0;
+				}
+				break;
+			}
+			if (j < lut->size - 1) {
+				by = lut->data[j + 1];
+				if (sy > ay && sy < by) {
+					ax = ((double) j) / (lut->size - 1);
+					bx = ((double) j + 1) / (lut->size - 1);
+					sx = ax +
+					  (sy - ay) / (by - ay) * (bx - ax);
+					break;
+				}
+			}
+		}
+		invlut->data[i] = sx;
+	}
+#if 0
+for (i=0;i<lut->size;++i)
+	jas_eprintf("lut[%d]=%f ", i, lut->data[i]);
+for (i=0;i<invlut->size;++i)
+	jas_eprintf("invlut[%d]=%f ", i, invlut->data[i]);
+#endif
+	return 0;
+}
+
+static int jas_cmshapmat_invmat(jas_cmreal_t out[3][4], jas_cmreal_t in[3][4])
+{
+	jas_cmreal_t d;
+	d = in[0][0] * (in[1][1] * in[2][2] - in[1][2] * in[2][1])
+	  - in[0][1] * (in[1][0] * in[2][2] - in[1][2] * in[2][0])
+	  + in[0][2] * (in[1][0] * in[2][1] - in[1][1] * in[2][0]);
+#if 0
+jas_eprintf("delta=%f\n", d);
+#endif
+	if (JAS_ABS(d) < 1e-6)
+		return -1;
+	out[0][0] = (in[1][1] * in[2][2] - in[1][2] * in[2][1]) / d;
+	out[1][0] = -(in[1][0] * in[2][2] - in[1][2] * in[2][0]) / d;
+	out[2][0] = (in[1][0] * in[2][1] - in[1][1] * in[2][0]) / d;
+	out[0][1] = -(in[0][1] * in[2][2] - in[0][2] * in[2][1]) / d;
+	out[1][1] = (in[0][0] * in[2][2] - in[0][2] * in[2][0]) / d;
+	out[2][1] = -(in[0][0] * in[2][1] - in[0][1] * in[2][0]) / d;
+	out[0][2] = (in[0][1] * in[1][2] - in[0][2] * in[1][1]) / d;
+	out[1][2] = -(in[0][0] * in[1][2] - in[1][0] * in[0][2]) / d;
+	out[2][2] = (in[0][0] * in[1][1] - in[0][1] * in[1][0]) / d;
+	out[0][3] = -in[0][3];
+	out[1][3] = -in[1][3];
+	out[2][3] = -in[2][3];
+#if 0
+jas_eprintf("[ %f %f %f %f ]\n[ %f %f %f %f ]\n[ %f %f %f %f ]\n",
+in[0][0], in[0][1], in[0][2], in[0][3],
+in[1][0], in[1][1], in[1][2], in[1][3],
+in[2][0], in[2][1], in[2][2], in[2][3]);
+jas_eprintf("[ %f %f %f %f ]\n[ %f %f %f %f ]\n[ %f %f %f %f ]\n",
+out[0][0], out[0][1], out[0][2], out[0][3],
+out[1][0], out[1][1], out[1][2], out[1][3],
+out[2][0], out[2][1], out[2][2], out[2][3]);
+#endif
+	return 0;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static jas_clrspc_t icctoclrspc(jas_iccsig_t iccclrspc, int refflag)
+{
+	if (refflag) {
+		switch (iccclrspc) {
+		case JAS_ICC_COLORSPC_XYZ:
+			return JAS_CLRSPC_CIEXYZ;
+		case JAS_ICC_COLORSPC_LAB:
+			return JAS_CLRSPC_CIELAB;
+		default:
+			abort();
+		}
+	} else {
+		switch (iccclrspc) {
+		case JAS_ICC_COLORSPC_YCBCR:
+			return JAS_CLRSPC_GENYCBCR;
+		case JAS_ICC_COLORSPC_RGB:
+			return JAS_CLRSPC_GENRGB;
+		case JAS_ICC_COLORSPC_GRAY:
+			return JAS_CLRSPC_GENGRAY;
+		default:
+			abort();
+		}
+	}
+	return -1;
+}
+
+static int mono(const jas_iccprof_t *iccprof, int op, jas_cmpxformseq_t **retpxformseq)
+{
+	jas_iccattrval_t *graytrc;
+	jas_cmshapmat_t *shapmat;
+	jas_cmpxform_t *pxform = NULL;
+	jas_cmpxformseq_t *pxformseq = NULL;
+	jas_cmshapmatlut_t lut;
+
+	jas_cmshapmatlut_init(&lut);
+	if (!(graytrc = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRYTRC)) ||
+	  graytrc->type != JAS_ICC_TYPE_CURV)
+		goto error;
+	if (!(pxform = jas_cmpxform_createshapmat()))
+		goto error;
+	shapmat = &pxform->data.shapmat;
+	if (!(pxformseq = jas_cmpxformseq_create()))
+		goto error;
+	if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform))
+		goto error;
+
+	pxform->numinchans = 1;
+	pxform->numoutchans = 3;
+
+	shapmat->mono = 1;
+	shapmat->useluts = 1;
+	shapmat->usemat = 1;
+	if (!op) {
+		shapmat->order = 0;
+		shapmat->mat[0][0] = 0.9642;
+		shapmat->mat[1][0] = 1.0;
+		shapmat->mat[2][0] = 0.8249;
+		if (jas_cmshapmatlut_set(&shapmat->luts[0], &graytrc->data.curv))
+			goto error;
+	} else {
+		shapmat->order = 1;
+		shapmat->mat[0][0] = 1.0 / 0.9642;
+		shapmat->mat[1][0] = 1.0;
+		shapmat->mat[2][0] = 1.0 / 0.8249;
+		jas_cmshapmatlut_init(&lut);
+		if (jas_cmshapmatlut_set(&lut, &graytrc->data.curv))
+			goto error;
+		if (jas_cmshapmatlut_invert(&shapmat->luts[0], &lut, lut.size))
+			goto error;
+		jas_cmshapmatlut_cleanup(&lut);
+	}
+	jas_iccattrval_destroy(graytrc);
+	jas_cmpxform_destroy(pxform);
+	*retpxformseq = pxformseq;
+	return 0;
+error:
+	if (graytrc)
+		jas_iccattrval_destroy(graytrc);
+	if (pxform)
+		jas_cmpxform_destroy(pxform);
+	if (pxformseq)
+		jas_cmpxformseq_destroy(pxformseq);
+	return -1;
+}
+
+static int triclr(const jas_iccprof_t *iccprof, int op, jas_cmpxformseq_t **retpxformseq)
+{
+	jas_iccattrval_t *trcs[3];
+	jas_iccattrval_t *cols[3];
+	jas_cmshapmat_t *shapmat;
+	jas_cmpxform_t *pxform;
+	jas_cmpxformseq_t *pxformseq;
+	jas_cmreal_t mat[3][4];
+	jas_cmshapmatlut_t lut;
+
+	pxform = 0;
+	pxformseq = 0;
+	for (unsigned i = 0; i < 3; ++i) {
+		trcs[i] = 0;
+		cols[i] = 0;
+	}
+	jas_cmshapmatlut_init(&lut);
+
+	if (!(trcs[0] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_REDTRC)) ||
+	  !(trcs[1] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRNTRC)) ||
+	  !(trcs[2] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_BLUTRC)) ||
+	  !(cols[0] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_REDMATCOL)) ||
+	  !(cols[1] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRNMATCOL)) ||
+	  !(cols[2] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_BLUMATCOL)))
+		goto error;
+	for (unsigned i = 0; i < 3; ++i) {
+		if (trcs[i]->type != JAS_ICC_TYPE_CURV ||
+		  cols[i]->type != JAS_ICC_TYPE_XYZ)
+			goto error;
+	}
+	if (!(pxform = jas_cmpxform_createshapmat()))
+		goto error;
+	pxform->numinchans = 3;
+	pxform->numoutchans = 3;
+	shapmat = &pxform->data.shapmat;
+	if (!(pxformseq = jas_cmpxformseq_create()))
+		goto error;
+	if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform))
+		goto error;
+	shapmat->mono = 0;
+	shapmat->useluts = 1;
+	shapmat->usemat = 1;
+	if (!op) {
+		shapmat->order = 0;
+		for (unsigned i = 0; i < 3; ++i) {
+			shapmat->mat[0][i] = (jas_cmreal_t)cols[i]->data.xyz.x / 65536.0;
+			shapmat->mat[1][i] = (jas_cmreal_t)cols[i]->data.xyz.y / 65536.0;
+			shapmat->mat[2][i] = (jas_cmreal_t)cols[i]->data.xyz.z / 65536.0;
+		}
+		for (unsigned i = 0; i < 3; ++i)
+			shapmat->mat[i][3] = 0.0;
+		for (unsigned i = 0; i < 3; ++i) {
+			if (jas_cmshapmatlut_set(&shapmat->luts[i], &trcs[i]->data.curv))
+				goto error;
+		}
+	} else {
+		shapmat->order = 1;
+		for (unsigned i = 0; i < 3; ++i) {
+			mat[0][i] = (jas_cmreal_t)cols[i]->data.xyz.x / 65536.0;
+			mat[1][i] = (jas_cmreal_t)cols[i]->data.xyz.y / 65536.0;
+			mat[2][i] = (jas_cmreal_t)cols[i]->data.xyz.z / 65536.0;
+		}
+		for (unsigned i = 0; i < 3; ++i)
+			mat[i][3] = 0.0;
+		if (jas_cmshapmat_invmat(shapmat->mat, mat))
+			goto error;
+		for (unsigned i = 0; i < 3; ++i) {
+			jas_cmshapmatlut_init(&lut);
+			if (jas_cmshapmatlut_set(&lut, &trcs[i]->data.curv))
+				goto error;
+			if (jas_cmshapmatlut_invert(&shapmat->luts[i], &lut, lut.size))
+				goto error;
+			jas_cmshapmatlut_cleanup(&lut);
+		}
+	}
+	for (unsigned i = 0; i < 3; ++i) {
+		jas_iccattrval_destroy(trcs[i]);
+		jas_iccattrval_destroy(cols[i]);
+	}
+	jas_cmpxform_destroy(pxform);
+	*retpxformseq = pxformseq;
+	return 0;
+
+error:
+
+	for (unsigned i = 0; i < 3; ++i) {
+		if (trcs[i]) {
+			jas_iccattrval_destroy(trcs[i]);
+		}
+		if (cols[i]) {
+			jas_iccattrval_destroy(cols[i]);
+		}
+	}
+	if (pxformseq) {
+		jas_cmpxformseq_destroy(pxformseq);
+	}
+	if (pxform) {
+		jas_cmpxform_destroy(pxform);
+	}
+
+	return -1;
+}
+
+static int jas_cmgetint(const long **bufptr, int sgnd, unsigned prec, long *val)
+{
+	long v;
+	int m;
+	v = **bufptr;
+	if (sgnd) {
+		m = (1 << (prec - 1));
+		if (v < -m || v >= m)
+			return -1;
+	} else {
+		if (v < 0 || v >= (1 << prec))
+			return -1;
+	}
+	++(*bufptr);
+	*val = v;
+	return 0;
+}
+
+static int jas_cmputint(long **bufptr, int sgnd, unsigned prec, long val)
+{
+	int m;
+	if (sgnd) {
+		m = (1 << (prec - 1));
+		if (val < -m || val >= m)
+			return -1;
+	} else {
+		if (val < 0 || val >= (1 << prec))
+			return -1;
+	}
+	**bufptr = val;
+	++(*bufptr);
+	return 0;
+}
+
+unsigned jas_clrspc_numchans(jas_clrspc_t clrspc)
+{
+	switch (jas_clrspc_fam(clrspc)) {
+	case JAS_CLRSPC_FAM_XYZ:
+	case JAS_CLRSPC_FAM_LAB:
+	case JAS_CLRSPC_FAM_RGB:
+	case JAS_CLRSPC_FAM_YCBCR:
+		return 3;
+	case JAS_CLRSPC_FAM_GRAY:
+		return 1;
+	default:
+		abort();
+	}
+	return -1;
+}
+
+jas_iccprof_t *jas_iccprof_createfromcmprof(const jas_cmprof_t *prof)
+{
+	return jas_iccprof_copy(prof->iccprof);
+}
--- /dev/null
+++ b/jas_debug.c
@@ -1,0 +1,152 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_debug.h"
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Local data.
+\******************************************************************************/
+
+static int jas_dbglevel = 0;
+/* The debug level. */
+
+/******************************************************************************\
+* Code for getting/setting the debug level.
+\******************************************************************************/
+
+/* Set the library debug level. */
+int jas_setdbglevel(int dbglevel)
+{
+	int olddbglevel;
+
+	/* Save the old debug level. */
+	olddbglevel = jas_dbglevel;
+
+	/* Change the debug level. */
+	jas_dbglevel = dbglevel;
+
+	/* Return the old debug level. */
+	return olddbglevel;
+}
+
+/* Get the library debug level. */
+int jas_getdbglevel()
+{
+	return jas_dbglevel;
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/* Perform formatted output to standard error. */
+int jas_eprintf(const char *fmt, ...)
+{
+	int ret;
+	va_list ap;
+
+	va_start(ap, fmt);
+	ret = vfprintf(stderr, fmt, ap);
+	va_end(ap);
+	return ret;
+}
+
+/* Dump memory to a stream. */
+int jas_memdump(FILE *out, const void *data, size_t len)
+{
+	size_t i;
+	size_t j;
+	const jas_uchar *dp = data;
+	for (i = 0; i < len; i += 16) {
+		fprintf(out, "%04zx:", i);
+		for (j = 0; j < 16; ++j) {
+			if (i + j < len) {
+				fprintf(out, " %02x", dp[i + j]);
+			}
+		}
+		fprintf(out, "\n");
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+void jas_deprecated(const char *s)
+{
+	static const char message[] =
+	"WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n"
+	"WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n"
+	"WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n"
+	"YOUR CODE IS RELYING ON DEPRECATED FUNCTIONALITY IN THE JASPER LIBRARY.\n"
+	"THIS FUNCTIONALITY WILL BE REMOVED IN THE NEAR FUTURE.\n"
+	"PLEASE FIX THIS PROBLEM BEFORE YOUR CODE STOPS WORKING!\n"
+	;
+	jas_eprintf("%s", message);
+	jas_eprintf("The specific problem is as follows:\n%s\n", s);
+	//abort();
+}
--- /dev/null
+++ b/jas_icc.c
@@ -1,0 +1,1813 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#include "jasper/jas_icc.h"
+#include "jasper/jas_types.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+#include "jasper/jas_cm.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_string.h"
+
+#define	jas_iccputuint8(out, val)	jas_iccputuint(out, 1, val)
+#define	jas_iccputuint16(out, val)	jas_iccputuint(out, 2, val)
+#define	jas_iccputsint32(out, val)	jas_iccputsint(out, 4, val)
+#define	jas_iccputuint32(out, val)	jas_iccputuint(out, 4, val)
+#define	jas_iccputuint64(out, val)	jas_iccputuint(out, 8, val)
+
+static jas_iccattrval_t *jas_iccattrval_create0(void);
+
+static int jas_iccgetuint(jas_stream_t *in, unsigned n, jas_ulonglong *val);
+static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val);
+static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val);
+static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val);
+static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val);
+static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val);
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_iccputuint(jas_stream_t *out, unsigned n, jas_ulonglong val);
+static int jas_iccputsint(jas_stream_t *out, unsigned n, jas_longlong val);
+//#endif /* JAS_ENABLE_ENCODER */
+static jas_iccprof_t *jas_iccprof_create(void);
+static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr);
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_iccprof_writehdr(jas_stream_t *out, const jas_icchdr_t *hdr);
+//#endif
+static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab);
+static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab);
+static int jas_iccattrtab_lookup(const jas_iccattrtab_t *attrtab, jas_iccuint32_t name);
+static jas_iccattrtab_t *jas_iccattrtab_copy(const jas_iccattrtab_t *attrtab);
+static const jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t name);
+static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time);
+static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz);
+static int jas_icctagtabent_cmp(const void *src, const void *dst);
+
+static void jas_icccurv_destroy(jas_iccattrval_t *attrval);
+static int jas_icccurv_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval);
+static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt);
+static unsigned jas_icccurv_getsize(const jas_iccattrval_t *attrval);
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+//#endif
+static void jas_icccurv_dump(const jas_iccattrval_t *attrval, FILE *out);
+
+static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval);
+static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval);
+static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt);
+static unsigned jas_icctxtdesc_getsize(const jas_iccattrval_t *attrval);
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+//#endif
+static void jas_icctxtdesc_dump(const jas_iccattrval_t *attrval, FILE *out);
+
+static void jas_icctxt_destroy(jas_iccattrval_t *attrval);
+static int jas_icctxt_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval);
+static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt);
+static unsigned jas_icctxt_getsize(const jas_iccattrval_t *attrval);
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+//#endif
+static void jas_icctxt_dump(const jas_iccattrval_t *attrval, FILE *out);
+
+static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt);
+static unsigned jas_iccxyz_getsize(const jas_iccattrval_t *attrval);
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+//#endif
+static void jas_iccxyz_dump(const jas_iccattrval_t *attrval, FILE *out);
+
+static jas_iccattrtab_t *jas_iccattrtab_create(void);
+static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab);
+static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, unsigned maxents);
+static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i,
+  jas_iccuint32_t name, jas_iccattrval_t *val);
+static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, unsigned i,
+  jas_iccuint32_t name, jas_iccattrval_t *val);
+static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, unsigned i);
+//#ifdef JAS_ENABLE_ENCODER
+static unsigned jas_iccpadtomult(unsigned x, unsigned y);
+static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, unsigned i,
+  jas_iccattrname_t *name, jas_iccattrval_t **val);
+static int jas_iccprof_puttagtab(jas_stream_t *out, const jas_icctagtab_t *tagtab);
+//#endif /* JAS_ENABLE_ENCODER */
+
+static void jas_icclut16_destroy(jas_iccattrval_t *attrval);
+static int jas_icclut16_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval);
+static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt);
+static unsigned jas_icclut16_getsize(const jas_iccattrval_t *attrval);
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+//#endif
+static void jas_icclut16_dump(const jas_iccattrval_t *attrval, FILE *out);
+
+static void jas_icclut8_destroy(jas_iccattrval_t *attrval);
+static int jas_icclut8_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval);
+static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt);
+static unsigned jas_icclut8_getsize(const jas_iccattrval_t *attrval);
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+//#endif /* JAS_ENABLE_ENCODER */
+static void jas_icclut8_dump(const jas_iccattrval_t *attrval, FILE *out);
+
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_iccputtime(jas_stream_t *out, const jas_icctime_t *ctime);
+static int jas_iccputxyz(jas_stream_t *out, const jas_iccxyz_t *xyz);
+//#endif /* JAS_ENABLE_ENCODER */
+
+static unsigned jas_iccpowi(unsigned x, unsigned n);
+
+static char *jas_iccsigtostr(unsigned sig, char *buf);
+
+
+static const jas_iccattrvalinfo_t jas_iccattrvalinfos[] = {
+	{
+		JAS_ICC_TYPE_CURV, {
+			jas_icccurv_destroy,
+			jas_icccurv_copy,
+			jas_icccurv_input,
+//#ifdef JAS_ENABLE_ENCODER
+			jas_icccurv_output,
+//#endif
+			jas_icccurv_getsize,
+			jas_icccurv_dump,
+		},
+	},
+	{
+		JAS_ICC_TYPE_XYZ,
+		{
+			0,
+			0,
+			jas_iccxyz_input,
+//#ifdef JAS_ENABLE_ENCODER
+			jas_iccxyz_output,
+//#endif
+			jas_iccxyz_getsize,
+			jas_iccxyz_dump,
+		},
+	},
+	{
+		JAS_ICC_TYPE_TXTDESC,
+		{
+			jas_icctxtdesc_destroy,
+			jas_icctxtdesc_copy,
+			jas_icctxtdesc_input,
+//#ifdef JAS_ENABLE_ENCODER
+			jas_icctxtdesc_output,
+//#endif
+			jas_icctxtdesc_getsize,
+			jas_icctxtdesc_dump,
+		},
+	},
+	{
+		JAS_ICC_TYPE_TXT,
+		{
+			jas_icctxt_destroy,
+			jas_icctxt_copy,
+			jas_icctxt_input,
+//#ifdef JAS_ENABLE_ENCODER
+			jas_icctxt_output,
+//#endif
+			jas_icctxt_getsize,
+			jas_icctxt_dump,
+		},
+	},
+	{
+		JAS_ICC_TYPE_LUT8,
+		{
+			jas_icclut8_destroy,
+			jas_icclut8_copy,
+			jas_icclut8_input,
+//#ifdef JAS_ENABLE_ENCODER
+			jas_icclut8_output,
+//#endif
+			jas_icclut8_getsize,
+			jas_icclut8_dump,
+		},
+	},
+	{
+		JAS_ICC_TYPE_LUT16, {
+			jas_icclut16_destroy,
+			jas_icclut16_copy,
+			jas_icclut16_input,
+//#ifdef JAS_ENABLE_ENCODER
+			jas_icclut16_output,
+//#endif
+			jas_icclut16_getsize,
+			jas_icclut16_dump,
+		},
+	},
+	{
+		0,
+		{
+			0,
+			0,
+			0,
+//#ifdef JAS_ENABLE_ENCODER
+			0,
+//#endif
+			0,
+			0,
+		},
+	}
+};
+
+/******************************************************************************\
+* profile class
+\******************************************************************************/
+
+static jas_iccprof_t *jas_iccprof_create()
+{
+	jas_iccprof_t *prof;
+	if (!(prof = jas_malloc(sizeof(jas_iccprof_t)))) {
+		goto error;
+	}
+	if (!(prof->attrtab = jas_iccattrtab_create()))
+		goto error;
+	memset(&prof->hdr, 0, sizeof(jas_icchdr_t));
+	prof->tagtab.numents = 0;
+	prof->tagtab.ents = 0;
+	return prof;
+error:
+	if (prof)
+		jas_iccprof_destroy(prof);
+	return 0;
+}
+
+jas_iccprof_t *jas_iccprof_copy(const jas_iccprof_t *prof)
+{
+	jas_iccprof_t *newprof;
+	if (!(newprof = jas_iccprof_create()))
+		goto error;
+	newprof->hdr = prof->hdr;
+	newprof->tagtab.numents = 0;
+	newprof->tagtab.ents = 0;
+	assert(newprof->attrtab);
+	jas_iccattrtab_destroy(newprof->attrtab);
+	if (!(newprof->attrtab = jas_iccattrtab_copy(prof->attrtab)))
+		goto error;
+	return newprof;
+error:
+	if (newprof)
+		jas_iccprof_destroy(newprof);
+	return 0;
+}
+
+void jas_iccprof_destroy(jas_iccprof_t *prof)
+{
+	if (prof->attrtab)
+		jas_iccattrtab_destroy(prof->attrtab);
+	if (prof->tagtab.ents)
+		jas_free(prof->tagtab.ents);
+	jas_free(prof);
+}
+
+void jas_iccprof_dump(const jas_iccprof_t *prof, FILE *out)
+{
+	jas_iccattrtab_dump(prof->attrtab, out);
+}
+
+jas_iccprof_t *jas_iccprof_load(jas_stream_t *in)
+{
+	jas_iccprof_t *prof;
+	long curoff;
+	long reloff;
+	long prevoff;
+	jas_iccsig_t type;
+	jas_iccattrval_t *attrval;
+	jas_iccattrval_t *prevattrval;
+
+	attrval = 0;
+
+	if (!(prof = jas_iccprof_create())) {
+		goto error;
+	}
+
+	if (jas_iccprof_readhdr(in, &prof->hdr)) {
+		jas_eprintf("cannot get header\n");
+		goto error;
+	}
+	if (jas_iccprof_gettagtab(in, &prof->tagtab)) {
+		jas_eprintf("cannot get tab table\n");
+		goto error;
+	}
+	jas_iccprof_sorttagtab(&prof->tagtab);
+
+	const unsigned numtags = prof->tagtab.numents;
+	curoff = JAS_ICC_HDRLEN + 4 + 12 * numtags;
+	prevoff = 0;
+	prevattrval = 0;
+	for (unsigned i = 0; i < numtags; ++i) {
+		const jas_icctagtabent_t *tagtabent = &prof->tagtab.ents[i];
+		if (tagtabent->off == JAS_CAST(jas_iccuint32_t, prevoff)) {
+			if (prevattrval) {
+				if (!(attrval = jas_iccattrval_clone(prevattrval)))
+					goto error;
+				if (jas_iccprof_setattr(prof, tagtabent->tag, attrval))
+					goto error;
+				jas_iccattrval_destroy(attrval);
+				attrval = 0;
+			} else {
+#if 0
+				jas_eprintf("warning: skipping unknown tag type\n");
+#endif
+			}
+			continue;
+		}
+		reloff = tagtabent->off - curoff;
+		if (reloff > 0) {
+			if (jas_stream_gobble(in, reloff) != reloff)
+				goto error;
+			curoff += reloff;
+		} else if (reloff < 0) {
+			goto error;
+		}
+		prevoff = curoff;
+		if (jas_iccgetuint32(in, &type)) {
+			goto error;
+		}
+		if (jas_stream_gobble(in, 4) != 4) {
+			goto error;
+		}
+		curoff += 8;
+		if (!jas_iccattrvalinfo_lookup(type)) {
+#if 0
+			jas_eprintf("warning: skipping unknown tag type\n");
+#endif
+			prevattrval = 0;
+			continue;
+		}
+		if (!(attrval = jas_iccattrval_create(type))) {
+			goto error;
+		}
+		const unsigned len = tagtabent->len - 8;
+		if ((*attrval->ops->input)(attrval, in, len)) {
+			goto error;
+		}
+		curoff += len;
+		if (jas_iccprof_setattr(prof, tagtabent->tag, attrval)) {
+			goto error;
+		}
+		prevattrval = attrval; /* This is correct, but slimey. */
+		jas_iccattrval_destroy(attrval);
+		attrval = 0;
+	}
+
+	return prof;
+
+error:
+	if (prof)
+		jas_iccprof_destroy(prof);
+	if (attrval)
+		jas_iccattrval_destroy(attrval);
+	return 0;
+}
+
+int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out)
+{
+//#ifdef JAS_ENABLE_ENCODER
+	long curoff;
+	long reloff;
+	long newoff;
+	jas_icctagtabent_t *tagtabent;
+	jas_icctagtabent_t *sharedtagtabent;
+	jas_icctagtabent_t *tmptagtabent;
+	jas_iccuint32_t attrname;
+	jas_iccattrval_t *attrval;
+	jas_icctagtab_t *tagtab;
+
+	tagtab = &prof->tagtab;
+	if (!(tagtab->ents = jas_alloc2(prof->attrtab->numattrs,
+	  sizeof(jas_icctagtabent_t))))
+		goto error;
+	tagtab->numents = prof->attrtab->numattrs;
+	curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents;
+	for (unsigned i = 0; i < tagtab->numents; ++i) {
+		tagtabent = &tagtab->ents[i];
+		if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval))
+			goto error;
+		assert(attrval->ops->output);
+		tagtabent->tag = attrname;
+		tagtabent->data = &attrval->data;
+		sharedtagtabent = 0;
+		for (unsigned j = 0; j < i; ++j) {
+			tmptagtabent = &tagtab->ents[j];
+			if (tagtabent->data == tmptagtabent->data) {
+				sharedtagtabent = tmptagtabent;
+				break;
+			}
+		}
+		if (sharedtagtabent) {
+			tagtabent->off = sharedtagtabent->off;
+			tagtabent->len = sharedtagtabent->len;
+			tagtabent->first = sharedtagtabent;
+		} else {
+			tagtabent->off = curoff;
+			tagtabent->len = (*attrval->ops->getsize)(attrval) + 8;
+			tagtabent->first = 0;
+			if (i < tagtab->numents - 1) {
+				curoff = jas_iccpadtomult(curoff + tagtabent->len, 4);
+			} else {
+				curoff += tagtabent->len;
+			}
+		}
+		jas_iccattrval_destroy(attrval);
+	}
+	prof->hdr.size = curoff;
+	if (jas_iccprof_writehdr(out, &prof->hdr))
+		goto error;
+	if (jas_iccprof_puttagtab(out, &prof->tagtab))
+		goto error;
+	curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents;
+	for (unsigned i = 0; i < tagtab->numents;) {
+		tagtabent = &tagtab->ents[i];
+		assert(curoff == JAS_CAST(long, tagtabent->off));
+		if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval))
+			goto error;
+		if (jas_iccputuint32(out, attrval->type) || jas_stream_pad(out,
+		  4, 0) != 4)
+			goto error;
+		if ((*attrval->ops->output)(attrval, out))
+			goto error;
+		jas_iccattrval_destroy(attrval);
+		curoff += tagtabent->len;
+		++i;
+		while (i < tagtab->numents &&
+		  tagtab->ents[i].first)
+			++i;
+		newoff = (i < tagtab->numents) ?
+		  tagtab->ents[i].off : prof->hdr.size;
+		reloff = newoff - curoff;
+		assert(reloff >= 0);
+		if (reloff > 0) {
+			if (jas_stream_pad(out, reloff, 0) != reloff)
+				goto error;
+			curoff += reloff;
+		}
+	}	
+	return 0;
+error:
+	/* XXX - need to free some resources here */
+//#else
+//	(void)prof;
+//	(void)out;
+//#endif /* JAS_ENABLE_ENCODER */
+	return -1;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+
+static int jas_iccprof_writehdr(jas_stream_t *out, const jas_icchdr_t *hdr)
+{
+	if (jas_iccputuint32(out, hdr->size) ||
+	  jas_iccputuint32(out, hdr->cmmtype) ||
+	  jas_iccputuint32(out, hdr->version) ||
+	  jas_iccputuint32(out, hdr->clas) ||
+	  jas_iccputuint32(out, hdr->colorspc) ||
+	  jas_iccputuint32(out, hdr->refcolorspc) ||
+	  jas_iccputtime(out, &hdr->ctime) ||
+	  jas_iccputuint32(out, hdr->magic) ||
+	  jas_iccputuint32(out, hdr->platform) ||
+	  jas_iccputuint32(out, hdr->flags) ||
+	  jas_iccputuint32(out, hdr->maker) ||
+	  jas_iccputuint32(out, hdr->model) ||
+	  jas_iccputuint64(out, hdr->attr) ||
+	  jas_iccputuint32(out, hdr->intent) ||
+	  jas_iccputxyz(out, &hdr->illum) ||
+	  jas_iccputuint32(out, hdr->creator) ||
+	  jas_stream_pad(out, 44, 0) != 44)
+		return -1;
+	return 0;
+}
+
+static int jas_iccprof_puttagtab(jas_stream_t *out, const jas_icctagtab_t *tagtab)
+{
+	jas_icctagtabent_t *tagtabent;
+	if (jas_iccputuint32(out, tagtab->numents))
+		goto error;
+	for (unsigned i = 0; i < tagtab->numents; ++i) {
+		tagtabent = &tagtab->ents[i];
+		if (jas_iccputuint32(out, tagtabent->tag) ||
+		  jas_iccputuint32(out, tagtabent->off) ||
+		  jas_iccputuint32(out, tagtabent->len))
+			goto error;
+	}
+	return 0;
+error:
+	return -1;
+}
+
+//#endif
+
+static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr)
+{
+	if (jas_iccgetuint32(in, &hdr->size) ||
+	  jas_iccgetuint32(in, &hdr->cmmtype) ||
+	  jas_iccgetuint32(in, &hdr->version) ||
+	  jas_iccgetuint32(in, &hdr->clas) ||
+	  jas_iccgetuint32(in, &hdr->colorspc) ||
+	  jas_iccgetuint32(in, &hdr->refcolorspc) ||
+	  jas_iccgettime(in, &hdr->ctime) ||
+	  jas_iccgetuint32(in, &hdr->magic) ||
+	  jas_iccgetuint32(in, &hdr->platform) ||
+	  jas_iccgetuint32(in, &hdr->flags) ||
+	  jas_iccgetuint32(in, &hdr->maker) ||
+	  jas_iccgetuint32(in, &hdr->model) ||
+	  jas_iccgetuint64(in, &hdr->attr) ||
+	  jas_iccgetuint32(in, &hdr->intent) ||
+	  jas_iccgetxyz(in, &hdr->illum) ||
+	  jas_iccgetuint32(in, &hdr->creator) ||
+	  jas_stream_gobble(in, 44) != 44)
+		return -1;
+	return 0;
+}
+
+static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab)
+{
+	jas_icctagtabent_t *tagtabent;
+
+	if (tagtab->ents) {
+		jas_free(tagtab->ents);
+		tagtab->ents = 0;
+	}
+	if (jas_iccgetuint32(in, &tagtab->numents))
+		goto error;
+	if (!(tagtab->ents = jas_alloc2(tagtab->numents,
+	  sizeof(jas_icctagtabent_t))))
+		goto error;
+	tagtabent = tagtab->ents;
+	for (unsigned i = 0; i < tagtab->numents; ++i) {
+		if (jas_iccgetuint32(in, &tagtabent->tag) ||
+		jas_iccgetuint32(in, &tagtabent->off) ||
+		jas_iccgetuint32(in, &tagtabent->len))
+			goto error;
+		++tagtabent;
+	}
+	return 0;
+error:
+	if (tagtab->ents) {
+		jas_free(tagtab->ents);
+		tagtab->ents = 0;
+	}
+	return -1;
+}
+
+jas_iccattrval_t *jas_iccprof_getattr(const jas_iccprof_t *prof,
+  jas_iccattrname_t name)
+{
+	int i;
+	jas_iccattrval_t *attrval;
+	if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) < 0)
+		goto error;
+	if (!(attrval = jas_iccattrval_clone(prof->attrtab->attrs[i].val)))
+		goto error;
+	return attrval;
+error:
+	return 0;
+}
+
+int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name,
+  jas_iccattrval_t *val)
+{
+	int i;
+	if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) >= 0) {
+		if (val) {
+			if (jas_iccattrtab_replace(prof->attrtab, i, name, val))
+				goto error;
+		} else {
+			jas_iccattrtab_delete(prof->attrtab, i);
+		}
+	} else {
+		if (val) {
+			if (jas_iccattrtab_add(prof->attrtab, -1, name, val))
+				goto error;
+		} else {
+			/* NOP */
+		}
+	}
+	return 0;
+error:
+	return -1;
+}
+
+int jas_iccprof_gethdr(const jas_iccprof_t *prof, jas_icchdr_t *hdr)
+{
+	*hdr = prof->hdr;
+	return 0;
+}
+
+int jas_iccprof_sethdr(jas_iccprof_t *prof, const jas_icchdr_t *hdr)
+{
+	prof->hdr = *hdr;
+	return 0;
+}
+
+static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab)
+{
+	qsort(tagtab->ents, tagtab->numents, sizeof(jas_icctagtabent_t),
+	  jas_icctagtabent_cmp);
+}
+
+static int jas_icctagtabent_cmp(const void *src, const void *dst)
+{
+	const jas_icctagtabent_t *srctagtabent = JAS_CAST(const jas_icctagtabent_t *, src);
+	const jas_icctagtabent_t *dsttagtabent = JAS_CAST(const jas_icctagtabent_t *, dst);
+	if (srctagtabent->off > dsttagtabent->off) {
+		return 1;
+	} else if (srctagtabent->off < dsttagtabent->off) {
+		return -1;
+	}
+	return 0;
+}
+
+static const jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t type)
+{
+	const jas_iccattrvalinfo_t *info;
+	for (info = jas_iccattrvalinfos; info->type; ++info) {
+		if (info->type == type) {
+			return info;
+		}
+	}
+	return 0;
+}
+
+static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time)
+{
+	if (jas_iccgetuint16(in, &time->year) ||
+	  jas_iccgetuint16(in, &time->month) ||
+	  jas_iccgetuint16(in, &time->day) ||
+	  jas_iccgetuint16(in, &time->hour) ||
+	  jas_iccgetuint16(in, &time->min) ||
+	  jas_iccgetuint16(in, &time->sec)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz)
+{
+	if (jas_iccgetsint32(in, &xyz->x) ||
+	  jas_iccgetsint32(in, &xyz->y) ||
+	  jas_iccgetsint32(in, &xyz->z)) {
+		return -1;
+	}
+	return 0;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+
+static int jas_iccputtime(jas_stream_t *out, const jas_icctime_t *time)
+{
+	jas_iccputuint16(out, time->year);
+	jas_iccputuint16(out, time->month);
+	jas_iccputuint16(out, time->day);
+	jas_iccputuint16(out, time->hour);
+	jas_iccputuint16(out, time->min);
+	jas_iccputuint16(out, time->sec);
+	return 0;
+}
+
+static int jas_iccputxyz(jas_stream_t *out, const jas_iccxyz_t *xyz)
+{
+	jas_iccputuint32(out, xyz->x);
+	jas_iccputuint32(out, xyz->y);
+	jas_iccputuint32(out, xyz->z);
+	return 0;
+}
+
+//#endif /* JAS_ENABLE_ENCODER */
+
+/******************************************************************************\
+* attribute table class
+\******************************************************************************/
+
+static jas_iccattrtab_t *jas_iccattrtab_create()
+{
+	jas_iccattrtab_t *tab;
+	if (!(tab = jas_malloc(sizeof(jas_iccattrtab_t))))
+		goto error;
+	tab->maxattrs = 0;
+	tab->numattrs = 0;
+	tab->attrs = 0;
+	if (jas_iccattrtab_resize(tab, 32))
+		goto error;
+	return tab;
+error:
+	if (tab)
+		jas_iccattrtab_destroy(tab);
+	return 0;
+}
+
+static jas_iccattrtab_t *jas_iccattrtab_copy(const jas_iccattrtab_t *attrtab)
+{
+	jas_iccattrtab_t *newattrtab;
+	if (!(newattrtab = jas_iccattrtab_create()))
+		return NULL;
+	for (unsigned i = 0; i < attrtab->numattrs; ++i) {
+		if (jas_iccattrtab_add(newattrtab, i, attrtab->attrs[i].name,
+		  attrtab->attrs[i].val))
+			goto error;
+	}
+	return newattrtab;
+ error:
+	jas_iccattrtab_destroy(newattrtab);
+	return 0;
+}
+
+static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab)
+{
+	if (tab->attrs) {
+		while (tab->numattrs > 0) {
+			jas_iccattrtab_delete(tab, 0);
+		}
+		jas_free(tab->attrs);
+	}
+	jas_free(tab);
+}
+
+void jas_iccattrtab_dump(const jas_iccattrtab_t *attrtab, FILE *out)
+{
+	char buf[16];
+	fprintf(out, "numattrs=%d\n", attrtab->numattrs);
+	fprintf(out, "---\n");
+	for (unsigned i = 0; i < attrtab->numattrs; ++i) {
+		const jas_iccattr_t *attr = &attrtab->attrs[i];
+		const jas_iccattrval_t *attrval = attr->val;
+		const jas_iccattrvalinfo_t *info = jas_iccattrvalinfo_lookup(attrval->type);
+		assert(info);
+		(void)info;
+		fprintf(out, "attrno=%d; attrname=\"%s\"(0x%08"PRIxFAST32"); attrtype=\"%s\"(0x%08"PRIxFAST32")\n",
+		  i,
+		  jas_iccsigtostr(attr->name, &buf[0]),
+		  attr->name,
+		  jas_iccsigtostr(attrval->type, &buf[8]),
+		  attrval->type
+		  );
+		jas_iccattrval_dump(attrval, out);
+		fprintf(out, "---\n");
+	}
+}
+
+static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, unsigned maxents)
+{
+	jas_iccattr_t *newattrs;
+	assert(maxents >= tab->numattrs);
+	newattrs = tab->attrs ? jas_realloc2(tab->attrs, maxents,
+	  sizeof(jas_iccattr_t)) : jas_alloc2(maxents, sizeof(jas_iccattr_t));
+	if (!newattrs) {
+		return -1;
+	}
+	tab->attrs = newattrs;
+	tab->maxattrs = maxents;
+	return 0;
+}
+
+static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i,
+  jas_iccuint32_t name, jas_iccattrval_t *val)
+{
+	jas_iccattr_t *attr;
+	jas_iccattrval_t *tmpattrval;
+	if (i < 0) {
+		i = attrtab->numattrs;
+	}
+	assert(i >= 0 && (unsigned)i <= attrtab->numattrs);
+	if (attrtab->numattrs >= attrtab->maxattrs) {
+		if (jas_iccattrtab_resize(attrtab, attrtab->numattrs + 32)) {
+			return -1;
+		}
+	}
+	if (!(tmpattrval = jas_iccattrval_clone(val)))
+		return -1;
+	const unsigned n = attrtab->numattrs - i;
+	if (n > 0)
+		memmove(&attrtab->attrs[i + 1], &attrtab->attrs[i],
+		  n * sizeof(jas_iccattr_t));
+	attr = &attrtab->attrs[i];
+	attr->name = name;
+	attr->val = tmpattrval;
+	++attrtab->numattrs;
+	return 0;
+}
+
+static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, unsigned i,
+  jas_iccuint32_t name, jas_iccattrval_t *val)
+{
+	jas_iccattrval_t *newval;
+	jas_iccattr_t *attr;
+	if (!(newval = jas_iccattrval_clone(val)))
+		goto error;
+	attr = &attrtab->attrs[i];
+	jas_iccattrval_destroy(attr->val);
+	attr->name = name;
+	attr->val = newval;
+	return 0;
+error:
+	return -1;
+}
+
+static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, unsigned i)
+{
+	unsigned n;
+	jas_iccattrval_destroy(attrtab->attrs[i].val);
+	if ((n = attrtab->numattrs - i - 1) > 0)
+		memmove(&attrtab->attrs[i], &attrtab->attrs[i + 1],
+		  n * sizeof(jas_iccattr_t));
+	--attrtab->numattrs;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, unsigned i,
+  jas_iccattrname_t *name, jas_iccattrval_t **val)
+{
+	jas_iccattr_t *attr;
+	if (i >= attrtab->numattrs)
+		goto error;
+	attr = &attrtab->attrs[i];
+	*name = attr->name;
+	if (!(*val = jas_iccattrval_clone(attr->val)))
+		goto error;
+	return 0;
+error:
+	return -1;
+}
+//#endif /* JAS_ENABLE_ENCODER */
+
+static int jas_iccattrtab_lookup(const jas_iccattrtab_t *attrtab,
+  jas_iccuint32_t name)
+{
+	jas_iccattr_t *attr;
+	for (unsigned i = 0; i < attrtab->numattrs; ++i) {
+		attr = &attrtab->attrs[i];
+		if (attr->name == name)
+			return i;
+	}
+	return -1;
+}
+
+/******************************************************************************\
+* attribute value class
+\******************************************************************************/
+
+jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type)
+{
+	jas_iccattrval_t *attrval;
+	const jas_iccattrvalinfo_t *info;
+
+	if (!(info = jas_iccattrvalinfo_lookup(type)))
+		goto error;
+	if (!(attrval = jas_iccattrval_create0()))
+		goto error;
+	attrval->ops = &info->ops;
+	attrval->type = type;
+	++attrval->refcnt;
+	memset(&attrval->data, 0, sizeof(attrval->data));
+	return attrval;
+error:
+	return 0;
+}
+
+jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval)
+{
+	++attrval->refcnt;
+	return attrval;
+}
+
+void jas_iccattrval_destroy(jas_iccattrval_t *attrval)
+{
+#if 0
+jas_eprintf("refcnt=%d\n", attrval->refcnt);
+#endif
+	if (--attrval->refcnt <= 0) {
+		if (attrval->ops->destroy)
+			(*attrval->ops->destroy)(attrval);
+		jas_free(attrval);
+	}
+}
+
+void jas_iccattrval_dump(const jas_iccattrval_t *attrval, FILE *out)
+{
+	char buf[8];
+	jas_iccsigtostr(attrval->type, buf);
+	fprintf(out, "refcnt = %d; type = 0x%08"PRIxFAST32" %s\n", attrval->refcnt,
+	  attrval->type, jas_iccsigtostr(attrval->type, &buf[0]));
+	if (attrval->ops->dump) {
+		(*attrval->ops->dump)(attrval, out);
+	}
+}
+
+int jas_iccattrval_allowmodify(jas_iccattrval_t **attrvalx)
+{
+	jas_iccattrval_t *newattrval;
+	jas_iccattrval_t *attrval = *attrvalx;
+	if (attrval->refcnt > 1) {
+		if (!(newattrval = jas_iccattrval_create0()))
+			goto error;
+		newattrval->ops = attrval->ops;
+		newattrval->type = attrval->type;
+		++newattrval->refcnt;
+		if (newattrval->ops->copy) {
+			if ((*newattrval->ops->copy)(newattrval, attrval))
+				goto error;
+		} else {
+			memcpy(&newattrval->data, &attrval->data,
+			  sizeof(newattrval->data));
+		}
+		*attrvalx = newattrval;
+	}
+	return 0;
+error:
+	if (newattrval) {
+		jas_free(newattrval);
+	}
+	return -1;
+}
+
+static jas_iccattrval_t *jas_iccattrval_create0()
+{
+	jas_iccattrval_t *attrval;
+	if (!(attrval = jas_malloc(sizeof(jas_iccattrval_t))))
+		return 0;
+	memset(attrval, 0, sizeof(jas_iccattrval_t));
+	attrval->refcnt = 0;
+	attrval->ops = 0;
+	attrval->type = 0;
+	return attrval;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned len)
+{
+	assert(len == 4 * 3);
+	(void)len;
+	return jas_iccgetxyz(in, &attrval->data.xyz);
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+	const jas_iccxyz_t *xyz = &attrval->data.xyz;
+	if (jas_iccputuint32(out, xyz->x) ||
+	  jas_iccputuint32(out, xyz->y) ||
+	  jas_iccputuint32(out, xyz->z))
+		return -1;
+	return 0;
+}
+//#endif /* JAS_ENABLE_ENCODER */
+
+static unsigned jas_iccxyz_getsize(const jas_iccattrval_t *attrval)
+{
+	/* Avoid compiler warnings about unused parameters. */
+	USED(attrval);
+
+	return 12;
+}
+
+static void jas_iccxyz_dump(const jas_iccattrval_t *attrval, FILE *out)
+{
+	const jas_iccxyz_t *xyz = &attrval->data.xyz;
+	fprintf(out, "(%f, %f, %f)\n", xyz->x / 65536.0, xyz->y / 65536.0, xyz->z / 65536.0);
+}
+
+/******************************************************************************\
+* attribute table class
+\******************************************************************************/
+
+static void jas_icccurv_destroy(jas_iccattrval_t *attrval)
+{
+	jas_icccurv_t *curv = &attrval->data.curv;
+	if (curv->ents) {
+		jas_free(curv->ents);
+		curv->ents = 0;
+	}
+}
+
+static int jas_icccurv_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval)
+{
+	/* Avoid compiler warnings about unused parameters. */
+	USED(attrval);
+	USED(othattrval);
+
+	/* Not yet implemented. */
+	abort();
+	return -1;
+}
+
+static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt)
+{
+	jas_icccurv_t *curv = &attrval->data.curv;
+
+	curv->numents = 0;
+	curv->ents = 0;
+
+	if (jas_iccgetuint32(in, &curv->numents))
+		goto error;
+	if (!(curv->ents = jas_alloc2(curv->numents, sizeof(jas_iccuint16_t))))
+		goto error;
+	for (unsigned i = 0; i < curv->numents; ++i) {
+		if (jas_iccgetuint16(in, &curv->ents[i]))
+			goto error;
+	}
+
+	if (4 + 2 * curv->numents != cnt)
+		goto error;
+	return 0;
+
+error:
+	jas_icccurv_destroy(attrval);
+	return -1;
+}
+
+static unsigned jas_icccurv_getsize(const jas_iccattrval_t *attrval)
+{
+	const jas_icccurv_t *curv = &attrval->data.curv;
+	return 4 + 2 * curv->numents;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+	const jas_icccurv_t *curv = &attrval->data.curv;
+
+	if (jas_iccputuint32(out, curv->numents))
+		goto error;
+	for (unsigned i = 0; i < curv->numents; ++i) {
+		if (jas_iccputuint16(out, curv->ents[i]))
+			goto error;
+	}
+	return 0;
+error:
+	return -1;
+}
+//#endif /* JAS_ENABLE_ENCODER */
+
+static void jas_icccurv_dump(const jas_iccattrval_t *attrval, FILE *out)
+{
+	const jas_icccurv_t *curv = &attrval->data.curv;
+	fprintf(out, "number of entries = %"PRIuFAST32"\n", curv->numents);
+	if (curv->numents == 1) {
+		fprintf(out, "gamma = %f\n", curv->ents[0] / 256.0);
+	} else {
+		for (unsigned i = 0; i < curv->numents; ++i) {
+			if (i < 3 || i >= curv->numents - 3) {
+				fprintf(out, "entry[%d] = %f\n", i, curv->ents[i] / 65535.0);
+			}
+		}
+	}
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval)
+{
+	jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+	if (txtdesc->ascdata) {
+		jas_free(txtdesc->ascdata);
+		txtdesc->ascdata = 0;
+	}
+	if (txtdesc->ucdata) {
+		jas_free(txtdesc->ucdata);
+		txtdesc->ucdata = 0;
+	}
+}
+
+static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval)
+{
+	jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+
+	/* Avoid compiler warnings about unused parameters. */
+	USED(attrval);
+	USED(othattrval);
+	USED(txtdesc);
+
+	/* Not yet implemented. */
+	abort();
+	return -1;
+}
+
+static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt)
+{
+	int c;
+	jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+	txtdesc->ascdata = 0;
+	txtdesc->ucdata = 0;
+	if (jas_iccgetuint32(in, &txtdesc->asclen))
+		goto error;
+	if (txtdesc->asclen < 1)
+		goto error;
+	if (!(txtdesc->ascdata = jas_malloc(txtdesc->asclen)))
+		goto error;
+	if (jas_stream_read(in, txtdesc->ascdata, txtdesc->asclen) !=
+	  txtdesc->asclen)
+		goto error;
+	txtdesc->ascdata[txtdesc->asclen - 1] = '\0';
+	if (jas_iccgetuint32(in, &txtdesc->uclangcode) ||
+	  jas_iccgetuint32(in, &txtdesc->uclen))
+		goto error;
+	if (!(txtdesc->ucdata = jas_alloc2(txtdesc->uclen, 2)))
+		goto error;
+	if (jas_stream_read(in, txtdesc->ucdata, txtdesc->uclen * 2) !=
+	  txtdesc->uclen * 2)
+		goto error;
+	if (jas_iccgetuint16(in, &txtdesc->sccode))
+		goto error;
+	if ((c = jas_stream_getc(in)) == EOF)
+		goto error;
+	txtdesc->maclen = c;
+	if (jas_stream_read(in, txtdesc->macdata, 67) != 67)
+		goto error;
+	txtdesc->asclen = JAS_CAST(jas_iccuint32_t, strlen(txtdesc->ascdata) + 1);
+#define WORKAROUND_BAD_PROFILES
+#ifdef WORKAROUND_BAD_PROFILES
+	const unsigned n = txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67;
+	if (n > cnt) {
+		return -1;
+	}
+	if (n < cnt) {
+		if (jas_stream_gobble(in, cnt - n) != (int)(cnt - n))
+			goto error;
+	}
+#else
+	if (txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67 != cnt)
+		return -1;
+#endif
+	return 0;
+error:
+	jas_icctxtdesc_destroy(attrval);
+	return -1;
+}
+
+static unsigned jas_icctxtdesc_getsize(const jas_iccattrval_t *attrval)
+{
+	const jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+	return strlen(txtdesc->ascdata) + 1 + txtdesc->uclen * 2 + 15 + 67;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+	const jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+	if (jas_iccputuint32(out, txtdesc->asclen) ||
+	  jas_stream_puts(out, txtdesc->ascdata) ||
+	  jas_stream_putc(out, 0) == EOF ||
+	  jas_iccputuint32(out, txtdesc->uclangcode) ||
+	  jas_iccputuint32(out, txtdesc->uclen) ||
+	  jas_stream_write(out, txtdesc->ucdata, txtdesc->uclen * 2) != txtdesc->uclen * 2 ||
+	  jas_iccputuint16(out, txtdesc->sccode) ||
+	  jas_stream_putc(out, txtdesc->maclen) == EOF)
+		goto error;
+	if (txtdesc->maclen > 0) {
+		if (jas_stream_write(out, txtdesc->macdata, 67) != 67)
+			goto error;
+	} else {
+		if (jas_stream_pad(out, 67, 0) != 67)
+			goto error;
+	}
+	return 0;
+error:
+	return -1;
+}
+//#endif /* JAS_ENABLE_ENCODER */
+
+static void jas_icctxtdesc_dump(const jas_iccattrval_t *attrval, FILE *out)
+{
+	const jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+	fprintf(out, "ascii = \"%s\"\n", txtdesc->ascdata);
+	fprintf(out, "uclangcode = %"PRIuFAST32"; uclen = %"PRIuFAST32"\n",
+	  txtdesc->uclangcode, txtdesc->uclen);
+	fprintf(out, "sccode = %"PRIuFAST16"\n", txtdesc->sccode);
+	fprintf(out, "maclen = %d\n", txtdesc->maclen);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jas_icctxt_destroy(jas_iccattrval_t *attrval)
+{
+	jas_icctxt_t *txt = &attrval->data.txt;
+	if (txt->string) {
+		jas_free(txt->string);
+		txt->string = 0;
+	}
+}
+
+static int jas_icctxt_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval)
+{
+	jas_icctxt_t *txt = &attrval->data.txt;
+	const jas_icctxt_t *othtxt = &othattrval->data.txt;
+	if (!(txt->string = jas_strdup(othtxt->string)))
+		return -1;
+	return 0;
+}
+
+static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt)
+{
+	jas_icctxt_t *txt = &attrval->data.txt;
+	txt->string = 0;
+	if (!(txt->string = jas_malloc(cnt)))
+		goto error;
+	if (jas_stream_read(in, txt->string, cnt) != cnt)
+		goto error;
+	txt->string[cnt - 1] = '\0';
+	if (strlen(txt->string) + 1 != cnt)
+		goto error;
+	return 0;
+error:
+	jas_icctxt_destroy(attrval);
+	return -1;
+}
+
+static unsigned jas_icctxt_getsize(const jas_iccattrval_t *attrval)
+{
+	const jas_icctxt_t *txt = &attrval->data.txt;
+	return strlen(txt->string) + 1;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+	const jas_icctxt_t *txt = &attrval->data.txt;
+	if (jas_stream_puts(out, txt->string) ||
+	  jas_stream_putc(out, 0) == EOF)
+		return -1;
+	return 0;
+}
+//#endif /* JAS_ENABLE_ENCODER */
+
+static void jas_icctxt_dump(const jas_iccattrval_t *attrval, FILE *out)
+{
+	const jas_icctxt_t *txt = &attrval->data.txt;
+	fprintf(out, "string = \"%s\"\n", txt->string);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jas_icclut8_destroy(jas_iccattrval_t *attrval)
+{
+	jas_icclut8_t *lut8 = &attrval->data.lut8;
+	if (lut8->clut) {
+		jas_free(lut8->clut);
+		lut8->clut = 0;
+	}
+	if (lut8->intabs) {
+		jas_free(lut8->intabs);
+		lut8->intabs = 0;
+	}
+	if (lut8->intabsbuf) {
+		jas_free(lut8->intabsbuf);
+		lut8->intabsbuf = 0;
+	}
+	if (lut8->outtabs) {
+		jas_free(lut8->outtabs);
+		lut8->outtabs = 0;
+	}
+	if (lut8->outtabsbuf) {
+		jas_free(lut8->outtabsbuf);
+		lut8->outtabsbuf = 0;
+	}
+}
+
+static int jas_icclut8_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval)
+{
+	/* Avoid compiler warnings about unused parameters. */
+	USED(attrval);
+	USED(othattrval);
+	abort();
+	return -1;
+}
+
+static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt)
+{
+	jas_icclut8_t *lut8 = &attrval->data.lut8;
+	lut8->clut = 0;
+	lut8->intabs = 0;
+	lut8->intabsbuf = 0;
+	lut8->outtabs = 0;
+	lut8->outtabsbuf = 0;
+	if (jas_iccgetuint8(in, &lut8->numinchans) ||
+	  jas_iccgetuint8(in, &lut8->numoutchans) ||
+	  jas_iccgetuint8(in, &lut8->clutlen) ||
+	  jas_stream_getc(in) == EOF)
+		goto error;
+	for (unsigned i = 0; i < 3; ++i) {
+		for (unsigned j = 0; j < 3; ++j) {
+			if (jas_iccgetsint32(in, &lut8->e[i][j]))
+				goto error;
+		}
+	}
+	if (jas_iccgetuint16(in, &lut8->numintabents) ||
+	  jas_iccgetuint16(in, &lut8->numouttabents))
+		goto error;
+	const unsigned clutsize = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans;
+	if (!(lut8->clut = jas_alloc2(clutsize, sizeof(jas_iccuint8_t))) ||
+	  !(lut8->intabsbuf = jas_alloc3(lut8->numinchans,
+	  lut8->numintabents, sizeof(jas_iccuint8_t))) ||
+	  !(lut8->intabs = jas_alloc2(lut8->numinchans,
+	  sizeof(jas_iccuint8_t *))))
+		goto error;
+	for (unsigned i = 0; i < lut8->numinchans; ++i)
+		lut8->intabs[i] = &lut8->intabsbuf[i * lut8->numintabents];
+	if (!(lut8->outtabsbuf = jas_alloc3(lut8->numoutchans,
+	  lut8->numouttabents, sizeof(jas_iccuint8_t))) ||
+	  !(lut8->outtabs = jas_alloc2(lut8->numoutchans,
+	  sizeof(jas_iccuint8_t *))))
+		goto error;
+	for (unsigned i = 0; i < lut8->numoutchans; ++i)
+		lut8->outtabs[i] = &lut8->outtabsbuf[i * lut8->numouttabents];
+	for (unsigned i = 0; i < lut8->numinchans; ++i) {
+		for (unsigned j = 0; j < lut8->numintabents; ++j) {
+			if (jas_iccgetuint8(in, &lut8->intabs[i][j]))
+				goto error;
+		}
+	}
+	for (unsigned i = 0; i < lut8->numoutchans; ++i) {
+		for (unsigned j = 0; j < lut8->numouttabents; ++j) {
+			if (jas_iccgetuint8(in, &lut8->outtabs[i][j]))
+				goto error;
+		}
+	}
+	for (unsigned i = 0; i < clutsize; ++i) {
+		if (jas_iccgetuint8(in, &lut8->clut[i]))
+			goto error;
+	}
+	if (44 + lut8->numinchans * lut8->numintabents +
+	  lut8->numoutchans * lut8->numouttabents +
+	  jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans !=
+	  cnt)
+		goto error;
+	return 0;
+error:
+	jas_icclut8_destroy(attrval);
+	return -1;
+}
+
+static unsigned jas_icclut8_getsize(const jas_iccattrval_t *attrval)
+{
+	const jas_icclut8_t *lut8 = &attrval->data.lut8;
+	return 44 + lut8->numinchans * lut8->numintabents +
+	  lut8->numoutchans * lut8->numouttabents +
+	  jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+	jas_icclut8_t *lut8 = &attrval->data.lut8;
+	lut8->clut = 0;
+	lut8->intabs = 0;
+	lut8->intabsbuf = 0;
+	lut8->outtabs = 0;
+	lut8->outtabsbuf = 0;
+	if (jas_stream_putc(out, lut8->numinchans) == EOF ||
+	  jas_stream_putc(out, lut8->numoutchans) == EOF ||
+	  jas_stream_putc(out, lut8->clutlen) == EOF ||
+	  jas_stream_putc(out, 0) == EOF)
+		goto error;
+	for (unsigned i = 0; i < 3; ++i) {
+		for (unsigned j = 0; j < 3; ++j) {
+			if (jas_iccputsint32(out, lut8->e[i][j]))
+				goto error;
+		}
+	}
+	if (jas_iccputuint16(out, lut8->numintabents) ||
+	  jas_iccputuint16(out, lut8->numouttabents))
+		goto error;
+	for (unsigned i = 0, n = lut8->numinchans * lut8->numintabents; i < n; ++i) {
+		if (jas_iccputuint8(out, lut8->intabsbuf[i]))
+			goto error;
+	}
+	for (unsigned i = 0, n = lut8->numoutchans * lut8->numouttabents; i < n; ++i) {
+		if (jas_iccputuint8(out, lut8->outtabsbuf[i]))
+			goto error;
+	}
+	for (unsigned i = 0, n = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; i < n; ++i) {
+		if (jas_iccputuint8(out, lut8->clut[i]))
+			goto error;
+	}
+	return 0;
+error:
+	return -1;
+}
+//#endif /* JAS_ENABLE_ENCODER */
+
+static void jas_icclut8_dump(const jas_iccattrval_t *attrval, FILE *out)
+{
+	const jas_icclut8_t *lut8 = &attrval->data.lut8;
+	fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n",
+	  lut8->numinchans, lut8->numoutchans, lut8->clutlen);
+	for (unsigned i = 0; i < 3; ++i) {
+		for (unsigned j = 0; j < 3; ++j) {
+			fprintf(out, "e[%d][%d]=%f ", i, j, lut8->e[i][j] / 65536.0);
+		}
+		fprintf(out, "\n");
+	}
+	fprintf(out, "numintabents=%"PRIuFAST16", numouttabents=%"PRIuFAST16"\n",
+	  lut8->numintabents, lut8->numouttabents);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jas_icclut16_destroy(jas_iccattrval_t *attrval)
+{
+	jas_icclut16_t *lut16 = &attrval->data.lut16;
+	if (lut16->clut) {
+		jas_free(lut16->clut);
+		lut16->clut = 0;
+	}
+	if (lut16->intabs) {
+		jas_free(lut16->intabs);
+		lut16->intabs = 0;
+	}
+	if (lut16->intabsbuf) {
+		jas_free(lut16->intabsbuf);
+		lut16->intabsbuf = 0;
+	}
+	if (lut16->outtabs) {
+		jas_free(lut16->outtabs);
+		lut16->outtabs = 0;
+	}
+	if (lut16->outtabsbuf) {
+		jas_free(lut16->outtabsbuf);
+		lut16->outtabsbuf = 0;
+	}
+}
+
+static int jas_icclut16_copy(jas_iccattrval_t *attrval,
+  const jas_iccattrval_t *othattrval)
+{
+	/* Avoid compiler warnings about unused parameters. */
+	USED(attrval);
+	USED(othattrval);
+	/* Not yet implemented. */
+	abort();
+	return -1;
+}
+
+static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+  unsigned cnt)
+{
+	jas_icclut16_t *lut16 = &attrval->data.lut16;
+	lut16->clut = 0;
+	lut16->intabs = 0;
+	lut16->intabsbuf = 0;
+	lut16->outtabs = 0;
+	lut16->outtabsbuf = 0;
+	if (jas_iccgetuint8(in, &lut16->numinchans) ||
+	  jas_iccgetuint8(in, &lut16->numoutchans) ||
+	  jas_iccgetuint8(in, &lut16->clutlen) ||
+	  jas_stream_getc(in) == EOF)
+		goto error;
+	for (unsigned i = 0; i < 3; ++i) {
+		for (unsigned j = 0; j < 3; ++j) {
+			if (jas_iccgetsint32(in, &lut16->e[i][j]))
+				goto error;
+		}
+	}
+	if (jas_iccgetuint16(in, &lut16->numintabents) ||
+	  jas_iccgetuint16(in, &lut16->numouttabents))
+		goto error;
+	const unsigned clutsize = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans;
+	if (!(lut16->clut = jas_alloc2(clutsize, sizeof(jas_iccuint16_t))) ||
+	  !(lut16->intabsbuf = jas_alloc3(lut16->numinchans,
+	  lut16->numintabents, sizeof(jas_iccuint16_t))) ||
+	  !(lut16->intabs = jas_alloc2(lut16->numinchans,
+	  sizeof(jas_iccuint16_t *))))
+		goto error;
+	for (unsigned i = 0; i < lut16->numinchans; ++i)
+		lut16->intabs[i] = &lut16->intabsbuf[i * lut16->numintabents];
+	if (!(lut16->outtabsbuf = jas_alloc3(lut16->numoutchans,
+	  lut16->numouttabents, sizeof(jas_iccuint16_t))) ||
+	  !(lut16->outtabs = jas_alloc2(lut16->numoutchans,
+	  sizeof(jas_iccuint16_t *))))
+		goto error;
+	for (unsigned i = 0; i < lut16->numoutchans; ++i)
+		lut16->outtabs[i] = &lut16->outtabsbuf[i * lut16->numouttabents];
+	for (unsigned i = 0; i < lut16->numinchans; ++i) {
+		for (unsigned j = 0; j < lut16->numintabents; ++j) {
+			if (jas_iccgetuint16(in, &lut16->intabs[i][j]))
+				goto error;
+		}
+	}
+	for (unsigned i = 0; i < lut16->numoutchans; ++i) {
+		for (unsigned j = 0; j < lut16->numouttabents; ++j) {
+			if (jas_iccgetuint16(in, &lut16->outtabs[i][j]))
+				goto error;
+		}
+	}
+	for (unsigned i = 0; i < clutsize; ++i) {
+		if (jas_iccgetuint16(in, &lut16->clut[i]))
+			goto error;
+	}
+	if (44 + 2 * (lut16->numinchans * lut16->numintabents +
+          lut16->numoutchans * lut16->numouttabents +
+          jas_iccpowi(lut16->clutlen, lut16->numinchans) *
+	  lut16->numoutchans) != cnt)
+		goto error;
+	return 0;
+error:
+	jas_icclut16_destroy(attrval);
+	return -1;
+}
+
+static unsigned jas_icclut16_getsize(const jas_iccattrval_t *attrval)
+{
+	const jas_icclut16_t *lut16 = &attrval->data.lut16;
+	return 44 + 2 * (lut16->numinchans * lut16->numintabents +
+	  lut16->numoutchans * lut16->numouttabents +
+	  jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans);
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+	const jas_icclut16_t *lut16 = &attrval->data.lut16;
+	if (jas_stream_putc(out, lut16->numinchans) == EOF ||
+	  jas_stream_putc(out, lut16->numoutchans) == EOF ||
+	  jas_stream_putc(out, lut16->clutlen) == EOF ||
+	  jas_stream_putc(out, 0) == EOF)
+		goto error;
+	for (unsigned i = 0; i < 3; ++i) {
+		for (unsigned j = 0; j < 3; ++j) {
+			if (jas_iccputsint32(out, lut16->e[i][j]))
+				goto error;
+		}
+	}
+	if (jas_iccputuint16(out, lut16->numintabents) ||
+	  jas_iccputuint16(out, lut16->numouttabents))
+		goto error;
+	for (unsigned i = 0, n = lut16->numinchans * lut16->numintabents; i < n; ++i) {
+		if (jas_iccputuint16(out, lut16->intabsbuf[i]))
+			goto error;
+	}
+	for (unsigned i = 0, n = lut16->numoutchans * lut16->numouttabents; i < n; ++i) {
+		if (jas_iccputuint16(out, lut16->outtabsbuf[i]))
+			goto error;
+	}
+	for (unsigned i = 0, n = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans; i < n; ++i) {
+		if (jas_iccputuint16(out, lut16->clut[i]))
+			goto error;
+	}
+	return 0;
+error:
+	return -1;
+}
+//#endif /* JAS_ENABLE_ENCODER */
+
+static void jas_icclut16_dump(const jas_iccattrval_t *attrval, FILE *out)
+{
+	const jas_icclut16_t *lut16 = &attrval->data.lut16;
+	fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n",
+	  lut16->numinchans, lut16->numoutchans, lut16->clutlen);
+	for (unsigned i = 0; i < 3; ++i) {
+		for (unsigned j = 0; j < 3; ++j) {
+			fprintf(out, "e[%d][%d]=%f ", i, j, lut16->e[i][j] / 65536.0);
+		}
+		fprintf(out, "\n");
+	}
+	fprintf(out, "numintabents=%"PRIuFAST16", numouttabents=%"PRIuFAST16"\n",
+	  lut16->numintabents, lut16->numouttabents);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int jas_iccgetuint(jas_stream_t *in, unsigned n, jas_ulonglong *val)
+{
+	int c;
+	jas_ulonglong v;
+	v = 0;
+	for (unsigned i = n; i > 0; --i) {
+		if ((c = jas_stream_getc(in)) == EOF)
+			return -1;
+		v = (v << 8) | c;
+	}
+	*val = v;
+	return 0;
+}
+
+static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val)
+{
+	int c;
+	if ((c = jas_stream_getc(in)) == EOF)
+		return -1;
+	*val = c;
+	return 0;
+}
+
+static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
+{
+	jas_ulonglong tmp;
+	if (jas_iccgetuint(in, 2, &tmp))
+		return -1;
+	*val = (jas_iccuint16_t)tmp;
+	return 0;
+}
+
+static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val)
+{
+	jas_ulonglong tmp;
+	if (jas_iccgetuint(in, 4, &tmp))
+		return -1;
+	*val = (tmp & 0x80000000) ? (-JAS_CAST(jas_longlong, (((~tmp) &
+	  0x7fffffff) + 1))) : JAS_CAST(jas_longlong, tmp);
+	return 0;
+}
+
+static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)
+{
+	jas_ulonglong tmp;
+	if (jas_iccgetuint(in, 4, &tmp))
+		return -1;
+	*val = (jas_iccuint32_t)tmp;
+	return 0;
+}
+
+static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
+{
+	jas_ulonglong tmp;
+	if (jas_iccgetuint(in, 8, &tmp))
+		return -1;
+	*val = (jas_iccuint64_t)tmp;
+	return 0;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+
+static int jas_iccputuint(jas_stream_t *out, unsigned n, jas_ulonglong val)
+{
+	int c;
+	for (unsigned i = n; i > 0; --i) {
+		c = (val >> (8 * (i - 1))) & 0xff;
+		if (jas_stream_putc(out, c) == EOF)
+			return -1;
+	}
+	return 0;
+}
+
+static int jas_iccputsint(jas_stream_t *out, unsigned n, jas_longlong val)
+{
+	assert(val >= 0);
+	jas_ulonglong tmp;
+	tmp = (val < 0) ? 0 : val;
+	return jas_iccputuint(out, n, tmp);
+}
+
+//#endif /* JAS_ENABLE_ENCODER */
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static char *jas_iccsigtostr(unsigned sig, char *buf)
+{
+	int c;
+	char *bufptr;
+	bufptr = buf;
+	for (unsigned n = 4; n > 0; --n) {
+		c = (sig >> 24) & 0xff;
+		if (isalpha(c) || isdigit(c)) {
+			*bufptr++ = c;
+		}
+		sig <<= 8;
+	}
+	*bufptr = '\0';
+	return buf;
+}
+
+//#ifdef JAS_ENABLE_ENCODER
+static unsigned jas_iccpadtomult(unsigned x, unsigned y)
+{
+	return ((x + y - 1) / y) * y;
+}
+//#endif /* JAS_ENABLE_ENCODER */
+
+static unsigned jas_iccpowi(unsigned x, unsigned n)
+{
+	unsigned y;
+	y = 1;
+	while (n-- > 0)
+		y *= x;
+	return y;
+}
+
+
+jas_iccprof_t *jas_iccprof_createfrombuf(const jas_uchar *buf, unsigned len)
+{
+	jas_stream_t *in;
+	jas_iccprof_t *prof;
+	if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len)))
+		goto error;
+	if (!(prof = jas_iccprof_load(in)))
+		goto error;
+	jas_stream_close(in);
+	return prof;
+error:
+	if (in)
+		jas_stream_close(in);
+	return 0;
+}
+
+jas_iccprof_t *jas_iccprof_createfromclrspc(unsigned clrspc)
+{
+	jas_iccprof_t *prof;
+	switch (clrspc) {
+	case JAS_CLRSPC_SRGB:
+		prof = jas_iccprof_createfrombuf(jas_iccprofdata_srgb,
+		  jas_iccprofdata_srgblen);
+		break;
+	case JAS_CLRSPC_SGRAY:
+		prof = jas_iccprof_createfrombuf(jas_iccprofdata_sgray,
+		  jas_iccprofdata_sgraylen);
+		break;
+	default:
+		prof = 0;
+		break;
+	}
+	return prof;
+}
--- /dev/null
+++ b/jas_iccdata.c
@@ -1,0 +1,517 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#include <jasper/jas_config.h> /* IWYU pragma: keep */
+#include <jasper/jas_types.h>
+
+const jas_uchar jas_iccprofdata_srgb[] =
+{
+	0x00, 0x00, 0x0c, 0x48, 0x4c, 0x69, 0x6e, 0x6f,
+	0x02, 0x10, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72,
+	0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
+	0x07, 0xce, 0x00, 0x02, 0x00, 0x09, 0x00, 0x06,
+	0x00, 0x31, 0x00, 0x00, 0x61, 0x63, 0x73, 0x70,
+	0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00,
+	0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
+	0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d,
+	0x48, 0x50, 0x20, 0x20, 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, 0x11, 0x63, 0x70, 0x72, 0x74,
+	0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x33,
+	0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x84,
+	0x00, 0x00, 0x00, 0x6c, 0x77, 0x74, 0x70, 0x74,
+	0x00, 0x00, 0x01, 0xf0, 0x00, 0x00, 0x00, 0x14,
+	0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x02, 0x04,
+	0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a,
+	0x00, 0x00, 0x02, 0x18, 0x00, 0x00, 0x00, 0x14,
+	0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x02, 0x2c,
+	0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a,
+	0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x14,
+	0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54,
+	0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64,
+	0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88,
+	0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x4c,
+	0x00, 0x00, 0x00, 0x86, 0x76, 0x69, 0x65, 0x77,
+	0x00, 0x00, 0x03, 0xd4, 0x00, 0x00, 0x00, 0x24,
+	0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xf8,
+	0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73,
+	0x00, 0x00, 0x04, 0x0c, 0x00, 0x00, 0x00, 0x24,
+	0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x04, 0x30,
+	0x00, 0x00, 0x00, 0x0c, 0x72, 0x54, 0x52, 0x43,
+	0x00, 0x00, 0x04, 0x3c, 0x00, 0x00, 0x08, 0x0c,
+	0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x3c,
+	0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43,
+	0x00, 0x00, 0x04, 0x3c, 0x00, 0x00, 0x08, 0x0c,
+	0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00,
+	0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68,
+	0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x31, 0x39,
+	0x39, 0x38, 0x20, 0x48, 0x65, 0x77, 0x6c, 0x65,
+	0x74, 0x74, 0x2d, 0x50, 0x61, 0x63, 0x6b, 0x61,
+	0x72, 0x64, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x61,
+	0x6e, 0x79, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
+	0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43,
+	0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e,
+	0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x12, 0x73, 0x52, 0x47,
+	0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39,
+	0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 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,
+	0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00,
+	0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x6f, 0xa2, 0x00, 0x00, 0x38, 0xf5,
+	0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x99,
+	0x00, 0x00, 0xb7, 0x85, 0x00, 0x00, 0x18, 0xda,
+	0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x24, 0xa0, 0x00, 0x00, 0x0f, 0x84,
+	0x00, 0x00, 0xb6, 0xcf, 0x64, 0x65, 0x73, 0x63,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16,
+	0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70,
+	0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69,
+	0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74,
+	0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e,
+	0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 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, 0x64, 0x65, 0x73, 0x63,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e,
+	0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36,
+	0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65,
+	0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47,
+	0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72,
+	0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d,
+	0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39,
+	0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44,
+	0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52,
+	0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75,
+	0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20,
+	0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c,
+	0x52, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63,
+	0x65, 0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e,
+	0x67, 0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74,
+	0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x49,
+	0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d,
+	0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x52,
+	0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65,
+	0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e, 0x67,
+	0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69,
+	0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x49, 0x45,
+	0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32,
+	0x2e, 0x31, 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, 0x76, 0x69, 0x65, 0x77,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0xfe,
+	0x00, 0x14, 0x5f, 0x2e, 0x00, 0x10, 0xcf, 0x14,
+	0x00, 0x03, 0xed, 0xcc, 0x00, 0x04, 0x13, 0x0b,
+	0x00, 0x03, 0x5c, 0x9e, 0x00, 0x00, 0x00, 0x01,
+	0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x4c, 0x09, 0x56, 0x00, 0x50, 0x00, 0x00,
+	0x00, 0x57, 0x1f, 0xe7, 0x6d, 0x65, 0x61, 0x73,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02,
+	0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00,
+	0x43, 0x52, 0x54, 0x20, 0x63, 0x75, 0x72, 0x76,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
+	0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f,
+	0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23,
+	0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37,
+	0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a,
+	0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e,
+	0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72,
+	0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86,
+	0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a,
+	0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae,
+	0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1,
+	0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5,
+	0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb,
+	0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01,
+	0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19,
+	0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32,
+	0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c,
+	0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67,
+	0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83,
+	0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1,
+	0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1,
+	0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1,
+	0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03,
+	0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26,
+	0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b,
+	0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71,
+	0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98,
+	0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1,
+	0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb,
+	0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16,
+	0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43,
+	0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72,
+	0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2,
+	0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3,
+	0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06,
+	0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b,
+	0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71,
+	0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8,
+	0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1,
+	0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c,
+	0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58,
+	0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96,
+	0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5,
+	0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16,
+	0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59,
+	0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d,
+	0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3,
+	0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b,
+	0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74,
+	0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf,
+	0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b,
+	0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a,
+	0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa,
+	0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb,
+	0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f,
+	0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4,
+	0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb,
+	0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54,
+	0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae,
+	0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b,
+	0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69,
+	0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8,
+	0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a,
+	0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e,
+	0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3,
+	0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a,
+	0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3,
+	0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e,
+	0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b,
+	0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09,
+	0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a,
+	0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec,
+	0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61,
+	0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7,
+	0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f,
+	0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9,
+	0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45,
+	0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3,
+	0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43,
+	0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5,
+	0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49,
+	0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce,
+	0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56,
+	0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0,
+	0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c,
+	0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa,
+	0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89,
+	0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b,
+	0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf,
+	0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45,
+	0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd,
+	0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77,
+	0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14,
+	0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2,
+	0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52,
+	0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5,
+	0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99,
+	0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40,
+	0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9,
+	0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94,
+	0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41,
+	0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0,
+	0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1,
+	0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55,
+	0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a,
+	0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2,
+	0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c,
+	0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38,
+	0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7,
+	0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7,
+	0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a,
+	0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f,
+	0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06,
+	0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0,
+	0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b,
+	0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69,
+	0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39,
+	0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c,
+	0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1,
+	0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7,
+	0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91,
+	0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c,
+	0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a,
+	0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a,
+	0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d,
+	0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1,
+	0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8,
+	0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2,
+	0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae,
+	0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c,
+	0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c,
+	0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f,
+	0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74,
+	0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b,
+	0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65,
+	0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61,
+	0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60,
+	0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61,
+	0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64,
+	0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a,
+	0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72,
+	0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d,
+	0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a,
+	0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a,
+	0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab,
+	0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0,
+	0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7,
+	0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0,
+	0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c,
+	0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a,
+	0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a,
+	0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e,
+	0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93,
+	0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb,
+	0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6,
+	0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13,
+	0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42,
+	0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75,
+	0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9,
+	0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0,
+	0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a,
+	0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56,
+	0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95,
+	0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6,
+	0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a,
+	0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61,
+	0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa,
+	0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5,
+	0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43,
+	0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94,
+	0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7,
+	0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d,
+	0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96,
+	0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1,
+	0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f,
+	0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf,
+	0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12,
+	0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78,
+	0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0,
+	0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b,
+	0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8,
+	0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28,
+	0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b,
+	0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11,
+	0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89,
+	0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04,
+	0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81,
+	0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01,
+	0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84,
+	0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a,
+	0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92,
+	0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d,
+	0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab,
+	0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b,
+	0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce,
+	0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64,
+	0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc,
+	0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98,
+	0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36,
+	0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6,
+	0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a,
+	0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20,
+	0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9,
+	0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75,
+	0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24,
+	0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5,
+	0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89,
+	0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40,
+	0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa,
+	0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6,
+	0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76,
+	0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38,
+	0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd,
+	0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4,
+	0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f,
+	0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c,
+	0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d,
+	0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00,
+	0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6,
+	0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae,
+	0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a,
+	0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68,
+	0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a,
+	0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e,
+	0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15,
+	0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff,
+	0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec,
+	0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb,
+	0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce,
+	0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3,
+	0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc,
+	0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7,
+	0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5,
+	0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6,
+	0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba,
+	0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1,
+	0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb,
+	0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8,
+	0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8,
+	0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb,
+	0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10,
+	0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29,
+	0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44,
+	0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63,
+	0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84,
+	0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9,
+	0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0,
+	0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb,
+	0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28,
+	0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58,
+	0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c,
+	0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2,
+	0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb,
+	0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38,
+	0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77,
+	0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba,
+	0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff
+};
+
+const unsigned jas_iccprofdata_srgblen = sizeof(jas_iccprofdata_srgb);
+
+const jas_uchar jas_iccprofdata_sgray[] = {
+	0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x00, 0x00,
+	0x02, 0x20, 0x00, 0x00, 0x73, 0x63, 0x6e, 0x72,
+	0x47, 0x52, 0x41, 0x59, 0x58, 0x59, 0x5a, 0x20,
+	0x07, 0xd3, 0x00, 0x01, 0x00, 0x1f, 0x00, 0x0d,
+	0x00, 0x35, 0x00, 0x21, 0x61, 0x63, 0x73, 0x70,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+	0x4b, 0x4f, 0x44, 0x41, 0x73, 0x47, 0x72, 0x79,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
+	0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d,
+	0x4a, 0x50, 0x45, 0x47, 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, 0x04, 0x64, 0x65, 0x73, 0x63,
+	0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x86,
+	0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0x3c,
+	0x00, 0x00, 0x00, 0x2b, 0x77, 0x74, 0x70, 0x74,
+	0x00, 0x00, 0x01, 0x68, 0x00, 0x00, 0x00, 0x14,
+	0x6b, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x7c,
+	0x00, 0x00, 0x00, 0x0e, 0x64, 0x65, 0x73, 0x63,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c,
+	0x52, 0x65, 0x73, 0x74, 0x72, 0x69, 0x63, 0x74,
+	0x65, 0x64, 0x20, 0x49, 0x43, 0x43, 0x20, 0x70,
+	0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x64,
+	0x65, 0x73, 0x63, 0x72, 0x69, 0x62, 0x69, 0x6e,
+	0x67, 0x20, 0x73, 0x52, 0x47, 0x42, 0x2d, 0x67,
+	0x72, 0x65, 0x79, 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, 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, 0x74, 0x65, 0x78, 0x74,
+	0x00, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x70, 0x79,
+	0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x32, 0x30,
+	0x30, 0x33, 0x20, 0x73, 0x52, 0x47, 0x42, 0x2d,
+	0x67, 0x72, 0x65, 0x79, 0x20, 0x52, 0x65, 0x66,
+	0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x00, 0x00,
+	0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+	0x00, 0x00, 0xf3, 0x54, 0x00, 0x01, 0x00, 0x00,
+	0x00, 0x01, 0x16, 0xcf, 0x63, 0x75, 0x72, 0x76,
+	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+	0x01, 0xcd
+};
+
+const unsigned jas_iccprofdata_sgraylen = sizeof(jas_iccprofdata_sgray);
--- /dev/null
+++ b/jas_image.c
@@ -1,0 +1,1612 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Image Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_image.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+#define	FLOORDIV(x, y) ((x) / (y))
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static jas_image_cmpt_t *jas_image_cmpt_create0(void);
+static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt);
+static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
+  int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
+  int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
+  bool inmem);
+static void jas_image_setbbox(jas_image_t *image);
+static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt);
+static int jas_image_growcmpts(jas_image_t *image, unsigned maxcmpts);
+static uint_fast32_t inttobits(jas_seqent_t v, unsigned prec, bool sgnd);
+static jas_seqent_t bitstoint(uint_fast32_t v, unsigned prec, bool sgnd);
+static int putint(jas_stream_t *out, bool sgnd, unsigned prec, long val);
+static int getint(jas_stream_t *in, bool sgnd, unsigned prec, long *val);
+static long uptomult(long x, long y);
+static long downtomult(long x, long y);
+static long convert(long val, bool oldsgnd, unsigned oldprec, bool newsgnd,
+  unsigned newprec);
+static void jas_image_calcbbox2(const jas_image_t *image, jas_image_coord_t *tlx,
+  jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+static unsigned jas_image_numfmts = 0;
+static jas_image_fmtinfo_t jas_image_fmtinfos[JAS_IMAGE_MAXFMTS];
+
+/******************************************************************************\
+* Create and destroy operations.
+\******************************************************************************/
+
+jas_image_t *jas_image_create(unsigned numcmpts, const jas_image_cmptparm_t *cmptparms,
+  jas_clrspc_t clrspc)
+{
+	jas_image_t *image;
+	size_t rawsize;
+	unsigned cmptno;
+	const jas_image_cmptparm_t *cmptparm;
+
+	JAS_DBGLOG(100, ("jas_image_create(%d, %p, %d)\n", numcmpts, cmptparms,
+	  clrspc));
+
+	if (!(image = jas_image_create0())) {
+		goto error;
+	}
+
+	image->clrspc_ = clrspc;
+	image->maxcmpts_ = numcmpts;
+//	image->inmem_ = true;
+
+	/* Allocate memory for the per-component information. */
+	if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_,
+	  sizeof(jas_image_cmpt_t *)))) {
+		goto error;
+	}
+	/* Initialize in case of failure. */
+	for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {
+		image->cmpts_[cmptno] = 0;
+	}
+
+#if 0
+	/* Compute the approximate raw size of the image. */
+	rawsize = 0;
+	for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
+	  ++cmptparm) {
+		rawsize += cmptparm->width * cmptparm->height *
+		  (cmptparm->prec + 7) / 8;
+	}
+	/* Decide whether to buffer the image data in memory, based on the
+	  raw size of the image. */
+	inmem = (rawsize < JAS_IMAGE_INMEMTHRESH);
+#endif
+
+	/* Create the individual image components. */
+	for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
+	  ++cmptparm) {
+		if (!jas_safe_size_mul3(cmptparm->width, cmptparm->height,
+		  (cmptparm->prec + 7), &rawsize)) {
+			goto error;
+		}
+		rawsize /= 8;
+		const bool inmem = (rawsize < JAS_IMAGE_INMEMTHRESH);
+		if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,
+		  cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
+		  cmptparm->width, cmptparm->height, cmptparm->prec,
+		  cmptparm->sgnd, inmem))) {
+			goto error;
+		}
+		++image->numcmpts_;
+	}
+
+	/* Determine the bounding box for all of the components on the
+	  reference grid (i.e., the image area) */
+	jas_image_setbbox(image);
+
+	return image;
+
+error:
+	if (image) {
+		jas_image_destroy(image);
+	}
+	return 0;
+}
+
+jas_image_t *jas_image_create0()
+{
+	jas_image_t *image;
+
+	if (!(image = jas_malloc(sizeof(jas_image_t)))) {
+		return 0;
+	}
+
+	image->tlx_ = 0;
+	image->tly_ = 0;
+	image->brx_ = 0;
+	image->bry_ = 0;
+	image->clrspc_ = JAS_CLRSPC_UNKNOWN;
+	image->numcmpts_ = 0;
+	image->maxcmpts_ = 0;
+	image->cmpts_ = 0;
+//	image->inmem_ = true;
+	image->cmprof_ = 0;
+
+	return image;
+}
+
+jas_image_t *jas_image_copy(jas_image_t *image)
+{
+	jas_image_t *newimage;
+
+	if (!(newimage = jas_image_create0())) {
+		goto error;
+	}
+
+	if (jas_image_growcmpts(newimage, image->numcmpts_)) {
+		goto error;
+	}
+	for (unsigned cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+		if (!(newimage->cmpts_[cmptno] = jas_image_cmpt_copy(image->cmpts_[cmptno]))) {
+			goto error;
+		}
+		++newimage->numcmpts_;
+	}
+
+	jas_image_setbbox(newimage);
+
+	if (image->cmprof_) {
+		if (!(newimage->cmprof_ = jas_cmprof_copy(image->cmprof_)))
+			goto error;
+	}
+
+	return newimage;
+error:
+	if (newimage) {
+		jas_image_destroy(newimage);
+	}
+	return 0;
+}
+
+static jas_image_cmpt_t *jas_image_cmpt_create0()
+{
+	jas_image_cmpt_t *cmpt;
+	if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
+		return 0;
+	}
+	memset(cmpt, 0, sizeof(jas_image_cmpt_t));
+	cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
+	return cmpt;
+}
+
+static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt)
+{
+	jas_image_cmpt_t *newcmpt;
+
+	if (!(newcmpt = jas_image_cmpt_create0())) {
+		return 0;
+	}
+	newcmpt->tlx_ = cmpt->tlx_;
+	newcmpt->tly_ = cmpt->tly_;
+	newcmpt->hstep_ = cmpt->hstep_;
+	newcmpt->vstep_ = cmpt->vstep_;
+	newcmpt->width_ = cmpt->width_;
+	newcmpt->height_ = cmpt->height_;
+	newcmpt->prec_ = cmpt->prec_;
+	newcmpt->sgnd_ = cmpt->sgnd_;
+	newcmpt->cps_ = cmpt->cps_;
+	newcmpt->type_ = cmpt->type_;
+	if (!(newcmpt->stream_ = jas_stream_memopen(0, 0))) {
+		goto error;
+	}
+	if (jas_stream_seek(cmpt->stream_, 0, SEEK_SET)) {
+		goto error;
+	}
+	if (jas_stream_copy(newcmpt->stream_, cmpt->stream_, -1)) {
+		goto error;
+	}
+	if (jas_stream_seek(newcmpt->stream_, 0, SEEK_SET)) {
+		goto error;
+	}
+	return newcmpt;
+error:
+	jas_image_cmpt_destroy(newcmpt);
+	return 0;
+}
+
+void jas_image_destroy(jas_image_t *image)
+{
+	if (image->cmpts_) {
+		for (unsigned i = 0; i < image->numcmpts_; ++i) {
+			jas_image_cmpt_destroy(image->cmpts_[i]);
+			image->cmpts_[i] = 0;
+		}
+		jas_free(image->cmpts_);
+	}
+	if (image->cmprof_)
+		jas_cmprof_destroy(image->cmprof_);
+	jas_free(image);
+}
+
+static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
+  int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
+  int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
+  bool inmem)
+{
+	jas_image_cmpt_t *cmpt;
+	size_t size;
+
+	JAS_DBGLOG(100, (
+	  "jas_image_cmpt_create(%ld, %ld, %ld, %ld, %ld, %ld, %d, %d, %d)\n",
+	  JAS_CAST(long, tlx),
+	  JAS_CAST(long, tly),
+	  JAS_CAST(long, hstep),
+	  JAS_CAST(long, vstep),
+	  JAS_CAST(long, width),
+	  JAS_CAST(long, height),
+	  JAS_CAST(int, depth),
+	  sgnd,
+	  inmem
+	  ));
+
+	if (depth < 1U + sgnd) {
+		/* we need at least 1 bit for unsigned samples and 2
+		   bits for signed samples */
+		return NULL;
+	}
+
+	if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
+		return NULL;
+	}
+	if (!jas_safe_intfast32_add(tlx, width, 0) ||
+	  !jas_safe_intfast32_add(tly, height, 0)) {
+		return NULL;
+	}
+	if (!jas_safe_intfast32_mul3(width, height, depth, 0)) {
+		return NULL;
+	}
+
+	if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
+		return NULL;
+	}
+
+	cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
+	cmpt->tlx_ = tlx;
+	cmpt->tly_ = tly;
+	cmpt->hstep_ = hstep;
+	cmpt->vstep_ = vstep;
+	cmpt->width_ = width;
+	cmpt->height_ = height;
+	cmpt->prec_ = depth;
+	cmpt->sgnd_ = sgnd;
+	cmpt->stream_ = 0;
+	cmpt->cps_ = (depth + 7) / 8;
+
+	// Compute the number of samples in the image component, while protecting
+	// against overflow.
+	// size = cmpt->width_ * cmpt->height_ * cmpt->cps_;
+	if (!jas_safe_size_mul3(cmpt->width_, cmpt->height_, cmpt->cps_, &size)) {
+		goto error;
+	}
+	cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) :
+	  jas_stream_tmpfile();
+	if (!cmpt->stream_) {
+		goto error;
+	}
+
+	/* Zero the component data.  This isn't necessary, but it is
+	convenient for debugging purposes. */
+	/* Note: conversion of size - 1 to long can overflow */
+	if (size > 0) {
+		if (size - 1 > LONG_MAX) {
+			goto error;
+		}
+		if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
+		  jas_stream_putc(cmpt->stream_, 0) == EOF ||
+		  jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
+			goto error;
+		}
+	}
+
+	return cmpt;
+
+error:
+	jas_image_cmpt_destroy(cmpt);
+	return 0;
+}
+
+static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt)
+{
+	if (cmpt->stream_) {
+		jas_stream_close(cmpt->stream_);
+	}
+	jas_free(cmpt);
+}
+
+/******************************************************************************\
+* Load and save operations.
+\******************************************************************************/
+
+jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, const char *optstr)
+{
+	const jas_image_fmtinfo_t *fmtinfo;
+	jas_image_t *image;
+
+	image = 0;
+
+	/* If possible, try to determine the format of the input data. */
+	if (fmt < 0) {
+		if ((fmt = jas_image_getfmt(in)) < 0){
+			werrstr("unknown format");
+			goto error;
+		}
+	}
+
+	/* Is it possible to decode an image represented in this format? */
+	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))){
+		werrstr("unsupported format");
+		goto error;
+	}
+	if (!fmtinfo->ops.decode){
+		werrstr("no decoder for the format");
+		goto error;
+	}
+
+	/* Decode the image. */
+	if (!(image = (*fmtinfo->ops.decode)(in, optstr))){
+		werrstr("failed to decode");
+		goto error;
+	}
+
+	/* Create a color profile if needed. */
+	if (!jas_clrspc_isunknown(image->clrspc_) &&
+	  !jas_clrspc_isgeneric(image->clrspc_) && !image->cmprof_) {
+		if (!(image->cmprof_ =
+		  jas_cmprof_createfromclrspc(jas_image_clrspc(image)))){
+			werrstr("failed to create colorspace");
+			goto error;
+		}
+	}
+
+	return image;
+error:
+	if (image)
+		jas_image_destroy(image);
+	return 0;
+}
+
+int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt,
+  const char *optstr)
+{
+	const jas_image_fmtinfo_t *fmtinfo;
+	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
+		jas_eprintf("format lookup failed\n");
+		return -1;
+	}
+	return (fmtinfo->ops.encode) ? (*fmtinfo->ops.encode)(image, out,
+	  optstr) : (-1);
+}
+
+/******************************************************************************\
+* Component read and write operations.
+\******************************************************************************/
+
+int jas_image_readcmpt(jas_image_t *image, unsigned cmptno, jas_image_coord_t x,
+  jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+  jas_matrix_t *data)
+{
+	jas_image_cmpt_t *cmpt;
+	jas_image_coord_t i;
+	jas_image_coord_t j;
+	jas_seqent_t v;
+	int c;
+	jas_seqent_t *dr;
+	jas_seqent_t *d;
+
+	JAS_DBGLOG(100, ("jas_image_readcmpt(%p, %d, %ld, %ld, %ld, %ld, %p)\n",
+	  image, cmptno, JAS_CAST(long, x), JAS_CAST(long, y),
+	  JAS_CAST(long, width), JAS_CAST(long, height), data));
+
+	if(data == NULL) {
+		return -1;
+	}
+
+	if (cmptno >= image->numcmpts_) {
+		return -1;
+	}
+
+	cmpt = image->cmpts_[cmptno];
+	if (x >= cmpt->width_ || y >= cmpt->height_ ||
+	  x + width > cmpt->width_ ||
+	  y + height > cmpt->height_) {
+		return -1;
+	}
+
+	if (!jas_matrix_numrows(data) || !jas_matrix_numcols(data)) {
+		return -1;
+	}
+
+	if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) {
+		if (jas_matrix_resize(data, height, width)) {
+			return -1;
+		}
+	}
+
+	jas_stream_t *const stream = cmpt->stream_;
+	const uint_least32_t cmpt_width = cmpt->width_;
+	const unsigned cps = cmpt->cps_;
+	const unsigned prec = cmpt->prec_;
+	const bool sgnd = cmpt->sgnd_;
+
+	dr = jas_matrix_getref(data, 0, 0);
+	const uint_least32_t drs = jas_matrix_rowstep(data);
+	for (i = 0; i < height; ++i, dr += drs) {
+		d = dr;
+		if (jas_stream_seek(stream, (cmpt_width * (y + i) + x)
+		  * cps, SEEK_SET) < 0) {
+			return -1;
+		}
+
+		if (cps == 1 && !sgnd && width <= 16384) {
+			/* fast path for 1 byte per sample and
+			   unsigned with bulk reads */
+
+			jas_uchar buffer[16384];
+
+			if (jas_stream_read(stream, buffer, width) != width)
+				return -1;
+
+			for (j = 0; j < width; ++j)
+				d[j] = buffer[j];
+
+			continue;
+		}
+
+		for (j = width; j > 0; --j, ++d) {
+			v = 0;
+			for (unsigned k = cps; k > 0; --k) {
+				if ((c = jas_stream_getc(stream)) == EOF) {
+					return -1;
+				}
+				v = (v << 8) | (c & 0xff);
+			}
+			*d = bitstoint(v, prec, sgnd);
+		}
+	}
+
+	return 0;
+}
+
+int jas_image_writecmpt(jas_image_t *image, unsigned cmptno, jas_image_coord_t x,
+  jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+  const jas_matrix_t *data)
+{
+	jas_image_cmpt_t *cmpt;
+	jas_image_coord_t i;
+	jas_image_coord_t j;
+	jas_seqent_t v;
+	int c;
+
+	JAS_DBGLOG(100, ("jas_image_writecmpt(%p, %d, %ld, %ld, %ld, %ld, %p)\n",
+	  image, cmptno, JAS_CAST(long, x), JAS_CAST(long, y),
+	  JAS_CAST(long, width), JAS_CAST(long, height), data));
+
+	if (cmptno >= image->numcmpts_) {
+		return -1;
+	}
+
+	cmpt = image->cmpts_[cmptno];
+	if (x >= cmpt->width_ || y >= cmpt->height_ ||
+	  x + width > cmpt->width_ ||
+	  y + height > cmpt->height_) {
+		return -1;
+	}
+
+	if (!jas_matrix_numrows(data) || !jas_matrix_numcols(data)) {
+		return -1;
+	}
+
+	if (jas_matrix_numrows(data) != height ||
+	  jas_matrix_numcols(data) != width) {
+		return -1;
+	}
+
+	jas_stream_t *const stream = cmpt->stream_;
+	const uint_least32_t cmpt_width = cmpt->width_;
+	const unsigned cps = cmpt->cps_;
+	const unsigned prec = cmpt->prec_;
+	const bool sgnd = cmpt->sgnd_;
+
+	const jas_seqent_t *dr = jas_matrix_getref(data, 0, 0);
+	const uint_least32_t drs = jas_matrix_rowstep(data);
+	for (i = 0; i < height; ++i, dr += drs) {
+		const jas_seqent_t *d = dr;
+		if (jas_stream_seek(stream, (cmpt_width * (y + i) + x)
+		  * cps, SEEK_SET) < 0) {
+			return -1;
+		}
+
+		if (cps == 1 && !sgnd && width <= 16384) {
+			/* fast path for 1 byte per sample and
+			   unsigned with bulk writes */
+
+			jas_uchar buffer[16384];
+
+			for (j = 0; j < width; ++j)
+				buffer[j] = d[j];
+
+			jas_stream_write(stream, buffer, width);
+			continue;
+		}
+
+		for (j = width; j > 0; --j, ++d) {
+			v = inttobits(*d, prec, sgnd);
+			for (unsigned k = cps; k > 0; --k) {
+				c = (v >> (8 * (cps - 1))) & 0xff;
+				if (jas_stream_putc(stream,
+				  (unsigned char) c) == EOF) {
+					return -1;
+				}
+				v <<= 8;
+			}
+		}
+	}
+
+	return 0;
+}
+
+/******************************************************************************\
+* File format operations.
+\******************************************************************************/
+
+void jas_image_clearfmts()
+{
+	jas_image_fmtinfo_t *fmtinfo;
+	for (unsigned i = 0; i < jas_image_numfmts; ++i) {
+		fmtinfo = &jas_image_fmtinfos[i];
+		if (fmtinfo->name) {
+			jas_free(fmtinfo->name);
+			fmtinfo->name = 0;
+		}
+		if (fmtinfo->ext) {
+			jas_free(fmtinfo->ext);
+			fmtinfo->ext = 0;
+		}
+		if (fmtinfo->desc) {
+			jas_free(fmtinfo->desc);
+			fmtinfo->desc = 0;
+		}
+	}
+	jas_image_numfmts = 0;
+}
+
+int jas_image_addfmt(int id, const char *name, const char *ext,
+  const char *desc, const jas_image_fmtops_t *ops)
+{
+	jas_image_fmtinfo_t *fmtinfo;
+	assert(id >= 0 && name && ext && ops);
+	if (jas_image_numfmts >= JAS_IMAGE_MAXFMTS) {
+		return -1;
+	}
+	fmtinfo = &jas_image_fmtinfos[jas_image_numfmts];
+	fmtinfo->id = id;
+	if (!(fmtinfo->name = jas_strdup(name))) {
+		return -1;
+	}
+	if (!(fmtinfo->ext = jas_strdup(ext))) {
+		jas_free(fmtinfo->name);
+		return -1;
+	}
+	if (!(fmtinfo->desc = jas_strdup(desc))) {
+		jas_free(fmtinfo->name);
+		jas_free(fmtinfo->ext);
+		return -1;
+	}
+	fmtinfo->ops = *ops;
+	++jas_image_numfmts;
+	return 0;
+}
+
+/* This is for future consideration for addition to the library API. */
+#if 0
+JAS_DLLEXPORT
+int jas_image_delfmt(int fmtid)
+{
+	if (fmtid < 0 || fmtid >= JAS_CAST(int, jas_image_numfmts)) {
+		return -1;
+	}
+	const jas_image_fmtinfo_t *fmtinfo;
+	if (!(fmtinfo = jas_image_lookupfmtbyid(fmtid))) {
+		return -1;
+	}
+	for (int i = fmtinfo - jas_image_fmtinfos; i < JAS_CAST(int,
+	  jas_image_numfmts) - 1; ++i) {
+		jas_image_fmtinfos[i] = jas_image_fmtinfos[i + 1];
+	}
+	--jas_image_numfmts;
+	return 0;
+}
+#endif
+
+int jas_image_strtofmt(const char *name)
+{
+	const jas_image_fmtinfo_t *fmtinfo;
+	if (!(fmtinfo = jas_image_lookupfmtbyname(name))) {
+		return -1;
+	}
+	return fmtinfo->id;
+}
+
+const char *jas_image_fmttostr(int fmt)
+{
+	const jas_image_fmtinfo_t *fmtinfo;
+	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
+		return 0;
+	}
+	return fmtinfo->name;
+}
+
+int jas_image_getfmt(jas_stream_t *in)
+{
+	const jas_image_fmtinfo_t *fmtinfo;
+
+	/* Check for data in each of the supported formats. */
+	unsigned i;
+	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i,
+	  ++fmtinfo) {
+		if (fmtinfo->ops.validate) {
+			/* Is the input data valid for this format? */
+			JAS_DBGLOG(20, ("testing for format %s ... ", fmtinfo->name));
+			if (!(*fmtinfo->ops.validate)(in)) {
+				JAS_DBGLOG(20, ("test succeeded\n"));
+				return fmtinfo->id;
+			}
+			JAS_DBGLOG(20, ("test failed\n"));
+		}
+	}
+	return -1;
+}
+
+int jas_image_fmtfromname(const char *name)
+{
+	const char *ext;
+	const jas_image_fmtinfo_t *fmtinfo;
+	/* Get the file name extension. */
+	if (!(ext = strrchr(name, '.'))) {
+		return -1;
+	}
+	++ext;
+	/* Try to find a format that uses this extension. */	
+	unsigned i;
+	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i,
+	  ++fmtinfo) {
+		/* Do we have a match? */
+		if (!strcmp(ext, fmtinfo->ext)) {
+			return fmtinfo->id;
+		}
+	}
+	return -1;
+}
+
+/******************************************************************************\
+* Miscellaneous operations.
+\******************************************************************************/
+
+bool jas_image_cmpt_domains_same(const jas_image_t *image)
+{
+	jas_image_cmpt_t *cmpt;
+	jas_image_cmpt_t *cmpt0;
+
+	cmpt0 = image->cmpts_[0];
+	for (unsigned cmptno = 1; cmptno < image->numcmpts_; ++cmptno) {
+		cmpt = image->cmpts_[cmptno];
+		if (cmpt->tlx_ != cmpt0->tlx_ || cmpt->tly_ != cmpt0->tly_ ||
+		  cmpt->hstep_ != cmpt0->hstep_ || cmpt->vstep_ != cmpt0->vstep_ ||
+		  cmpt->width_ != cmpt0->width_ || cmpt->height_ != cmpt0->height_) {
+			return 0;
+		}
+	}
+	return 1;
+}
+
+uint_fast32_t jas_image_rawsize(const jas_image_t *image)
+{
+	uint_fast32_t rawsize;
+	jas_image_cmpt_t *cmpt;
+
+	rawsize = 0;
+	for (unsigned cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+		cmpt = image->cmpts_[cmptno];
+		rawsize += (cmpt->width_ * cmpt->height_ * cmpt->prec_ +
+		  7) / 8;
+	}
+	return rawsize;
+}
+
+void jas_image_delcmpt(jas_image_t *image, unsigned cmptno)
+{
+	if (cmptno >= image->numcmpts_) {
+		return;
+	}
+	jas_image_cmpt_destroy(image->cmpts_[cmptno]);
+	if (cmptno < image->numcmpts_) {
+		memmove(&image->cmpts_[cmptno], &image->cmpts_[cmptno + 1],
+		  (image->numcmpts_ - 1 - cmptno) * sizeof(jas_image_cmpt_t *));
+	}
+	--image->numcmpts_;
+
+	jas_image_setbbox(image);
+}
+
+int jas_image_addcmpt(jas_image_t *image, int cmptno,
+  const jas_image_cmptparm_t *cmptparm)
+{
+	jas_image_cmpt_t *newcmpt;
+	if (cmptno < 0) {
+		cmptno = image->numcmpts_;
+	}
+	assert(cmptno >= 0 && (unsigned)cmptno <= image->numcmpts_);
+	if (image->numcmpts_ >= image->maxcmpts_) {
+		if (jas_image_growcmpts(image, image->maxcmpts_ + 128)) {
+			return -1;
+		}
+	}
+	if (!(newcmpt = jas_image_cmpt_create(cmptparm->tlx,
+	  cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
+	  cmptparm->width, cmptparm->height, cmptparm->prec,
+	  cmptparm->sgnd, true))) {
+		return -1;
+	}
+	if ((unsigned)cmptno < image->numcmpts_) {
+		memmove(&image->cmpts_[cmptno + 1], &image->cmpts_[cmptno],
+		  (image->numcmpts_ - (unsigned)cmptno) * sizeof(jas_image_cmpt_t *));
+	}
+	image->cmpts_[cmptno] = newcmpt;
+	++image->numcmpts_;
+
+	jas_image_setbbox(image);
+
+	return 0;
+}
+
+const jas_image_fmtinfo_t *jas_image_lookupfmtbyid(int id)
+{
+	unsigned i;
+	const jas_image_fmtinfo_t *fmtinfo;
+
+	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
+		if (fmtinfo->id == id) {
+			return fmtinfo;
+		}
+	}
+	return 0;
+}
+
+const jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name)
+{
+	unsigned i;
+	const jas_image_fmtinfo_t *fmtinfo;
+
+	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
+		if (!strcmp(fmtinfo->name, name)) {
+			return fmtinfo;
+		}
+	}
+	return 0;
+}
+
+static uint_fast32_t inttobits(jas_seqent_t v, unsigned prec, bool sgnd)
+{
+	uint_fast32_t ret;
+	ret = ((sgnd && v < 0) ? ((1 << prec) + v) : v) & JAS_ONES(prec);
+	return ret;
+}
+
+static jas_seqent_t bitstoint(uint_fast32_t v, unsigned prec, bool sgnd)
+{
+	jas_seqent_t ret;
+	v &= JAS_ONES(prec);
+	ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v;
+	return ret;
+}
+
+static void jas_image_setbbox(jas_image_t *image)
+{
+	jas_image_cmpt_t *cmpt;
+	int_fast32_t x;
+	int_fast32_t y;
+
+	if (image->numcmpts_ > 0) {
+		/* Determine the bounding box for all of the components on the
+		  reference grid (i.e., the image area) */
+		cmpt = image->cmpts_[0];
+		image->tlx_ = cmpt->tlx_;
+		image->tly_ = cmpt->tly_;
+		image->brx_ = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1;
+		image->bry_ = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1;
+		for (unsigned cmptno = 1; cmptno < image->numcmpts_; ++cmptno) {
+			cmpt = image->cmpts_[cmptno];
+			if (image->tlx_ > cmpt->tlx_) {
+				image->tlx_ = cmpt->tlx_;
+			}
+			if (image->tly_ > cmpt->tly_) {
+				image->tly_ = cmpt->tly_;
+			}
+			x = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1;
+			if (image->brx_ < x) {
+				image->brx_ = x;
+			}
+			y = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1;
+			if (image->bry_ < y) {
+				image->bry_ = y;
+			}
+		}
+	} else {
+		image->tlx_ = 0;
+		image->tly_ = 0;
+		image->brx_ = 0;
+		image->bry_ = 0;
+	}
+}
+
+static int jas_image_growcmpts(jas_image_t *image, unsigned maxcmpts)
+{
+	jas_image_cmpt_t **newcmpts;
+
+	newcmpts = (!image->cmpts_) ? jas_alloc2(maxcmpts,
+	  sizeof(jas_image_cmpt_t *)) :
+	  jas_realloc2(image->cmpts_, maxcmpts, sizeof(jas_image_cmpt_t *));
+	if (!newcmpts) {
+		return -1;
+	}
+	image->cmpts_ = newcmpts;
+	image->maxcmpts_ = maxcmpts;
+	for (unsigned cmptno = image->numcmpts_; cmptno < image->maxcmpts_; ++cmptno) {
+		image->cmpts_[cmptno] = 0;
+	}
+	return 0;
+}
+
+int jas_image_copycmpt(jas_image_t *dstimage, unsigned dstcmptno,
+  jas_image_t *srcimage, unsigned srccmptno)
+{
+	jas_image_cmpt_t *newcmpt;
+	if (dstimage->numcmpts_ >= dstimage->maxcmpts_) {
+		if (jas_image_growcmpts(dstimage, dstimage->maxcmpts_ + 128)) {
+			return -1;
+		}
+	}
+	if (!(newcmpt = jas_image_cmpt_copy(srcimage->cmpts_[srccmptno]))) {
+		return -1;
+	}
+	if (dstcmptno < dstimage->numcmpts_) {
+		memmove(&dstimage->cmpts_[dstcmptno + 1], &dstimage->cmpts_[dstcmptno],
+		  (dstimage->numcmpts_ - dstcmptno) * sizeof(jas_image_cmpt_t *));
+	}
+	dstimage->cmpts_[dstcmptno] = newcmpt;
+	++dstimage->numcmpts_;
+
+	jas_image_setbbox(dstimage);
+	return 0;
+}
+
+void jas_image_dump(jas_image_t *image, FILE *out)
+{
+	long buf[1024];
+	jas_image_cmpt_t *cmpt;
+	for (unsigned cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+		cmpt = image->cmpts_[cmptno];
+		fprintf(out, "prec=%d, sgnd=%d, cmpttype=%"PRIiFAST32"\n", cmpt->prec_,
+		  cmpt->sgnd_, cmpt->type_);
+		const unsigned width = jas_image_cmptwidth(image, cmptno);
+		const unsigned height = jas_image_cmptheight(image, cmptno);
+		const unsigned n = JAS_MIN(16, width);
+		if (jas_image_readcmpt2(image, cmptno, 0, 0, n, 1, buf)) {
+			abort();
+		}
+		for (unsigned i = 0; i < n; ++i) {
+			fprintf(out, " f(%d,%d)=%ld", i, 0, buf[i]);
+		}
+		fprintf(out, "\n");
+		if (jas_image_readcmpt2(image, cmptno, width - n, height - 1, n, 1, buf)) {
+			abort();
+		}
+		for (unsigned i = 0; i < n; ++i) {
+			fprintf(out, " f(%d,%d)=%ld", width - n + i, height - 1, buf[i]);
+		}
+		fprintf(out, "\n");
+	}
+}
+
+int jas_image_depalettize(jas_image_t *image, unsigned cmptno, unsigned numlutents,
+  const int_fast32_t *lutents, unsigned dtype, unsigned newcmptno)
+{
+	jas_image_cmptparm_t cmptparms;
+	const jas_image_cmpt_t *cmpt = image->cmpts_[cmptno];
+
+	const uint_least32_t width = cmpt->width_;
+	const uint_least32_t height = cmpt->height_;
+
+	cmptparms.tlx = cmpt->tlx_;
+	cmptparms.tly = cmpt->tly_;
+	cmptparms.hstep = cmpt->hstep_;
+	cmptparms.vstep = cmpt->vstep_;
+	cmptparms.width = width;
+	cmptparms.height = height;
+	cmptparms.prec = JAS_IMAGE_CDT_GETPREC(dtype);
+	cmptparms.sgnd = JAS_IMAGE_CDT_GETSGND(dtype);
+
+	if (jas_image_addcmpt(image, newcmptno, &cmptparms)) {
+		return -1;
+	}
+	if (newcmptno <= cmptno) {
+		++cmptno;
+	}
+
+	for (uint_least32_t j = 0; j < height; ++j) {
+		for (uint_least32_t i = 0; i < width; ++i) {
+			int v = jas_image_readcmptsample(image, cmptno, i, j);
+			if (v < 0) {
+				v = 0;
+			} else if ((unsigned)v >= numlutents) {
+				assert(numlutents > 0);
+				v = numlutents - 1;
+			}
+			jas_image_writecmptsample(image, newcmptno, i, j,
+			  lutents[v]);
+		}
+	}
+	return 0;
+}
+
+int jas_image_readcmptsample(jas_image_t *image, unsigned cmptno, unsigned x, unsigned y)
+{
+	jas_image_cmpt_t *cmpt;
+	uint_fast32_t v;
+	int c;
+
+	cmpt = image->cmpts_[cmptno];
+
+	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
+	  SEEK_SET) < 0) {
+		return -1;
+	}
+	v = 0;
+	for (unsigned k = cmpt->cps_; k > 0; --k) {
+		if ((c = jas_stream_getc(cmpt->stream_)) == EOF) {
+			return -1;
+		}
+		v = (v << 8) | (c & 0xff);
+	}
+	return bitstoint(v, cmpt->prec_, cmpt->sgnd_);
+}
+
+void jas_image_writecmptsample(jas_image_t *image, unsigned cmptno, unsigned x, unsigned y,
+  int_fast32_t v)
+{
+	jas_image_cmpt_t *cmpt;
+	uint_fast32_t t;
+	int c;
+
+	cmpt = image->cmpts_[cmptno];
+
+	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
+	  SEEK_SET) < 0) {
+		return;
+	}
+	t = inttobits(v, cmpt->prec_, cmpt->sgnd_);
+	for (unsigned k = cmpt->cps_; k > 0; --k) {
+		c = (t >> (8 * (cmpt->cps_ - 1))) & 0xff;
+		if (jas_stream_putc(cmpt->stream_, (unsigned char) c) == EOF) {
+			return;
+		}
+		t <<= 8;
+	}
+}
+
+int jas_image_getcmptbytype(const jas_image_t *image, jas_image_cmpttype_t ctype)
+{
+	for (unsigned cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+		if (image->cmpts_[cmptno]->type_ == ctype) {
+			return cmptno;
+		}
+	}
+	return -1;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+/***********************************************/
+/***********************************************/
+/***********************************************/
+/***********************************************/
+
+int jas_image_readcmpt2(jas_image_t *image, unsigned cmptno, jas_image_coord_t x,
+  jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+  long *buf)
+{
+	jas_image_cmpt_t *cmpt;
+	jas_image_coord_t i;
+	jas_image_coord_t j;
+	long v;
+	long *bufptr;
+
+	if (cmptno >= image->numcmpts_)
+		goto error;
+	cmpt = image->cmpts_[cmptno];
+	if (x < 0 || x >= cmpt->width_ || y < 0 || y >= cmpt->height_ ||
+	  width < 0 || height < 0 || x + width > cmpt->width_ ||
+	  y + height > cmpt->height_)
+		goto error;
+
+	bufptr = buf;
+	for (i = 0; i < height; ++i) {
+		if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
+		  * cmpt->cps_, SEEK_SET) < 0)
+			goto error;
+		for (j = 0; j < width; ++j) {
+			if (getint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, &v))
+				goto error;
+			*bufptr++ = v;
+		}
+	}
+
+	return 0;
+error:
+	return -1;
+}
+
+int jas_image_writecmpt2(jas_image_t *image, unsigned cmptno, jas_image_coord_t x,
+  jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+  const long *buf)
+{
+	jas_image_cmpt_t *cmpt;
+	jas_image_coord_t i;
+	jas_image_coord_t j;
+	long v;
+
+	if (cmptno >= image->numcmpts_)
+		goto error;
+	cmpt = image->cmpts_[cmptno];
+	if (x < 0 || x >= cmpt->width_ || y < 0 || y >= cmpt->height_ ||
+	  width < 0 || height < 0 || x + width > cmpt->width_ ||
+	  y + height > cmpt->height_)
+		goto error;
+
+	const long *bufptr = buf;
+	for (i = 0; i < height; ++i) {
+		if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
+		  * cmpt->cps_, SEEK_SET) < 0)
+			goto error;
+		for (j = 0; j < width; ++j) {
+			v = *bufptr++;
+			if (putint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, v))
+				goto error;
+		}
+	}
+
+	return 0;
+error:
+	return -1;
+}
+
+int jas_image_sampcmpt(jas_image_t *image, unsigned cmptno, unsigned newcmptno,
+  jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs,
+  jas_image_coord_t vs, int sgnd, unsigned prec)
+{
+	jas_image_coord_t tlx;
+	jas_image_coord_t tly;
+	jas_image_coord_t brx;
+	jas_image_coord_t bry;
+	jas_image_cmptparm_t cmptparm;
+	jas_image_coord_t ax;
+	jas_image_coord_t ay;
+	jas_image_coord_t bx;
+	jas_image_coord_t by;
+	jas_image_coord_t d0;
+	jas_image_coord_t d1;
+	jas_image_coord_t d2;
+	jas_image_coord_t d3;
+	jas_image_coord_t oldx;
+	jas_image_coord_t oldy;
+	jas_image_coord_t x;
+	jas_image_coord_t y;
+	long v;
+	jas_image_coord_t cmptbrx;
+	jas_image_coord_t cmptbry;
+
+	assert(cmptno < image->numcmpts_);
+	const jas_image_cmpt_t *const oldcmpt = image->cmpts_[cmptno];
+	assert(oldcmpt->tlx_ == 0 && oldcmpt->tly_ == 0);
+	jas_image_calcbbox2(image, &tlx, &tly, &brx, &bry);
+	const unsigned width = FLOORDIV(brx - ho + hs, hs);
+	const unsigned height = FLOORDIV(bry - vo + vs, vs);
+	cmptparm.tlx = ho;
+	cmptparm.tly = vo;
+	cmptparm.hstep = hs;
+	cmptparm.vstep = vs;
+	cmptparm.width = width;
+	cmptparm.height = height;
+	cmptparm.prec = prec;
+	cmptparm.sgnd = sgnd;
+	if (jas_image_addcmpt(image, newcmptno, &cmptparm))
+		goto error;
+cmptbrx = oldcmpt->tlx_ + (oldcmpt->width_ - 1) * oldcmpt->hstep_;
+cmptbry = oldcmpt->tly_ + (oldcmpt->height_ - 1) * oldcmpt->vstep_;
+	const jas_image_cmpt_t *const newcmpt = image->cmpts_[newcmptno];
+	jas_stream_rewind(newcmpt->stream_);
+	for (unsigned i = 0; i < height; ++i) {
+		y = newcmpt->tly_ + newcmpt->vstep_ * i;
+		for (unsigned j = 0; j < width; ++j) {
+			x = newcmpt->tlx_ + newcmpt->hstep_ * j;
+			ax = downtomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_;
+			ay = downtomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_;
+			bx = uptomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_;
+			if (bx > cmptbrx)
+				bx = cmptbrx;
+			by = uptomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_;
+			if (by > cmptbry)
+				by = cmptbry;
+			d0 = (ax - x) * (ax - x) + (ay - y) * (ay - y);
+			d1 = (bx - x) * (bx - x) + (ay - y) * (ay - y);
+			d2 = (bx - x) * (bx - x) + (by - y) * (by - y);
+			d3 = (ax - x) * (ax - x) + (by - y) * (by - y);
+			if (d0 <= d1 && d0 <= d2 && d0 <= d3) {
+				oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_;
+				oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_;
+			} else if (d1 <= d0 && d1 <= d2 && d1 <= d3) {
+				oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_;
+				oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_;
+			} else if (d2 <= d0 && d2 <= d1 && d1 <= d3) {
+				oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_;
+				oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_;
+			} else {
+				oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_;
+				oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_;
+			}
+			assert(oldx >= 0 && oldx < oldcmpt->width_ &&
+			  oldy >= 0 && oldy < oldcmpt->height_);
+			if (jas_stream_seek(oldcmpt->stream_, oldcmpt->cps_ *
+			  (oldy * oldcmpt->width_ + oldx), SEEK_SET) < 0)
+				goto error;
+			if (getint(oldcmpt->stream_, oldcmpt->sgnd_,
+			  oldcmpt->prec_, &v))
+				goto error;
+			if (newcmpt->prec_ != oldcmpt->prec_ ||
+			  newcmpt->sgnd_ != oldcmpt->sgnd_) {
+				v = convert(v, oldcmpt->sgnd_, oldcmpt->prec_,
+				  newcmpt->sgnd_, newcmpt->prec_);
+			}
+			if (putint(newcmpt->stream_, newcmpt->sgnd_,
+			  newcmpt->prec_, v))
+				goto error;
+		}
+	}
+	return 0;
+error:
+	return -1;
+}
+
+int jas_image_ishomosamp(const jas_image_t *image)
+{
+	jas_image_coord_t hstep;
+	jas_image_coord_t vstep;
+	int result;
+	hstep = jas_image_cmpthstep(image, 0);
+	vstep = jas_image_cmptvstep(image, 0);
+	result = 1;
+	for (unsigned i = 0; i < image->numcmpts_; ++i) {
+		if (jas_image_cmpthstep(image, i) != hstep ||
+		  jas_image_cmptvstep(image, i) != vstep) {
+			result = 0;
+			break;
+		}
+	}
+	return result;
+}
+
+/* Note: This function defines a bounding box differently. */
+static void jas_image_calcbbox2(const jas_image_t *image, jas_image_coord_t *tlx,
+  jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry)
+{
+	jas_image_coord_t tmptlx;
+	jas_image_coord_t tmptly;
+	jas_image_coord_t tmpbrx;
+	jas_image_coord_t tmpbry;
+	jas_image_coord_t t;
+	if (image->numcmpts_ > 0) {
+		const jas_image_cmpt_t *cmpt = image->cmpts_[0];
+		tmptlx = cmpt->tlx_;
+		tmptly = cmpt->tly_;
+		tmpbrx = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1);
+		tmpbry = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1);
+		for (unsigned i = 0; i < image->numcmpts_; ++i) {
+			cmpt = image->cmpts_[i];
+			if (cmpt->tlx_ < tmptlx)
+				tmptlx = cmpt->tlx_;
+			if (cmpt->tly_ < tmptly)
+				tmptly = cmpt->tly_;
+			t = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1);
+			if (t > tmpbrx)
+				tmpbrx = t;
+			t = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1);
+			if (t > tmpbry)
+				tmpbry = t;
+		}
+	} else {
+		tmptlx = 0;
+		tmptly = 0;
+		tmpbrx = -1;
+		tmpbry = -1;
+	}
+	*tlx = tmptlx;
+	*tly = tmptly;
+	*brx = tmpbrx;
+	*bry = tmpbry;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline long decode_twos_comp(jas_ulong c, unsigned prec)
+{
+	long result;
+	assert(prec >= 2);
+	jas_eprintf("warning: support for signed data is untested\n");
+	// NOTE: Is this correct?
+	result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1)));
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jas_ulong encode_twos_comp(long n, unsigned prec)
+{
+	jas_ulong result;
+	assert(prec >= 2);
+	jas_eprintf("warning: support for signed data is untested\n");
+	// NOTE: Is this correct?
+	if (n < 0) {
+		result = -n;
+		result = (result ^ 0xffffffffUL) + 1;
+		result &= (1 << prec) - 1;
+	} else {
+		result = n;
+	}
+	return result;
+}
+
+static int getint(jas_stream_t *in, bool sgnd, unsigned prec, long *val)
+{
+	long v;
+	int c;
+	assert((!sgnd && prec >= 1) || (sgnd && prec >= 2));
+	v = 0;
+	for (unsigned n = (prec + 7) / 8; n-- > 0;) {
+		if ((c = jas_stream_getc(in)) == EOF)
+			return -1;
+		v = (v << 8) | c;
+	}
+	v &= ((1 << prec) - 1);
+	if (sgnd) {
+		*val = decode_twos_comp(v, prec);
+	} else {
+		*val = v;
+	}
+	return 0;
+}
+
+static int putint(jas_stream_t *out, bool sgnd, unsigned prec, long val)
+{
+	int c;
+	assert((!sgnd && prec >= 1) || (sgnd && prec >= 2));
+	if (sgnd) {
+		val = encode_twos_comp(val, prec);
+	}
+	assert(val >= 0);
+	val &= (1 << prec) - 1;
+	for (unsigned n = (prec + 7) / 8; n-- > 0;) {
+		c = (val >> (n * 8)) & 0xff;
+		if (jas_stream_putc(out, c) != c)
+			return -1;
+	}
+	return 0;
+}
+
+static long convert(long val, bool oldsgnd, unsigned oldprec, bool newsgnd,
+  unsigned newprec)
+{
+	if (newsgnd != oldsgnd) {
+	}
+	if (newprec != oldprec) {
+		if (newprec > oldprec) {
+			val <<= newprec - oldprec;
+		} else if (oldprec > newprec) {
+			val >>= oldprec - newprec;
+		}
+	}
+	return val;
+}
+
+static long downtomult(long x, long y)
+{
+	assert(x >= 0);
+	return (x / y) * y;
+}
+
+static long uptomult(long x, long y)
+{
+	assert(x >= 0);
+	return ((x + y - 1) / y) * y;
+}
+
+jas_image_t *jas_image_chclrspc(jas_image_t *image, const jas_cmprof_t *outprof,
+  jas_cmxform_intent_t intent)
+{
+	jas_image_t *inimage;
+	int k;
+	jas_image_t *outimage;
+	jas_cmprof_t *inprof;
+	jas_cmprof_t *tmpprof;
+	jas_image_cmptparm_t cmptparm;
+	jas_cmxform_t *xform;
+	jas_cmpixmap_t inpixmap;
+	jas_cmpixmap_t outpixmap;
+	jas_cmcmptfmt_t *incmptfmts;
+	jas_cmcmptfmt_t *outcmptfmts;
+
+#if 0
+jas_eprintf("IMAGE\n");
+jas_image_dump(image, stderr);
+#endif
+
+	if (image->numcmpts_ == 0)
+		/* can't work with a file with no components;
+		   continuing would crash because we'd attempt to
+		   obtain information about the first component */
+		return NULL;
+
+	outimage = 0;
+	xform = 0;
+	if (!(inimage = jas_image_copy(image)))
+		goto error;
+
+	if (!jas_image_ishomosamp(inimage)) {
+		unsigned minhstep = jas_image_cmpthstep(inimage, 0);
+		unsigned minvstep = jas_image_cmptvstep(inimage, 0);
+		for (unsigned i = 1; i < jas_image_numcmpts(inimage); ++i) {
+			const unsigned hstep = jas_image_cmpthstep(inimage, i);
+			const unsigned vstep = jas_image_cmptvstep(inimage, i);
+			if (hstep < minhstep) {
+				minhstep = hstep;
+			}
+			if (vstep < minvstep) {
+				minvstep = vstep;
+			}
+		}
+		unsigned n = jas_image_numcmpts(inimage);
+		for (unsigned i = 0; i < n; ++i) {
+			if (jas_image_sampcmpt(inimage, i, i + 1, 0, 0, minhstep, minvstep,
+			  jas_image_cmptsgnd(inimage, i), jas_image_cmptprec(inimage, i))) {
+				goto error;
+			}
+			const jas_image_cmpttype_t cmpttype = jas_image_cmpttype(inimage, i);
+			jas_image_setcmpttype(inimage, i + 1, cmpttype);
+			jas_image_delcmpt(inimage, i);
+		}
+	}
+
+	const unsigned width = jas_image_cmptwidth(inimage, 0);
+	const unsigned height = jas_image_cmptheight(inimage, 0);
+	const unsigned hstep = jas_image_cmpthstep(inimage, 0);
+	const unsigned vstep = jas_image_cmptvstep(inimage, 0);
+
+	if (!(inprof = jas_image_cmprof(inimage))) {
+		abort();
+	}
+	const unsigned numinclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(inprof));
+	const unsigned numoutclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(outprof));
+	const unsigned prec = 8;
+
+	if (!(outimage = jas_image_create0())) {
+		goto error;
+	}
+
+	/* Create a component for each of the colorants. */
+	for (unsigned i = 0; i < numoutclrchans; ++i) {
+		cmptparm.tlx = 0;
+		cmptparm.tly = 0;
+		cmptparm.hstep = hstep;
+		cmptparm.vstep = vstep;
+		cmptparm.width = width;
+		cmptparm.height = height;
+		cmptparm.prec = prec;
+		cmptparm.sgnd = 0;
+		if (jas_image_addcmpt(outimage, -1, &cmptparm))
+			goto error;
+		jas_image_setcmpttype(outimage, i, JAS_IMAGE_CT_COLOR(i));
+	}
+#if 0
+	/* Copy the auxiliary components without modification. */
+	for (i = 0; i < jas_image_numcmpts(inimage); ++i) {
+		if (!ISCOLOR(jas_image_cmpttype(inimage, i))) {
+			jas_image_copycmpt(outimage, -1, inimage, i);
+/* XXX - need to specify laydown of component on ref. grid */
+		}
+	}
+#endif
+
+	if (!(tmpprof = jas_cmprof_copy(outprof)))
+		goto error;
+	assert(!jas_image_cmprof(outimage));
+	jas_image_setcmprof(outimage, tmpprof);
+	jas_image_setclrspc(outimage, jas_cmprof_clrspc(outprof));
+
+	if (!(xform = jas_cmxform_create(inprof, outprof, 0, JAS_CMXFORM_OP_FWD,
+	  intent, JAS_CMXFORM_OPTM_SPEED))) {
+		goto error;
+	}
+
+	inpixmap.numcmpts = numinclrchans;
+	if (!(incmptfmts = jas_alloc2(numinclrchans, sizeof(jas_cmcmptfmt_t)))) {
+		abort();
+	}
+	inpixmap.cmptfmts = incmptfmts;
+	for (unsigned i = 0; i < numinclrchans; ++i) {
+		const int j = jas_image_getcmptbytype(inimage, JAS_IMAGE_CT_COLOR(i));
+		if (!(incmptfmts[i].buf = jas_alloc2(width, sizeof(long)))) {
+			goto error;
+		}
+		incmptfmts[i].prec = jas_image_cmptprec(inimage, j);
+		incmptfmts[i].sgnd = jas_image_cmptsgnd(inimage, j);
+		incmptfmts[i].width = width;
+		incmptfmts[i].height = 1;
+	}
+
+	outpixmap.numcmpts = numoutclrchans;
+	if (!(outcmptfmts = jas_alloc2(numoutclrchans, sizeof(jas_cmcmptfmt_t)))) {
+		abort();
+	}
+	outpixmap.cmptfmts = outcmptfmts;
+
+	for (unsigned i = 0; i < numoutclrchans; ++i) {
+		const int j = jas_image_getcmptbytype(outimage, JAS_IMAGE_CT_COLOR(i));
+		if (!(outcmptfmts[i].buf = jas_alloc2(width, sizeof(long))))
+			goto error;
+		outcmptfmts[i].prec = jas_image_cmptprec(outimage, j);
+		outcmptfmts[i].sgnd = jas_image_cmptsgnd(outimage, j);
+		outcmptfmts[i].width = width;
+		outcmptfmts[i].height = 1;
+	}
+
+	for (unsigned i = 0; i < height; ++i) {
+		for (unsigned j = 0; j < numinclrchans; ++j) {
+			k = jas_image_getcmptbytype(inimage, JAS_IMAGE_CT_COLOR(j));
+			if (jas_image_readcmpt2(inimage, k, 0, i, width, 1,
+			  incmptfmts[j].buf))
+				goto error;
+		}
+		jas_cmxform_apply(xform, &inpixmap, &outpixmap);
+		for (unsigned j = 0; j < numoutclrchans; ++j) {
+			k = jas_image_getcmptbytype(outimage, JAS_IMAGE_CT_COLOR(j));
+			if (jas_image_writecmpt2(outimage, k, 0, i, width, 1,
+			  outcmptfmts[j].buf))
+				goto error;
+		}
+	}
+
+	for (unsigned i = 0; i < numoutclrchans; ++i) {
+		jas_free(outcmptfmts[i].buf);
+	}
+	jas_free(outcmptfmts);
+	for (unsigned i = 0; i < numinclrchans; ++i) {
+		jas_free(incmptfmts[i].buf);
+	}
+	jas_free(incmptfmts);
+	jas_cmxform_destroy(xform);
+	jas_image_destroy(inimage);
+
+#if 0
+jas_eprintf("INIMAGE\n");
+jas_image_dump(inimage, stderr);
+jas_eprintf("OUTIMAGE\n");
+jas_image_dump(outimage, stderr);
+#endif
+	return outimage;
+error:
+	if (xform)
+		jas_cmxform_destroy(xform);
+	if (inimage)
+		jas_image_destroy(inimage);
+	if (outimage)
+		jas_image_destroy(outimage);
+	return 0;
+}
--- /dev/null
+++ b/jas_init.c
@@ -1,0 +1,107 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_init.h"
+#include "jasper/jas_image.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/* Initialize the image format table. */
+JAS_DLLEXPORT
+int jas_init(void)
+{
+	jas_image_fmtops_t fmtops;
+	int fmtid = 0;
+
+#if defined(JAS_INCLUDE_JP2_CODEC)
+	fmtops.decode = jp2_decode;
+	fmtops.validate = jp2_validate;
+	jas_image_addfmt(fmtid++, "jp2", "jp2",
+	  "JPEG-2000 JP2 File Format Syntax (ISO/IEC 15444-1)", &fmtops);
+#endif
+
+#if defined(JAS_INCLUDE_JPC_CODEC) || defined(JAS_INCLUDE_JP2_CODEC)
+	fmtops.decode = jpc_decode;
+	fmtops.validate = jpc_validate;
+	jas_image_addfmt(fmtid, "jpc", "jpc",
+	  "JPEG-2000 Code Stream Syntax (ISO/IEC 15444-1)", &fmtops);
+#endif
+
+	/* We must not register the JasPer library exit handler until after
+	at least one memory allocation is performed.  This is desirable
+	as it ensures that the JasPer exit handler is called before the
+	debug memory allocator exit handler. */
+	atexit(jas_cleanup);
+
+	return 0;
+}
+
+JAS_DLLEXPORT
+void jas_cleanup(void)
+{
+	jas_image_clearfmts();
+}
--- /dev/null
+++ b/jas_malloc.c
@@ -1,0 +1,299 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Memory Allocator
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+#include "jasper/jas_math.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
+
+static size_t jas_mem = 0;
+static size_t jas_max_mem = JAS_DEFAULT_MAX_MEM_USAGE;
+
+typedef struct {
+	size_t size;
+} jas_mb_t;
+
+#define JAS_MB_ADJUST \
+  ((sizeof(jas_mb_t) + sizeof(max_align_t) - 1) / sizeof(max_align_t))
+#define JAS_MB_SIZE (JAS_MB_ADJUST * sizeof(max_align_t))
+
+jas_mb_t *jas_get_mb(void *ptr)
+{
+	return JAS_CAST(jas_mb_t *, JAS_CAST(max_align_t *, ptr) - JAS_MB_ADJUST);
+}
+
+void *jas_mb_get_data(jas_mb_t *mb)
+{
+	return JAS_CAST(void *, JAS_CAST(max_align_t *, mb) + JAS_MB_ADJUST);
+}
+
+void jas_set_max_mem_usage(size_t max_mem)
+{
+	jas_max_mem = max_mem;
+}
+
+size_t jas_get_mem_usage()
+{
+	return jas_mem;
+}
+
+void *jas_malloc(size_t size)
+{
+	void *result;
+	jas_mb_t *mb;
+	size_t ext_size;
+	size_t mem;
+
+	JAS_DBGLOG(100, ("jas_malloc(%zu)\n", size));
+#if defined(JAS_MALLOC_RETURN_NULL_PTR_FOR_ZERO_SIZE)
+	if (!size) {
+		return 0;
+	}
+#endif
+	if (!jas_safe_size_add(size, JAS_MB_SIZE, &ext_size)) {
+		jas_eprintf("requested memory size is too large\n");
+		result = 0;
+		mb = 0;
+	} else if (!jas_safe_size_add(jas_mem, size, &mem) || mem > jas_max_mem) {
+		jas_eprintf("maximum memory limit would be exceeded\n");
+		result = 0;
+		mb = 0;
+	} else {
+		JAS_DBGLOG(100, ("jas_malloc: ext_size=%zu\n", ext_size));
+		if ((mb = malloc(ext_size))) {
+			result = jas_mb_get_data(mb);
+			mb->size = size;
+			jas_mem = mem;
+		} else {
+			result = 0;
+		}
+	}
+	JAS_DBGLOG(99, ("jas_malloc(%zu) -> %p (mb=%p)\n", size, result, mb));
+	JAS_DBGLOG(102, ("max_mem=%zu; mem=%zu\n", jas_max_mem, jas_mem));
+	return result;
+}
+
+void *jas_realloc(void *ptr, size_t size)
+{
+	void *result;
+	jas_mb_t *mb;
+	jas_mb_t *old_mb;
+	size_t old_size;
+	size_t ext_size;
+	size_t mem;
+
+	JAS_DBGLOG(100, ("jas_realloc(%p, %zu)\n", ptr, size));
+	if (!ptr) {
+		return jas_malloc(size);
+	}
+	if (ptr && !size) {
+		jas_free(ptr);
+	}
+	if (!jas_safe_size_add(size, JAS_MB_SIZE, &ext_size)) {
+		jas_eprintf("requested memory size is too large\n");
+		return 0;
+	}
+	old_mb = jas_get_mb(ptr);
+	old_size = old_mb->size;
+	JAS_DBGLOG(101, ("jas_realloc: old_mb=%p; old_size=%zu\n", old_mb,
+	  old_size));
+	if (size > old_size) {
+		if (!jas_safe_size_add(jas_mem, ext_size, &mem) || mem > jas_max_mem) {
+			jas_eprintf("maximum memory limit would be exceeded\n");
+			return 0;
+		}
+	} else {
+		if (!jas_safe_size_sub(jas_mem, old_size - size, &jas_mem)) {
+			jas_eprintf("heap corruption detected\n");
+			abort();
+		}
+	}
+	JAS_DBGLOG(100, ("jas_realloc: realloc(%p, %zu)\n", old_mb, ext_size));
+	if (!(mb = realloc(old_mb, ext_size))) {
+		result = 0;
+	} else {
+		result = jas_mb_get_data(mb);
+		mb->size = size;
+		jas_mem = mem;
+	}
+	JAS_DBGLOG(100, ("jas_realloc(%p, %zu) -> %p (%p)\n", ptr, size, result,
+	  mb));
+	JAS_DBGLOG(102, ("max_mem=%zu; mem=%zu\n", jas_max_mem, jas_mem));
+	return result;
+}
+
+void jas_free(void *ptr)
+{
+	jas_mb_t *mb;
+	size_t mem;
+	size_t size;
+	JAS_DBGLOG(100, ("jas_free(%p)\n", ptr));
+	if (ptr) {
+		mb = jas_get_mb(ptr);
+		size = mb->size;
+		JAS_DBGLOG(101, ("jas_free(%p) (mb=%p; size=%zu)\n", ptr, mb, size));
+		if (!jas_safe_size_sub(jas_mem, size, &jas_mem)) {
+			jas_eprintf("heap corruption detected\n");
+			abort();
+		}
+		JAS_DBGLOG(100, ("jas_free: free(%p)\n", mb));
+		free(mb);
+	}
+	JAS_DBGLOG(102, ("max_mem=%zu; mem=%zu\n", jas_max_mem, jas_mem));
+}
+
+#endif
+
+/******************************************************************************\
+* Basic memory allocation and deallocation primitives.
+\******************************************************************************/
+
+#if !defined(JAS_DEFAULT_MAX_MEM_USAGE)
+
+void *jas_malloc(size_t size)
+{
+	void *result;
+	JAS_DBGLOG(101, ("jas_malloc(%zu)\n", size));
+	result = malloc(size);
+	JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result));
+	return result;
+}
+
+void *jas_realloc(void *ptr, size_t size)
+{
+	void *result;
+	JAS_DBGLOG(101, ("jas_realloc(%p, %zu)\n", ptr, size));
+	result = realloc(ptr, size);
+	JAS_DBGLOG(100, ("jas_realloc(%p, %zu) -> %p\n", ptr, size, result));
+	return result;
+}
+
+void jas_free(void *ptr)
+{
+	JAS_DBGLOG(100, ("jas_free(%p)\n", ptr));
+	free(ptr);
+}
+
+#endif
+
+/******************************************************************************\
+* Additional memory allocation and deallocation primitives
+* (mainly for overflow checking).
+\******************************************************************************/
+
+void *jas_alloc2(size_t num_elements, size_t element_size)
+{
+	size_t size;
+	if (!jas_safe_size_mul(num_elements, element_size, &size)) {
+		return 0;
+	}
+	return jas_malloc(size);
+}
+
+void *jas_alloc3(size_t num_arrays, size_t array_size, size_t element_size)
+{
+	size_t size;
+	if (!jas_safe_size_mul(array_size, element_size, &size) ||
+	  !jas_safe_size_mul(size, num_arrays, &size)) {
+		return 0;
+	}
+	return jas_malloc(size);
+}
+
+void *jas_realloc2(void *ptr, size_t num_elements, size_t element_size)
+{
+	size_t size;
+	if (!jas_safe_size_mul(num_elements, element_size, &size)) {
+		return 0;
+	}
+	return jas_realloc(ptr, size);
+}
+
+void *jas_calloc(size_t num_elements, size_t element_size)
+{
+	void *ptr;
+	size_t size;
+	if (!jas_safe_size_mul(num_elements, element_size, &size)) {
+		return 0;
+	}
+	if (!(ptr = jas_malloc(size))) {
+		return 0;
+	}
+	memset(ptr, 0, size);
+	return ptr;
+}
--- /dev/null
+++ b/jas_seq.c
@@ -1,0 +1,408 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Sequence/Matrix Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_seq.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+
+/******************************************************************************\
+* Constructors and destructors.
+\******************************************************************************/
+
+jas_matrix_t *jas_seq2d_create(jas_matind_t xstart, jas_matind_t ystart,
+  jas_matind_t xend, jas_matind_t yend)
+{
+	jas_matrix_t *matrix;
+	assert(xstart <= xend && ystart <= yend);
+	if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {
+		return 0;
+	}
+	matrix->xstart_ = xstart;
+	matrix->ystart_ = ystart;
+	matrix->xend_ = xend;
+	matrix->yend_ = yend;
+	return matrix;
+}
+
+jas_matrix_t *jas_matrix_create(jas_matind_t numrows, jas_matind_t numcols)
+{
+	jas_matrix_t *matrix;
+	jas_matind_t i;
+	size_t size;
+
+	if (numrows < 0 || numcols < 0) {
+		return NULL;
+	}
+
+	// matrix->datasize_ = numrows * numcols;
+	if (!jas_safe_size_mul(numrows, numcols, &size)) {
+		return NULL;
+	}
+
+	if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
+		return NULL;
+	}
+	matrix->flags_ = 0;
+	matrix->numrows_ = numrows;
+	matrix->numcols_ = numcols;
+	matrix->rows_ = 0;
+	matrix->maxrows_ = numrows;
+	matrix->data_ = 0;
+	matrix->datasize_ = size;
+
+	if (matrix->maxrows_ > 0) {
+		if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,
+		  sizeof(jas_seqent_t *)))) {
+			goto error;
+		}
+	}
+
+	if (matrix->datasize_ > 0) {
+		if (!(matrix->data_ = jas_alloc2(matrix->datasize_,
+		  sizeof(jas_seqent_t)))) {
+			goto error;
+		}
+
+		memset(matrix->data_, 0,
+		       matrix->datasize_ * sizeof(jas_seqent_t));
+	}
+
+	for (i = 0; i < numrows; ++i) {
+		matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
+	}
+
+	matrix->xstart_ = 0;
+	matrix->ystart_ = 0;
+	matrix->xend_ = matrix->numcols_;
+	matrix->yend_ = matrix->numrows_;
+
+	return matrix;
+
+error:
+	jas_matrix_destroy(matrix);
+	return 0;
+}
+
+void jas_matrix_destroy(jas_matrix_t *matrix)
+{
+	if (matrix->data_) {
+		assert(!(matrix->flags_ & JAS_MATRIX_REF));
+	}
+	jas_free(matrix->data_);
+	jas_free(matrix->rows_);
+	jas_free(matrix);
+}
+
+jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)
+{
+	jas_matrix_t *y;
+	jas_matind_t i;
+	jas_matind_t j;
+	y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x),
+	  jas_seq2d_xend(x), jas_seq2d_yend(x));
+	assert(y);
+	for (i = 0; i < x->numrows_; ++i) {
+		for (j = 0; j < x->numcols_; ++j) {
+			*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
+		}
+	}
+	return y;
+}
+
+jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)
+{
+	jas_matrix_t *y;
+	jas_matind_t i;
+	jas_matind_t j;
+	y = jas_matrix_create(x->numrows_, x->numcols_);
+	for (i = 0; i < x->numrows_; ++i) {
+		for (j = 0; j < x->numcols_; ++j) {
+			*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
+		}
+	}
+	return y;
+}
+
+/******************************************************************************\
+* Bind operations.
+\******************************************************************************/
+
+int jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, jas_matind_t xstart,
+  jas_matind_t ystart, jas_matind_t xend, jas_matind_t yend)
+{
+	if (xstart < s1->xstart_ || ystart < s1->ystart_ ||
+	    xend > s1->xend_ || yend > s1->yend_)
+		return -1;
+
+	return jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,
+				  yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);
+}
+
+int jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1,
+  jas_matind_t r0, jas_matind_t c0, jas_matind_t r1, jas_matind_t c1)
+{
+	jas_matind_t i;
+
+	if (mat0->data_) {
+		if (!(mat0->flags_ & JAS_MATRIX_REF)) {
+			jas_free(mat0->data_);
+		}
+		mat0->data_ = 0;
+		mat0->datasize_ = 0;
+	}
+	if (mat0->rows_) {
+		jas_free(mat0->rows_);
+		mat0->rows_ = 0;
+	}
+	mat0->flags_ |= JAS_MATRIX_REF;
+	mat0->numrows_ = r1 - r0 + 1;
+	mat0->numcols_ = c1 - c0 + 1;
+	mat0->maxrows_ = mat0->numrows_;
+	if (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {
+		return -1;
+	}
+
+	for (i = 0; i < mat0->numrows_; ++i) {
+		mat0->rows_[i] = mat1->rows_[r0 + i] + c0;
+	}
+
+	mat0->xstart_ = mat1->xstart_ + c0;
+	mat0->ystart_ = mat1->ystart_ + r0;
+	mat0->xend_ = mat0->xstart_ + mat0->numcols_;
+	mat0->yend_ = mat0->ystart_ + mat0->numrows_;
+
+	return 0;
+}
+
+/******************************************************************************\
+* Arithmetic operations.
+\******************************************************************************/
+
+int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)
+{
+	jas_matind_t i;
+	jas_matind_t j;
+
+	if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=
+	  mat1->numcols_) {
+		return 1;
+	}
+	for (i = 0; i < mat0->numrows_; i++) {
+		for (j = 0; j < mat0->numcols_; j++) {
+			if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {
+				return 1;
+			}
+		}
+	}
+	return 0;
+}
+
+void jas_matrix_divpow2(jas_matrix_t *matrix, unsigned n)
+{
+	jas_matind_t i;
+	jas_matind_t j;
+	jas_seqent_t *rowstart;
+	jas_matind_t rowstep;
+	jas_seqent_t *data;
+
+	if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
+		assert(matrix->rows_);
+		rowstep = jas_matrix_rowstep(matrix);
+		for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+		  rowstart += rowstep) {
+			for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+			  ++data) {
+				*data = (*data >= 0) ? ((*data) >> n) :
+				  (-((-(*data)) >> n));
+			}
+		}
+	}
+}
+
+void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,
+  jas_seqent_t maxval)
+{
+	jas_matind_t i;
+	jas_matind_t j;
+	jas_seqent_t v;
+	jas_seqent_t *rowstart;
+	jas_seqent_t *data;
+	jas_matind_t rowstep;
+
+	if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
+		assert(matrix->rows_);
+		rowstep = jas_matrix_rowstep(matrix);
+		for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+		  rowstart += rowstep) {
+			for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+			  ++data) {
+				v = *data;
+				if (v < minval) {
+					*data = minval;
+				} else if (v > maxval) {
+					*data = maxval;
+				}
+			}
+		}
+	}
+}
+
+void jas_matrix_asr(jas_matrix_t *matrix, unsigned n)
+{
+	jas_matind_t i;
+	jas_matind_t j;
+	jas_seqent_t *rowstart;
+	jas_matind_t rowstep;
+	jas_seqent_t *data;
+
+	if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
+		assert(matrix->rows_);
+		rowstep = jas_matrix_rowstep(matrix);
+		for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+		  rowstart += rowstep) {
+			for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+			  ++data) {
+				//*data >>= n;
+				*data = jas_seqent_asr(*data, n);
+			}
+		}
+	}
+}
+
+void jas_matrix_asl(jas_matrix_t *matrix, unsigned n)
+{
+	jas_matind_t i;
+	jas_matind_t j;
+	jas_seqent_t *rowstart;
+	jas_matind_t rowstep;
+	jas_seqent_t *data;
+
+	if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
+		assert(matrix->rows_);
+		rowstep = jas_matrix_rowstep(matrix);
+		for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+		  rowstart += rowstep) {
+			for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+			  ++data) {
+				//*data <<= n;
+				*data = jas_seqent_asl(*data, n);
+			}
+		}
+	}
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+int jas_matrix_resize(jas_matrix_t *matrix, jas_matind_t numrows,
+  jas_matind_t numcols)
+{
+	jas_matind_t size;
+	jas_matind_t i;
+
+	size = numrows * numcols;
+	if (size > matrix->datasize_ || numrows > matrix->maxrows_) {
+		return -1;
+	}
+
+	matrix->numrows_ = numrows;
+	matrix->numcols_ = numcols;
+
+	for (i = 0; i < numrows; ++i) {
+		matrix->rows_[i] = &matrix->data_[numcols * i];
+	}
+
+	return 0;
+}
+
+void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
+{
+	jas_matind_t i;
+	jas_matind_t j;
+	jas_seqent_t *rowstart;
+	jas_matind_t rowstep;
+	jas_seqent_t *data;
+
+	if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
+		assert(matrix->rows_);
+		rowstep = jas_matrix_rowstep(matrix);
+		for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
+		  rowstart += rowstep) {
+			for (j = matrix->numcols_, data = rowstart; j > 0; --j,
+			  ++data) {
+				*data = val;
+			}
+		}
+	}
+}
--- /dev/null
+++ b/jas_stream.c
@@ -1,0 +1,1454 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * I/O Stream Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_stream.h"
+#include "jasper/jas_debug.h"
+#include "jasper/jas_types.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static int jas_strtoopenmode(const char *s);
+static void jas_stream_destroy(jas_stream_t *stream);
+static jas_stream_t *jas_stream_create(void);
+static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
+  int bufsize);
+
+static int mem_read(jas_stream_obj_t *obj, char *buf, unsigned cnt);
+static int mem_write(jas_stream_obj_t *obj, const char *buf, unsigned cnt);
+static long mem_seek(jas_stream_obj_t *obj, long offset, int origin);
+static int mem_close(jas_stream_obj_t *obj);
+
+static int sfile_read(jas_stream_obj_t *obj, char *buf, unsigned cnt);
+static int sfile_write(jas_stream_obj_t *obj, const char *buf, unsigned cnt);
+static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin);
+static int sfile_close(jas_stream_obj_t *obj);
+
+static int file_read(jas_stream_obj_t *obj, char *buf, unsigned cnt);
+static int file_write(jas_stream_obj_t *obj, const char *buf, unsigned cnt);
+static long file_seek(jas_stream_obj_t *obj, long offset, int origin);
+static int file_close(jas_stream_obj_t *obj);
+
+/******************************************************************************\
+* Local data.
+\******************************************************************************/
+
+static const jas_stream_ops_t jas_stream_fileops = {
+	file_read,
+	file_write,
+	file_seek,
+	file_close
+};
+
+static const jas_stream_ops_t jas_stream_sfileops = {
+	sfile_read,
+	sfile_write,
+	sfile_seek,
+	sfile_close
+};
+
+static const jas_stream_ops_t jas_stream_memops = {
+	mem_read,
+	mem_write,
+	mem_seek,
+	mem_close
+};
+
+/******************************************************************************\
+* Code for opening and closing streams.
+\******************************************************************************/
+
+static jas_stream_t *jas_stream_create()
+{
+	jas_stream_t *stream;
+
+	if (!(stream = jas_malloc(sizeof(jas_stream_t)))) {
+		return 0;
+	}
+	stream->openmode_ = 0;
+	stream->bufmode_ = 0;
+	stream->flags_ = 0;
+	stream->bufbase_ = 0;
+	stream->bufstart_ = 0;
+	stream->bufsize_ = 0;
+	stream->ptr_ = 0;
+	stream->cnt_ = 0;
+	stream->ops_ = 0;
+	stream->obj_ = 0;
+	stream->rwcnt_ = 0;
+	stream->rwlimit_ = -1;
+
+	return stream;
+}
+
+/*
+This function will eventually replace jas_stream_memopen.
+For documentation of the interface for this function, see jas_stream.h.
+*/
+
+jas_stream_t *jas_stream_memopen2(char *buf, size_t bufsize)
+{
+	jas_stream_t *stream;
+	jas_stream_memobj_t *obj;
+
+	JAS_DBGLOG(100, ("jas_stream_memopen2(%p, %zu)\n", buf, bufsize));
+
+	assert((buf && bufsize > 0) || (!buf));
+
+	if (!(stream = jas_stream_create())) {
+		return 0;
+	}
+
+	/* A stream associated with a memory buffer is always opened
+	for both reading and writing in binary mode. */
+	stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY;
+
+	/* Since the stream data is already resident in memory, buffering
+	is not necessary. */
+	jas_stream_initbuf(stream, JAS_STREAM_UNBUF, 0, 0);
+
+	/* Select the operations for a memory stream. */
+	stream->ops_ = &jas_stream_memops;
+
+	/* Allocate memory for the underlying memory stream object. */
+	if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) {
+		jas_stream_destroy(stream);
+		return 0;
+	}
+	stream->obj_ = (void *) obj;
+
+	/* Initialize a few important members of the memory stream object. */
+	obj->myalloc_ = 0;
+	obj->buf_ = 0;
+
+	/* If the buffer size specified is nonpositive, then the buffer
+	is allocated internally and automatically grown as needed. */
+	if (!bufsize) {
+		obj->bufsize_ = 1024;
+		obj->growable_ = 1;
+	} else {
+		obj->bufsize_ = bufsize;
+		obj->growable_ = 0;
+	}
+	if (buf) {
+		obj->buf_ = JAS_CAST(unsigned char *, buf);
+	} else {
+		obj->buf_ = jas_malloc(obj->bufsize_);
+		obj->myalloc_ = 1;
+	}
+	if (!obj->buf_) {
+		jas_stream_close(stream);
+		return 0;
+	}
+	JAS_DBGLOG(100, ("jas_stream_memopen2 buffer buf=%p myalloc=%d\n",
+	  obj->buf_, obj->myalloc_));
+
+	if (bufsize > 0 && buf) {
+		/* If a buffer was supplied by the caller and its length is positive,
+		  make the associated buffer data appear in the stream initially. */
+		obj->len_ = bufsize;
+	} else {
+		/* The stream is initially empty. */
+		obj->len_ = 0;
+	}
+	obj->pos_ = 0;
+	
+	return stream;
+}
+
+/*
+NOTE:
+The version of the function jas_stream_memopen only exists for backwards
+compatibility.
+Eventually, it should be replaced by jas_stream_memopen2.
+In retrospect, it was a very poor choice to have specified the buffer
+size parameter (bufsize) to have type int.  On some machines, int may only
+be a 16-bit integer.  This precludes larger-sized buffer allocations, which
+are needed in practice.
+
+If bufsize <= 0, the buffer is growable; otherwise, the buffer has a fixed
+size of bufsize.
+If buf is 0, the buffer is dynamically allocated with jas_malloc.
+If buf is not 0 and bufsize <= 0 (which is not permitted in any
+circumstances), bad things will happen (especially if the buf was not
+allocated with jas_malloc).
+*/
+jas_stream_t *jas_stream_memopen(char *buf, int bufsize)
+{
+	char *new_buf;
+	size_t new_bufsize;
+
+	JAS_DBGLOG(100, ("jas_stream_memopen(%p, %d)\n", buf, bufsize));
+	if (bufsize < 0) {
+		jas_deprecated("negative buffer size for jas_stream_memopen");
+	}
+	if (buf && bufsize <= 0) {
+		// This was never a valid thing to do with the old API.
+		jas_eprintf("Invalid use of jas_stream_memopen detected.\n");
+		jas_deprecated("A user-provided buffer for "
+		  "jas_stream_memopen cannot be growable.\n");
+	}
+	if (bufsize <= 0) {
+		new_bufsize = 0;
+		new_buf = 0;
+	} else {
+		new_bufsize = bufsize;
+		new_buf = buf;
+	}
+	return jas_stream_memopen2(new_buf, new_bufsize);
+}
+
+jas_stream_t *jas_stream_fopen(const char *filename, const char *mode)
+{
+	jas_stream_t *stream;
+	jas_stream_fileobj_t *obj;
+	int openflags;
+
+	JAS_DBGLOG(100, ("jas_stream_fopen(\"%s\", \"%s\")\n", filename, mode));
+
+	/* Allocate a stream object. */
+	if (!(stream = jas_stream_create())) {
+		return 0;
+	}
+
+	/* Parse the mode string. */
+	stream->openmode_ = jas_strtoopenmode(mode);
+
+	/* Determine the correct flags to use for opening the file. */
+	if ((stream->openmode_ & JAS_STREAM_READ) &&
+	  (stream->openmode_ & JAS_STREAM_WRITE)) {
+		openflags = ORDWR;
+	} else if (stream->openmode_ & JAS_STREAM_READ) {
+		openflags = OREAD;
+	} else if (stream->openmode_ & JAS_STREAM_WRITE) {
+		openflags = OWRITE;
+	} else {
+		openflags = 0;
+	}
+	if (stream->openmode_ & JAS_STREAM_CREATE) {
+		openflags |= OTRUNC;
+	}
+
+	openflags |= OCEXEC;
+
+	/* Allocate space for the underlying file stream object. */
+	if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) {
+		jas_stream_destroy(stream);
+		return 0;
+	}
+	obj->fd = -1;
+	obj->flags = 0;
+	obj->pathname[0] = '\0';
+	stream->obj_ = (void *) obj;
+
+	/* Select the operations for a file stream object. */
+	stream->ops_ = &jas_stream_fileops;
+
+	if (stream->openmode_ & JAS_STREAM_CREATE) {
+		obj->fd = create(filename, openflags, JAS_STREAM_PERMS);
+	} else {
+		obj->fd = open(filename, openflags);
+	}
+
+	/* Open the underlying file. */
+	if (obj->fd < 0) {
+		// Free the underlying file object, since it will not otherwise
+		// be freed.
+		jas_free(obj);
+		jas_stream_destroy(stream);
+		return 0;
+	}
+	if (stream->openmode_ & JAS_STREAM_APPEND) {
+		seek(obj->fd, 0, 2);
+	}
+
+	/* By default, use full buffering for this type of stream. */
+	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+
+	return stream;
+}
+
+jas_stream_t *jas_stream_freopen(const char *path, const char *mode, FILE *fp)
+{
+	jas_stream_t *stream;
+
+	JAS_DBGLOG(100, ("jas_stream_freopen(\"%s\", \"%s\", %p)\n", path, mode,
+	  fp));
+
+	/* Eliminate compiler warning about unused variable. */
+	USED(path);
+
+	/* Allocate a stream object. */
+	if (!(stream = jas_stream_create())) {
+		return 0;
+	}
+
+	/* Parse the mode string. */
+	stream->openmode_ = jas_strtoopenmode(mode);
+
+	stream->obj_ = JAS_CAST(void *, fp);
+
+	/* Select the operations for a file stream object. */
+	stream->ops_ = &jas_stream_sfileops;
+
+	/* By default, use full buffering for this type of stream. */
+	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+
+	return stream;
+}
+
+#ifndef _WIN32
+
+/**
+ * Copy the absolute path of the directory for temporary files to the
+ * given buffer (without a null terminator), including a trailing path
+ * separator.
+ *
+ * @return the number of characters copied to the buffer or 0 on error
+ */
+static size_t get_temp_directory(char *buffer, size_t size)
+{
+	const char *tmpdir = getenv("TMPDIR");
+	if (tmpdir == NULL)
+		tmpdir = "/tmp";
+
+	size_t length = strlen(tmpdir);
+	if (length + 1 > size)
+		return 0;
+
+	memcpy(buffer, tmpdir, length);
+	buffer[length++] = '/';
+	return length;
+}
+
+#endif /* !_WIN32 */
+
+/**
+ * Generate a template for mkstemp().
+ *
+ * @return 0 on success, -1 on error
+ */
+static int make_mkstemp_template(char *buffer, size_t size)
+{
+#ifdef _WIN32
+	char temp_directory[MAX_PATH];
+	if (GetTempPathA(sizeof(temp_directory), temp_directory) == 0)
+		return -1;
+
+	(void)size;
+
+	return GetTempFileNameA(temp_directory, "jasper", 0, buffer) > 0
+		? 0 : -1;
+#else
+	static const char base[] = "jasper.XXXXXXXXXXX";
+
+	size_t length = get_temp_directory(buffer, size);
+	if (length == 0 || length + sizeof(base) >= size)
+		return -1;
+
+	memcpy(buffer + length, base, sizeof(base));
+	return 0;
+#endif
+}
+
+/**
+ * A wrapper for mkstemp() which generates a template for mkstemp()
+ * before calling the function.
+ *
+ * @return a non-negative file descriptor on success, -1 on error
+ */
+static int easy_mkstemp(char *buffer, size_t size)
+{
+#if defined(__linux__) && defined(O_TMPFILE)
+	/* try to use O_TMPFILE, which is a Linux-specific feature to
+	   create a temporary file without a name, not linked to any
+	   directory; this is even more secure than mkstemp() */
+	const char *tmpdir = getenv("TMPDIR");
+	if (tmpdir == NULL)
+		tmpdir = "/tmp";
+
+	int fd = open(tmpdir, O_TMPFILE|O_RDWR, JAS_STREAM_PERMS);
+	if (fd >= 0) {
+		*buffer = 0;
+		return fd;
+	}
+#endif
+
+	if (make_mkstemp_template(buffer, size))
+		return -1;
+
+#ifdef _WIN32
+	return open(buffer,
+		    O_CREAT | O_EXCL | O_RDWR | O_TRUNC | O_BINARY | O_CLOEXEC,
+		    JAS_STREAM_PERMS);
+#else
+#ifdef JAS_HAVE_MKOSTEMP
+	return mkostemp(buffer, O_CLOEXEC);
+#else
+	return create(mktemp(buffer), OTRUNC|ORDWR|OEXCL|OCEXEC, JAS_STREAM_PERMS);
+#endif
+#endif
+}
+
+jas_stream_t *jas_stream_tmpfile()
+{
+	jas_stream_t *stream;
+	jas_stream_fileobj_t *obj;
+
+	JAS_DBGLOG(100, ("jas_stream_tmpfile()\n"));
+
+	if (!(stream = jas_stream_create())) {
+		return 0;
+	}
+
+	/* A temporary file stream is always opened for both reading and
+	writing in binary mode. */
+	stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY;
+
+	/* Allocate memory for the underlying temporary file object. */
+	if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) {
+		jas_stream_destroy(stream);
+		return 0;
+	}
+	obj->fd = -1;
+	obj->flags = 0;
+	obj->pathname[0] = '\0';
+	stream->obj_ = obj;
+
+	/* Create the temporary file. */
+	if ((obj->fd = easy_mkstemp(obj->pathname, sizeof(obj->pathname))) < 0) {
+		jas_stream_destroy(stream);
+		return 0;
+	}
+
+	/* Unlink the file so that it will disappear if the program
+	terminates abnormally. */
+	/* Under UNIX, one can unlink an open file and continue to do I/O
+	on it.  Not all operating systems support this functionality, however.
+	For example, under Microsoft Windows the unlink operation will fail,
+	since the file is open. */
+	if (*obj->pathname != 0 && remove(obj->pathname) < 0) {
+		/* We will try unlinking the file again after it is closed. */
+		obj->flags |= JAS_STREAM_FILEOBJ_DELONCLOSE;
+	}
+
+	/* Use full buffering. */
+	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+
+	stream->ops_ = &jas_stream_fileops;
+
+	return stream;
+}
+
+jas_stream_t *jas_stream_fdopen(int fd, const char *mode)
+{
+	jas_stream_t *stream;
+	jas_stream_fileobj_t *obj;
+
+	JAS_DBGLOG(100, ("jas_stream_fdopen(%d, \"%s\")\n", fd, mode));
+
+	/* Allocate a stream object. */
+	if (!(stream = jas_stream_create())) {
+		return 0;
+	}
+
+	/* Parse the mode string. */
+	stream->openmode_ = jas_strtoopenmode(mode);
+
+#if defined(WIN32)
+	/* Argh!!!  Someone ought to banish text mode (i.e., O_TEXT) to the
+	  greatest depths of purgatory! */
+	/* Ensure that the file descriptor is in binary mode, if the caller
+	  has specified the binary mode flag.  Arguably, the caller ought to
+	  take care of this, but text mode is a ugly wart anyways, so we save
+	  the caller some grief by handling this within the stream library. */
+	/* This ugliness is mainly for the benefit of those who run the
+	  JasPer software under Windows from shells that insist on opening
+	  files in text mode.  For example, in the Cygwin environment,
+	  shells often open files in text mode when I/O redirection is
+	  used.  Grr... */
+	if (stream->openmode_ & JAS_STREAM_BINARY) {
+		setmode(fd, O_BINARY);
+	}
+#endif
+
+	/* Allocate space for the underlying file stream object. */
+	if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) {
+		jas_stream_destroy(stream);
+		return 0;
+	}
+	obj->fd = fd;
+	obj->flags = 0;
+	obj->pathname[0] = '\0';
+	stream->obj_ = (void *) obj;
+
+	/* Do not close the underlying file descriptor when the stream is
+	closed. */
+	obj->flags |= JAS_STREAM_FILEOBJ_NOCLOSE;
+
+	/* By default, use full buffering for this type of stream. */
+	jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+
+	/* Select the operations for a file stream object. */
+	stream->ops_ = &jas_stream_fileops;
+
+	return stream;
+}
+
+static void jas_stream_destroy(jas_stream_t *stream)
+{
+	JAS_DBGLOG(100, ("jas_stream_destroy(%p)\n", stream));
+
+	/* If the memory for the buffer was allocated with malloc, free
+	this memory. */
+	if ((stream->bufmode_ & JAS_STREAM_FREEBUF) && stream->bufbase_) {
+		JAS_DBGLOG(100, ("jas_stream_destroy freeing buffer %p\n",
+		  stream->bufbase_));
+		jas_free(stream->bufbase_);
+		stream->bufbase_ = 0;
+	}
+	jas_free(stream);
+}
+
+int jas_stream_close(jas_stream_t *stream)
+{
+	JAS_DBGLOG(100, ("jas_stream_close(%p)\n", stream));
+
+	/* Flush buffer if necessary. */
+	jas_stream_flush(stream);
+
+	/* Close the underlying stream object. */
+	(*stream->ops_->close_)(stream->obj_);
+
+	jas_stream_destroy(stream);
+
+	return 0;
+}
+
+static bool jas_stream_is_unbuffered(const jas_stream_t *stream)
+{
+	return stream->bufsize_ <= 1;
+}
+
+static bool jas_stream_is_input_buffer_empty(const jas_stream_t *stream)
+{
+	return stream->cnt_ == 0;
+}
+
+/******************************************************************************\
+* Code for reading and writing streams.
+\******************************************************************************/
+
+int jas_stream_getc_func(jas_stream_t *stream)
+{
+	assert(stream->ptr_ - stream->bufbase_ <= stream->bufsize_ +
+	  JAS_STREAM_MAXPUTBACK);
+	return jas_stream_getc_macro(stream);
+}
+
+int jas_stream_putc_func(jas_stream_t *stream, int c)
+{
+	assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_);
+	return jas_stream_putc_macro(stream, c);
+}
+
+int jas_stream_ungetc(jas_stream_t *stream, int c)
+{
+	if (!stream->ptr_ || stream->ptr_ == stream->bufbase_) {
+		return -1;
+	}
+
+	/* Reset the EOF indicator (since we now have at least one character
+	  to read). */
+	stream->flags_ &= ~JAS_STREAM_EOF;
+
+	--stream->rwcnt_;
+	--stream->ptr_;
+	++stream->cnt_;
+	*stream->ptr_ = c;
+	return 0;
+}
+
+/* FIXME integral type */
+unsigned jas_stream_read(jas_stream_t *stream, void *buf, unsigned cnt)
+{
+	int c;
+	char *bufptr;
+
+	JAS_DBGLOG(100, ("jas_stream_read(%p, %p, %u)\n", stream, buf, cnt));
+
+	if (cnt == 0)
+		return 0;
+
+	bufptr = buf;
+
+	if (jas_stream_is_unbuffered(stream) && stream->rwlimit_ < 0 &&
+	    jas_stream_is_input_buffer_empty(stream)) {
+		/* fast path for unbuffered streams */
+
+		if ((stream->flags_ & JAS_STREAM_ERRMASK) != 0)
+			return 0;
+
+		if ((stream->openmode_ & JAS_STREAM_READ) == 0)
+			return 0;
+
+		assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0);
+
+		stream->bufmode_ |= JAS_STREAM_RDBUF;
+
+		int nbytes = stream->ops_->read_(stream->obj_, bufptr, cnt);
+		if (nbytes <= 0) {
+			stream->flags_ |= nbytes < 0
+				? JAS_STREAM_ERR
+				: JAS_STREAM_EOF;
+			return 0;
+		}
+
+		stream->rwcnt_ += nbytes;
+		return nbytes;
+	}
+
+	unsigned n = 0;
+	while (n < cnt) {
+		if ((c = jas_stream_getc(stream)) == EOF) {
+			return n;
+		}
+		*bufptr++ = c;
+		++n;
+	}
+
+	return n;
+}
+
+unsigned jas_stream_peek(jas_stream_t *stream, void *buf, size_t cnt)
+{
+	char *bufptr = buf;
+
+	const unsigned n = jas_stream_read(stream, bufptr, cnt);
+
+	/* Put the characters read back onto the stream. */
+	for (unsigned i = n; i-- > 0;)
+		if (jas_stream_ungetc(stream, bufptr[i]) == EOF)
+			return 0;
+
+	return n;
+}
+
+/* FIXME integral type */
+unsigned jas_stream_write(jas_stream_t *stream, const void *buf, unsigned cnt)
+{
+	const char *bufptr;
+
+	JAS_DBGLOG(100, ("jas_stream_write(%p, %p, %d)\n", stream, buf, cnt));
+
+	if (cnt == 0)
+		return 0;
+
+	bufptr = buf;
+
+	if (jas_stream_is_unbuffered(stream) && stream->rwlimit_ < 0) {
+		/* fast path for unbuffered streams */
+
+		/* need to flush the output buffer before we do a raw
+		   write */
+		if (jas_stream_flushbuf(stream, EOF))
+			return 0;
+
+		stream->bufmode_ |= JAS_STREAM_WRBUF;
+
+		int nbytes = stream->ops_->write_(stream->obj_, bufptr, cnt);
+		if (nbytes != (int)cnt) {
+			stream->flags_ |= JAS_STREAM_ERR;
+			return 0;
+		}
+
+		stream->rwcnt_ += nbytes;
+		return nbytes;
+	}
+
+	unsigned n = 0;
+	while (n < cnt) {
+		if (jas_stream_putc(stream, *bufptr) == EOF) {
+			return n;
+		}
+		++bufptr;
+		++n;
+	}
+
+	return n;
+}
+
+/* Note: This function uses a fixed size buffer.  Therefore, it cannot
+  handle invocations that will produce more output than can be held
+  by the buffer. */
+int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...)
+{
+	va_list ap;
+	char buf[4096];
+	int ret;
+
+	va_start(ap, fmt);
+	ret = vsnprintf(buf, sizeof buf, fmt, ap);
+	jas_stream_puts(stream, buf);
+	va_end(ap);
+	return ret;
+}
+
+int jas_stream_puts(jas_stream_t *stream, const char *s)
+{
+	while (*s != '\0') {
+		if (jas_stream_putc_macro(stream, *s) == EOF) {
+			return -1;
+		}
+		++s;
+	}
+	return 0;
+}
+
+/* TODO/FIXME: this function should return null upon error (buffer overrun or I/O error */
+/* FIXME integral type */
+char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize)
+{
+	int c;
+	char *bufptr;
+	assert(bufsize > 0);
+
+	JAS_DBGLOG(100, ("jas_stream_gets(%p, %p, %d)\n", stream, buf, bufsize));
+
+	bufptr = buf;
+	while (bufsize > 1) {
+		if ((c = jas_stream_getc(stream)) == EOF) {
+			break;
+		}
+		*bufptr++ = c;
+		--bufsize;
+		if (c == '\n') {
+			break;
+		}
+	}
+	*bufptr = '\0';
+	return buf;
+}
+
+/* FIXME integral type */
+int jas_stream_gobble(jas_stream_t *stream, int n)
+{
+	int m;
+
+	JAS_DBGLOG(100, ("jas_stream_gobble(%p, %d)\n", stream, n));
+
+	if (n < 0) {
+		jas_deprecated("negative count for jas_stream_gobble");
+	}
+	for (m = n; m > 0; --m) {
+		if (jas_stream_getc(stream) == EOF) {
+			return n - m;
+		}
+	}
+	return n;
+}
+
+/* FIXME integral type */
+int jas_stream_pad(jas_stream_t *stream, int n, int c)
+{
+	int m;
+
+	JAS_DBGLOG(100, ("jas_stream_pad(%p, %d, %d)\n", stream, n, c));
+
+	if (n < 0) {
+		jas_deprecated("negative count for jas_stream_pad");
+	}
+	for (m = n; m > 0; --m) {
+		if (jas_stream_putc(stream, c) == EOF)
+			return n - m;
+	}
+	return n;
+}
+
+/******************************************************************************\
+* Code for getting and setting the stream position.
+\******************************************************************************/
+
+int jas_stream_isseekable(jas_stream_t *stream)
+{
+	if (stream->ops_ == &jas_stream_memops) {
+		return 1;
+	} else if (stream->ops_ == &jas_stream_fileops) {
+		if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) {
+			return 0;
+		}
+		return 1;
+	} else {
+		return 0;
+	}
+}
+
+int jas_stream_rewind(jas_stream_t *stream)
+{
+	JAS_DBGLOG(100, ("jas_stream_rewind(%p)\n", stream));
+	return jas_stream_seek(stream, 0, SEEK_SET);
+}
+
+long jas_stream_seek(jas_stream_t *stream, long offset, int origin)
+{
+	long newpos;
+
+	JAS_DBGLOG(100, ("jas_stream_seek(%p, %ld, %d)\n", stream, offset,
+	  origin));
+
+	/* The buffer cannot be in use for both reading and writing. */
+	assert(!((stream->bufmode_ & JAS_STREAM_RDBUF) && (stream->bufmode_ &
+	  JAS_STREAM_WRBUF)));
+
+	/* Reset the EOF indicator (since we may not be at the EOF anymore). */
+	stream->flags_ &= ~JAS_STREAM_EOF;
+
+	if (stream->bufmode_ & JAS_STREAM_RDBUF) {
+		if (origin == SEEK_CUR) {
+			offset -= stream->cnt_;
+		}
+	} else if (stream->bufmode_ & JAS_STREAM_WRBUF) {
+		if (jas_stream_flush(stream)) {
+			return -1;
+		}
+	}
+	stream->cnt_ = 0;
+	stream->ptr_ = stream->bufstart_;
+	stream->bufmode_ &= ~(JAS_STREAM_RDBUF | JAS_STREAM_WRBUF);
+
+	if ((newpos = (*stream->ops_->seek_)(stream->obj_, offset, origin))
+	  < 0) {
+		return -1;
+	}
+
+	return newpos;
+}
+
+long jas_stream_tell(jas_stream_t *stream)
+{
+	int adjust;
+	int offset;
+
+	JAS_DBGLOG(100, ("jas_stream_tell(%p)\n", stream));
+
+	if (stream->bufmode_ & JAS_STREAM_RDBUF) {
+		adjust = -stream->cnt_;
+	} else if (stream->bufmode_ & JAS_STREAM_WRBUF) {
+		adjust = stream->ptr_ - stream->bufstart_;
+	} else {
+		adjust = 0;
+	}
+
+	if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR)) < 0) {
+		return -1;
+	}
+
+	return offset + adjust;
+}
+
+/******************************************************************************\
+* Buffer initialization code.
+\******************************************************************************/
+
+/* FIXME integral type */
+static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
+  int bufsize)
+{
+	/* If this function is being called, the buffer should not have been
+	  initialized yet. */
+	assert(!stream->bufbase_);
+
+	if (bufmode != JAS_STREAM_UNBUF) {
+		/* The full- or line-buffered mode is being employed. */
+		if (!buf) {
+			/* The caller has not specified a buffer to employ, so allocate
+			  one. */
+			if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE +
+			  JAS_STREAM_MAXPUTBACK))) {
+				stream->bufmode_ |= JAS_STREAM_FREEBUF;
+				stream->bufsize_ = JAS_STREAM_BUFSIZE;
+			} else {
+				/* The buffer allocation has failed.  Resort to unbuffered
+				  operation. */
+				stream->bufbase_ = stream->tinybuf_;
+				stream->bufsize_ = 1;
+			}
+		} else {
+			/* The caller has specified a buffer to employ. */
+			/* The buffer must be large enough to accommodate maximum
+			  putback. */
+			assert(bufsize > JAS_STREAM_MAXPUTBACK);
+			stream->bufbase_ = JAS_CAST(jas_uchar *, buf);
+			stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
+		}
+	} else {
+		/* The unbuffered mode is being employed. */
+		/* A buffer should not have been supplied by the caller. */
+		assert(!buf);
+		/* Use a trivial one-character buffer. */
+		stream->bufbase_ = stream->tinybuf_;
+		stream->bufsize_ = 1;
+	}
+	stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
+	stream->ptr_ = stream->bufstart_;
+	stream->cnt_ = 0;
+	stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
+}
+
+/******************************************************************************\
+* Buffer filling and flushing code.
+\******************************************************************************/
+
+int jas_stream_flush(jas_stream_t *stream)
+{
+	if (stream->bufmode_ & JAS_STREAM_RDBUF) {
+		return 0;
+	}
+	return jas_stream_flushbuf(stream, EOF);
+}
+
+int jas_stream_fillbuf(jas_stream_t *stream, int getflag)
+{
+	int c;
+
+	/* The stream must not be in an error or EOF state. */
+	if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) {
+		return EOF;
+	}
+
+	/* The stream must be open for reading. */
+	if ((stream->openmode_ & JAS_STREAM_READ) == 0) {
+		return EOF;
+	}
+
+	/* Make a half-hearted attempt to confirm that the buffer is not
+	currently being used for writing.  This check is not intended
+	to be foolproof! */
+	assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0);
+
+	assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_);
+
+	/* Mark the buffer as being used for reading. */
+	stream->bufmode_ |= JAS_STREAM_RDBUF;
+
+	/* Read new data into the buffer. */
+	stream->ptr_ = stream->bufstart_;
+	if ((stream->cnt_ = (*stream->ops_->read_)(stream->obj_,
+	  (char *) stream->bufstart_, stream->bufsize_)) <= 0) {
+		if (stream->cnt_ < 0) {
+			stream->flags_ |= JAS_STREAM_ERR;
+		} else {
+			stream->flags_ |= JAS_STREAM_EOF;
+		}
+		stream->cnt_ = 0;
+		return EOF;
+	}
+
+	assert(stream->cnt_ > 0);
+	/* Get or peek at the first character in the buffer. */
+	c = (getflag) ? jas_stream_getc2(stream) : (*stream->ptr_);
+
+	return c;
+}
+
+int jas_stream_flushbuf(jas_stream_t *stream, int c)
+{
+	int len;
+	int n;
+
+	/* The stream should not be in an error or EOF state. */
+	if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) {
+		return EOF;
+	}
+
+	/* The stream must be open for writing. */
+	if ((stream->openmode_ & (JAS_STREAM_WRITE | JAS_STREAM_APPEND)) == 0) {
+		return EOF;
+	}
+
+	/* The buffer should not currently be in use for reading. */
+	assert(!(stream->bufmode_ & JAS_STREAM_RDBUF));
+
+	/* Note: Do not use the quantity stream->cnt to determine the number
+	of characters in the buffer!  Depending on how this function was
+	called, the stream->cnt value may be "off-by-one". */
+	len = stream->ptr_ - stream->bufstart_;
+	if (len > 0) {
+		n = (*stream->ops_->write_)(stream->obj_, (char *)
+		  stream->bufstart_, len);
+		if (n != len) {
+			stream->flags_ |= JAS_STREAM_ERR;
+			return EOF;
+		}
+	}
+	stream->cnt_ = stream->bufsize_;
+	stream->ptr_ = stream->bufstart_;
+
+	stream->bufmode_ |= JAS_STREAM_WRBUF;
+
+	if (c != EOF) {
+		assert(stream->cnt_ > 0);
+		return jas_stream_putc2(stream, c);
+	}
+
+	return 0;
+}
+
+/******************************************************************************\
+* Miscellaneous code.
+\******************************************************************************/
+
+static int jas_strtoopenmode(const char *s)
+{
+	int openmode = 0;
+	while (*s != '\0') {
+		switch (*s) {
+		case 'r':
+			openmode |= JAS_STREAM_READ;
+			break;
+		case 'w':
+			openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE;
+			break;
+		case 'b':
+			openmode |= JAS_STREAM_BINARY;
+			break;
+		case 'a':
+			openmode |= JAS_STREAM_APPEND;
+			break;
+		case '+':
+			openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE;
+			break;
+		default:
+			break;
+		}
+		++s;
+	}
+	return openmode;
+}
+
+/* FIXME integral type */
+int jas_stream_copy(jas_stream_t *out, jas_stream_t *in, int n)
+{
+	int m;
+
+	const bool all = n < 0;
+
+	char buffer[JAS_STREAM_BUFSIZE];
+
+	m = n;
+	while (all || m > 0) {
+		unsigned nbytes = jas_stream_read(in, buffer,
+						  JAS_MIN((size_t)m, sizeof(buffer)));
+		if (nbytes == 0)
+			return !all || jas_stream_error(in) ? -1 : 0;
+
+		if (jas_stream_write(out, buffer, nbytes) != nbytes)
+			return -1;
+
+		m -= nbytes;
+	}
+
+	return 0;
+}
+
+/* FIXME integral type */
+long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt)
+{
+	int old;
+
+	old = stream->rwcnt_;
+	stream->rwcnt_ = rwcnt;
+	return old;
+}
+
+JAS_DLLEXPORT
+long jas_stream_setrwlimit(jas_stream_t *stream, long rwlimit)
+{
+	long old;
+
+	old = stream->rwlimit_;
+	stream->rwlimit_ = rwlimit;
+	return old;
+}
+
+/* FIXME integral type */
+int jas_stream_display(jas_stream_t *stream, FILE *fp, int n)
+{
+	unsigned char buf[16];
+	int i;
+	int j;
+	int m;
+	int c;
+	int display;
+	int cnt;
+
+	cnt = n - (n % 16);
+	display = 1;
+
+	for (i = 0; i < n; i += 16) {
+		if (n > 16 && i > 0) {
+			display = (i >= cnt) ? 1 : 0;
+		}
+		if (display) {
+			fprintf(fp, "%08x:", i);
+		}
+		m = JAS_MIN(n - i, 16);
+		for (j = 0; j < m; ++j) {
+			if ((c = jas_stream_getc(stream)) == EOF) {
+				abort();
+				return -1;
+			}
+			buf[j] = c;
+		}
+		if (display) {
+			for (j = 0; j < m; ++j) {
+				fprintf(fp, " %02x", buf[j]);
+			}
+			fputc(' ', fp);
+			for (; j < 16; ++j) {
+				fprintf(fp, "   ");
+			}
+			for (j = 0; j < m; ++j) {
+				if (isprint(buf[j])) {
+					fputc(buf[j], fp);
+				} else {
+					fputc(' ', fp);
+				}
+			}
+			fprintf(fp, "\n");
+		}
+
+
+	}
+	return 0;
+}
+
+long jas_stream_length(jas_stream_t *stream)
+{
+	long oldpos;
+	long pos;
+	if ((oldpos = jas_stream_tell(stream)) < 0) {
+		return -1;
+	}
+	if (jas_stream_seek(stream, 0, SEEK_END) < 0) {
+		return -1;
+	}
+	if ((pos = jas_stream_tell(stream)) < 0) {
+		return -1;
+	}
+	if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) {
+		return -1;
+	}
+	return pos;
+}
+
+/******************************************************************************\
+* Memory stream object.
+\******************************************************************************/
+
+/* FIXME integral type */
+static int mem_read(jas_stream_obj_t *obj, char *buf, unsigned cnt)
+{
+	jas_stream_memobj_t *m;
+	assert(buf);
+
+	JAS_DBGLOG(100, ("mem_read(%p, %p, %u)\n", obj, buf, cnt));
+	m = (jas_stream_memobj_t *)obj;
+	size_t n = m->len_ - m->pos_;
+	cnt = JAS_MIN(n, cnt);
+	memcpy(buf, &m->buf_[m->pos_], cnt);
+	m->pos_ += cnt;
+	return cnt;
+}
+
+static int mem_resize(jas_stream_memobj_t *m, size_t bufsize)
+{
+	unsigned char *buf;
+
+	//assert(m->buf_);
+
+	JAS_DBGLOG(100, ("mem_resize(%p, %zu)\n", m, bufsize));
+	if (!bufsize) {
+		jas_eprintf(
+		  "mem_resize was not really designed to handle a buffer of size 0\n"
+		  "This may not work.\n"
+		);
+	}
+
+	if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) &&
+	  bufsize) {
+		JAS_DBGLOG(100, ("mem_resize realloc failed\n"));
+		return -1;
+	}
+	JAS_DBGLOG(100, ("mem_resize realloc succeeded\n"));
+	m->buf_ = buf;
+	m->bufsize_ = bufsize;
+	return 0;
+}
+
+/* FIXME integral type */
+static int mem_write(jas_stream_obj_t *obj, const char *buf, unsigned cnt)
+{
+	size_t n;
+	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
+	size_t newbufsize;
+	size_t newpos;
+
+	assert(buf);
+
+	JAS_DBGLOG(100, ("mem_write(%p, %p, %u)\n", obj, buf, cnt));
+	newpos = m->pos_ + cnt;
+	if (newpos > m->bufsize_ && m->growable_) {
+		newbufsize = m->bufsize_;
+		while (newbufsize < newpos) {
+			//newbufsize <<= 1;
+			if (!jas_safe_size_mul(newbufsize, 2, &newbufsize)) {
+				JAS_DBGLOG(100, ("new buffer size would cause overflow\n"));
+				return -1;
+			}
+		}
+		JAS_DBGLOG(100, ("mem_write resizing from %d to %zu\n", m->bufsize_,
+		  newbufsize));
+		assert(newbufsize > 0);
+		if (mem_resize(m, newbufsize)) {
+			return -1;
+		}
+	}
+	if (m->pos_ > m->len_) {
+		/* The current position is beyond the end of the file, so
+		  pad the file to the current position with zeros. */
+		n = JAS_MIN(m->pos_, m->bufsize_) - m->len_;
+		if (n > 0) {
+			memset(&m->buf_[m->len_], 0, n);
+			m->len_ += n;
+		}
+		if (m->pos_ != m->len_) {
+			/* The buffer is not big enough. */
+			return 0;
+		}
+	}
+	n = m->bufsize_ - m->pos_;
+	unsigned ret = JAS_MIN(n, cnt);
+	if (ret > 0) {
+		memcpy(&m->buf_[m->pos_], buf, ret);
+		m->pos_ += ret;
+	}
+	if (m->pos_ > m->len_) {
+		m->len_ = m->pos_;
+	}
+	assert(ret == cnt);
+	return ret;
+}
+
+/* FIXME integral type */
+static long mem_seek(jas_stream_obj_t *obj, long offset, int origin)
+{
+	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
+	long newpos;
+
+	JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin));
+	switch (origin) {
+	case SEEK_SET:
+		newpos = offset;
+		break;
+	case SEEK_END:
+		newpos = m->len_ - offset;
+		break;
+	case SEEK_CUR:
+		newpos = m->pos_ + offset;
+		break;
+	default:
+		return -1;
+	}
+	if (newpos < 0) {
+		return -1;
+	}
+	m->pos_ = newpos;
+
+	return m->pos_;
+}
+
+static int mem_close(jas_stream_obj_t *obj)
+{
+	jas_stream_memobj_t *m;
+
+	JAS_DBGLOG(100, ("mem_close(%p)\n", obj));
+	m = (jas_stream_memobj_t *)obj;
+	JAS_DBGLOG(100, ("mem_close myalloc=%d\n", m->myalloc_));
+	if (m->myalloc_ && m->buf_) {
+		JAS_DBGLOG(100, ("mem_close freeing buffer %p\n", m->buf_));
+		jas_free(m->buf_);
+		m->buf_ = 0;
+	}
+	jas_free(obj);
+	return 0;
+}
+
+/******************************************************************************\
+* File stream object.
+\******************************************************************************/
+
+/* FIXME integral type */
+static int file_read(jas_stream_obj_t *obj, char *buf, unsigned cnt)
+{
+	jas_stream_fileobj_t *fileobj;
+	JAS_DBGLOG(100, ("file_read(%p, %p, %u)\n", obj, buf, cnt));
+	fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
+	return read(fileobj->fd, buf, cnt);
+}
+
+/* FIXME integral type */
+static int file_write(jas_stream_obj_t *obj, const char *buf, unsigned cnt)
+{
+	jas_stream_fileobj_t *fileobj;
+	JAS_DBGLOG(100, ("file_write(%p, %p, %u)\n", obj, buf, cnt));
+	fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
+	return write(fileobj->fd, buf, cnt);
+}
+
+/* FIXME integral type */
+static long file_seek(jas_stream_obj_t *obj, long offset, int origin)
+{
+	jas_stream_fileobj_t *fileobj;
+	JAS_DBGLOG(100, ("file_seek(%p, %ld, %d)\n", obj, offset, origin));
+	fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
+	return seek(fileobj->fd, offset, origin);
+}
+
+static int file_close(jas_stream_obj_t *obj)
+{
+	int ret;
+	jas_stream_fileobj_t *fileobj;
+	JAS_DBGLOG(100, ("file_close(%p)\n", obj));
+	fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
+	ret = close(fileobj->fd);
+	if (fileobj->flags & JAS_STREAM_FILEOBJ_DELONCLOSE) {
+		remove(fileobj->pathname);
+	}
+	jas_free(fileobj);
+	return ret;
+}
+
+/******************************************************************************\
+* Stdio file stream object.
+\******************************************************************************/
+
+/* FIXME integral type */
+static int sfile_read(jas_stream_obj_t *obj, char *buf, unsigned cnt)
+{
+	FILE *fp;
+	size_t n;
+	int result;
+	JAS_DBGLOG(100, ("sfile_read(%p, %p, %u)\n", obj, buf, cnt));
+	fp = JAS_CAST(FILE *, obj);
+	n = fread(buf, 1, cnt, fp);
+	if (n != cnt) {
+		result = (!ferror(fp) && feof(fp)) ? 0 : -1;
+		if(result != 0) {
+			return result;
+		}
+	}
+	result = JAS_CAST(int, n);
+	return result;
+}
+
+/* FIXME integral type */
+static int sfile_write(jas_stream_obj_t *obj, const char *buf, unsigned cnt)
+{
+	FILE *fp;
+	size_t n;
+	JAS_DBGLOG(100, ("sfile_write(%p, %p, %d)\n", obj, buf, cnt));
+	fp = JAS_CAST(FILE *, obj);
+	n = fwrite(buf, 1, cnt, fp);
+	return (n != cnt) ? (-1) : (int)cnt;
+}
+
+/* FIXME integral type */
+static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin)
+{
+	FILE *fp;
+	JAS_DBGLOG(100, ("sfile_seek(%p, %ld, %d)\n", obj, offset, origin));
+	fp = JAS_CAST(FILE *, obj);
+	return fseek(fp, offset, origin);
+}
+
+static int sfile_close(jas_stream_obj_t *obj)
+{
+	FILE *fp;
+	JAS_DBGLOG(100, ("sfile_close(%p)\n", obj));
+	fp = JAS_CAST(FILE *, obj);
+	return fclose(fp);
+}
--- /dev/null
+++ b/jas_string.c
@@ -1,0 +1,94 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * String Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include "jasper/jas_string.h"
+#include "jasper/jas_malloc.h"
+
+/******************************************************************************\
+* Miscellaneous Functions
+\******************************************************************************/
+
+/* This function is equivalent to the popular but non-standard (and
+  not-always-available) strdup function. */
+
+char *jas_strdup(const char *s)
+{
+	size_t n;
+	char *p;
+	n = strlen(s) + 1;
+	if (!(p = jas_malloc(n))) {
+		return 0;
+	}
+	strcpy(p, s);
+	return p;
+}
--- /dev/null
+++ b/jasper/jas_cm.h
@@ -1,0 +1,272 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_cm.h
+ * @brief JasPer Color Management
+ */
+
+#ifndef JAS_CM_H
+#define JAS_CM_H
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#include <jasper/jas_icc.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef unsigned jas_clrspc_t;
+
+/* transform operations */
+typedef enum {
+	JAS_CMXFORM_OP_FWD = 0,
+	JAS_CMXFORM_OP_REV = 1,
+	JAS_CMXFORM_OP_PROOF = 2,
+	JAS_CMXFORM_OP_GAMUT = 3,
+} jas_cmxform_op_t;
+
+/* rendering intents */
+typedef enum {
+	JAS_CMXFORM_INTENT_PER = 0,
+	JAS_CMXFORM_INTENT_RELCLR = 1,
+	JAS_CMXFORM_INTENT_ABSCLR = 2,
+	JAS_CMXFORM_INTENT_SAT = 3,
+} jas_cmxform_intent_t;
+
+#define	JAS_CMXFORM_NUMINTENTS		4
+
+typedef enum {
+	JAS_CMXFORM_OPTM_SPEED = 0,
+	JAS_CMXFORM_OPTM_SIZE = 1,
+	JAS_CMXFORM_OPTM_ACC = 2,
+} jas_cmxform_optm_t;
+
+
+#define	jas_clrspc_create(fam, mbr)	(((fam) << 8) | (mbr))
+#define	jas_clrspc_fam(clrspc)	((clrspc) >> 8)
+#define	jas_clrspc_mbr(clrspc)	((clrspc) & 0xff)
+#define	jas_clrspc_isgeneric(clrspc)	(!jas_clrspc_mbr(clrspc))
+#define	jas_clrspc_isunknown(clrspc)	((clrspc) & JAS_CLRSPC_UNKNOWNMASK)
+
+#define	JAS_CLRSPC_UNKNOWNMASK	0x4000
+
+/* color space families */
+#define	JAS_CLRSPC_FAM_UNKNOWN	0
+#define	JAS_CLRSPC_FAM_XYZ	1
+#define	JAS_CLRSPC_FAM_LAB	2
+#define	JAS_CLRSPC_FAM_GRAY	3
+#define	JAS_CLRSPC_FAM_RGB	4
+#define	JAS_CLRSPC_FAM_YCBCR	5
+
+/* specific color spaces */
+#define	JAS_CLRSPC_UNKNOWN	JAS_CLRSPC_UNKNOWNMASK
+#define	JAS_CLRSPC_CIEXYZ	jas_clrspc_create(JAS_CLRSPC_FAM_XYZ, 1)
+#define	JAS_CLRSPC_CIELAB	jas_clrspc_create(JAS_CLRSPC_FAM_LAB, 1)
+#define	JAS_CLRSPC_SGRAY	jas_clrspc_create(JAS_CLRSPC_FAM_GRAY, 1)
+#define	JAS_CLRSPC_SRGB		jas_clrspc_create(JAS_CLRSPC_FAM_RGB, 1)
+#define	JAS_CLRSPC_SYCBCR	jas_clrspc_create(JAS_CLRSPC_FAM_YCBCR, 1)
+
+/* generic color spaces */
+#define	JAS_CLRSPC_GENRGB	jas_clrspc_create(JAS_CLRSPC_FAM_RGB, 0)
+#define	JAS_CLRSPC_GENGRAY	jas_clrspc_create(JAS_CLRSPC_FAM_GRAY, 0)
+#define	JAS_CLRSPC_GENYCBCR	jas_clrspc_create(JAS_CLRSPC_FAM_YCBCR, 0)
+
+#define	JAS_CLRSPC_CHANIND_YCBCR_Y	0
+#define	JAS_CLRSPC_CHANIND_YCBCR_CB	1
+#define	JAS_CLRSPC_CHANIND_YCBCR_CR	2
+
+#define	JAS_CLRSPC_CHANIND_RGB_R	0
+#define	JAS_CLRSPC_CHANIND_RGB_G	1
+#define	JAS_CLRSPC_CHANIND_RGB_B	2
+
+#define	JAS_CLRSPC_CHANIND_GRAY_Y	0
+
+typedef double jas_cmreal_t;
+
+struct jas_cmpxform_s;
+
+typedef struct {
+	long *buf;
+	unsigned prec;
+	int sgnd;
+	unsigned width;
+	unsigned height;
+} jas_cmcmptfmt_t;
+
+typedef struct {
+	unsigned numcmpts;
+	jas_cmcmptfmt_t *cmptfmts;
+} jas_cmpixmap_t;
+
+typedef struct {
+	void (*destroy)(struct jas_cmpxform_s *pxform);
+	int (*apply)(const struct jas_cmpxform_s *pxform, const jas_cmreal_t *in, jas_cmreal_t *out, unsigned  cnt);
+	void (*dump)(struct jas_cmpxform_s *pxform);
+} jas_cmpxformops_t;
+
+typedef struct {
+	jas_cmreal_t *data;
+	unsigned size;
+} jas_cmshapmatlut_t;
+
+typedef struct {
+	int mono;
+	int order;
+	int useluts;
+	int usemat;
+	jas_cmshapmatlut_t luts[3];
+	jas_cmreal_t mat[3][4];
+} jas_cmshapmat_t;
+
+typedef struct {
+	int order;
+} jas_cmshaplut_t;
+
+typedef struct {
+	unsigned inclrspc;
+	unsigned outclrspc;
+} jas_cmclrspcconv_t;
+
+#define	jas_align_t	double
+
+typedef struct jas_cmpxform_s {
+	unsigned refcnt;
+	const jas_cmpxformops_t *ops;
+	unsigned numinchans;
+	unsigned numoutchans;
+	union {
+		jas_align_t dummy;
+		jas_cmshapmat_t shapmat;
+		jas_cmshaplut_t shaplut;
+		jas_cmclrspcconv_t clrspcconv;
+	} data;
+} jas_cmpxform_t;
+
+typedef struct {
+	unsigned numpxforms;
+	unsigned maxpxforms;
+	jas_cmpxform_t **pxforms;
+} jas_cmpxformseq_t;
+
+typedef struct {
+	unsigned numinchans;
+	unsigned numoutchans;
+	jas_cmpxformseq_t *pxformseq;
+} jas_cmxform_t;
+
+#define	JAS_CMPROF_TYPE_DEV	1
+#define	JAS_CMPROF_TYPE_CLRSPC	2
+
+#define	JAS_CMPROF_NUMPXFORMSEQS	13
+
+typedef struct {
+	jas_clrspc_t clrspc;
+	unsigned numchans;
+	unsigned refclrspc;
+	unsigned numrefchans;
+	jas_iccprof_t *iccprof;
+	jas_cmpxformseq_t *pxformseqs[JAS_CMPROF_NUMPXFORMSEQS];
+} jas_cmprof_t;
+
+#if 0
+typedef int_fast32_t jas_cmattrname_t;
+typedef int_fast32_t jas_cmattrval_t;
+typedef int_fast32_t jas_cmattrtype_t;
+/* Load a profile. */
+int jas_cmprof_load(jas_cmprof_t *prof, jas_stream_t *in, unsigned fmt);
+/* Save a profile. */
+int jas_cmprof_save(jas_cmprof_t *prof, jas_stream_t *out, unsigned fmt);
+/* Set an attribute of a profile. */
+int jas_cm_prof_setattr(jas_cm_prof_t *prof, jas_cm_attrname_t name, void *val);
+/* Get an attribute of a profile. */
+void *jas_cm_prof_getattr(jas_cm_prof_t *prof, jas_cm_attrname_t name);
+#endif
+
+JAS_DLLEXPORT jas_cmxform_t *jas_cmxform_create(const jas_cmprof_t *inprof, const jas_cmprof_t *outprof,
+  const jas_cmprof_t *proofprof, jas_cmxform_op_t op, jas_cmxform_intent_t intent, jas_cmxform_optm_t optimize);
+
+JAS_DLLEXPORT void jas_cmxform_destroy(jas_cmxform_t *xform);
+
+/* Apply a transform to data. */
+JAS_DLLEXPORT int jas_cmxform_apply(const jas_cmxform_t *xform, const jas_cmpixmap_t *in,
+  jas_cmpixmap_t *out);
+
+/* Create a profile. */
+JAS_DLLEXPORT jas_cmprof_t *jas_cmprof_createfromiccprof(const jas_iccprof_t *iccprof);
+JAS_DLLEXPORT jas_cmprof_t *jas_cmprof_createfromclrspc(jas_clrspc_t clrspc);
+
+/* Destroy a profile. */
+JAS_DLLEXPORT void jas_cmprof_destroy(jas_cmprof_t *prof);
+
+unsigned jas_clrspc_numchans(jas_clrspc_t clrspc);
+JAS_DLLEXPORT jas_iccprof_t *jas_iccprof_createfromcmprof(const jas_cmprof_t *prof);
+
+#define	jas_cmprof_clrspc(prof) ((prof)->clrspc)
+JAS_DLLEXPORT jas_cmprof_t *jas_cmprof_copy(const jas_cmprof_t *prof);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_compiler.h
@@ -1,0 +1,103 @@
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_compiler.h
+ * @brief Compiler-related macros.
+ */
+
+#ifndef JAS_COMPILER_H
+#define JAS_COMPILER_H
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#ifdef _MSC_VER
+#ifndef __cplusplus
+#undef inline
+#define inline __inline
+#endif
+#endif
+
+#ifdef __GNUC__
+#define JAS_DEPRECATED __attribute__((deprecated))
+#define JAS_ATTRIBUTE_CONST __attribute__((const))
+#define JAS_ATTRIBUTE_PURE __attribute__((pure))
+#define JAS_FORCE_INLINE inline __attribute__((always_inline))
+#define JAS_UNREACHABLE() __builtin_unreachable()
+#define JAS_LIKELY(x) __builtin_expect (!!(x), 1)
+#define JAS_UNLIKELY(x) __builtin_expect (!!(x), 0)
+#else
+#define JAS_DEPRECATED
+#define JAS_ATTRIBUTE_CONST
+#define JAS_ATTRIBUTE_PURE
+#define JAS_FORCE_INLINE inline
+#define JAS_UNREACHABLE()
+#define JAS_LIKELY(x) (x)
+#define JAS_UNLIKELY(x) (x)
+#endif
+
+#ifdef __clang__
+#define JAS_ATTRIBUTE_DISABLE_USAN \
+  __attribute__((no_sanitize("undefined")))
+#elif defined(__GNUC__) && __GNUC__ >= 6
+#define JAS_ATTRIBUTE_DISABLE_USAN \
+  __attribute__((no_sanitize_undefined))
+#else
+#define JAS_ATTRIBUTE_DISABLE_USAN
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_config.h
@@ -1,0 +1,20 @@
+#ifndef JAS_CONFIG_H
+#define JAS_CONFIG_H
+
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <jasper/jas_compiler.h>
+#include <jasper/jas_dll.h>
+
+#define	JAS_VERSION "plan9"
+#define JAS_ENABLE_32BIT 1
+#define JAS_INCLUDE_JP2_CODEC 1
+#define JAS_INCLUDE_JPC_CODEC 1
+#define JAS_DEC_DEFAULT_MAX_SAMPLES (64 * ((size_t) 1048576))
+#define NDEBUG
+
+typedef usize size_t;
+
+#endif
--- /dev/null
+++ b/jasper/jas_debug.h
@@ -1,0 +1,120 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_debug.h
+ * @brief JasPer Debugging-Related Functionality
+ */
+
+#ifndef JAS_DEBUG_H
+#define JAS_DEBUG_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Macros and functions.
+\******************************************************************************/
+
+/* Output debugging information to standard error provided that the debug
+  level is set sufficiently high. */
+#if !defined(NDEBUG)
+#define	JAS_DBGLOG(n, x) \
+	((jas_getdbglevel() >= (n)) ? (jas_eprintf x) : 0)
+#else
+#define	JAS_DBGLOG(n, x)
+#endif
+
+/* Get the library debug level. */
+JAS_ATTRIBUTE_CONST
+JAS_DLLEXPORT int jas_getdbglevel(void);
+
+/* Set the library debug level. */
+JAS_DLLEXPORT int jas_setdbglevel(int dbglevel);
+
+/* Perform formatted output to standard error. */
+JAS_DLLEXPORT int jas_eprintf(const char *fmt, ...);
+
+/* Dump memory to a stream. */
+JAS_DLLEXPORT int jas_memdump(FILE *out, const void *data, size_t len);
+
+/* Warn about use of deprecated functionality. */
+JAS_DLLEXPORT void jas_deprecated(const char *s);
+
+/* Convert to a string literal */
+#define JAS_STRINGIFY(x) #x
+
+/* Convert to a string literal after macro expansion */
+#define JAS_STRINGIFYX(x) JAS_STRINGIFY(x)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_dll.h
@@ -1,0 +1,93 @@
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_dll.h
+ * @brief Shared Library Macros
+ */
+
+#ifndef JAS_DLL_H
+#define JAS_DLL_H
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#if defined(JAS_DLL)
+	#if defined(_WIN32)
+		#if defined(JAS_BUILDING_DLL)
+			#define JAS_DLLEXPORT __declspec(dllexport)
+		#else
+			#define JAS_DLLEXPORT __declspec(dllimport)
+		#endif
+		#define JAS_DLLLOCAL
+	#elif defined(JAS_HAVE_VISIBILITY)
+		#if defined(JAS_BUILDING_DLL)
+			#define JAS_DLLEXPORT __attribute__ ((visibility("default")))
+			#define JAS_DLLLOCAL __attribute__ ((visibility("hidden")))
+		#else
+			#define JAS_DLLEXPORT
+			#define JAS_DLLLOCAL
+		#endif
+	#else
+		#define JAS_DLLEXPORT
+		#define JAS_DLLLOCAL
+	#endif
+#else
+	#define JAS_DLLEXPORT
+	#define JAS_DLLLOCAL
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_fix.h
@@ -1,0 +1,349 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_fix.h
+ * @brief JasPer Fixed-Point Number Class
+ */
+
+#ifndef JAS_FIX_H
+#define JAS_FIX_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h> /* IWYU pragma: keep */
+
+#include <jasper/jas_types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* The representation of the value zero. */
+#define	JAS_FIX_ZERO(fix_t, fracbits) \
+	JAS_INTTOFIX(fix_t, fracbits, 0)
+
+/* The representation of the value one. */
+#define	JAS_FIX_ONE(fix_t, fracbits) \
+	JAS_INTTOFIX(fix_t, fracbits, 1)
+
+/* The representation of the value one half. */
+#define	JAS_FIX_HALF(fix_t, fracbits) \
+	(JAS_CAST(fix_t, 1) << ((fracbits) - 1))
+
+/******************************************************************************\
+* Conversion operations.
+\******************************************************************************/
+
+/* Convert an int to a fixed-point number. */
+#define JAS_INTTOFIX(fix_t, fracbits, x) \
+	(JAS_CAST(fix_t, x) << (fracbits))
+
+/* Convert a fixed-point number to an int. */
+#define JAS_FIXTOINT(fix_t, fracbits, x) \
+	JAS_CAST(int, (x) >> (fracbits))
+
+/* Convert a fixed-point number to a double. */
+#define JAS_FIXTODBL(fix_t, fracbits, x) \
+	(JAS_CAST(double, x) / JAS_FIX_ONE(fix_t, fracbits))
+
+/* Convert a double to a fixed-point number. */
+#define JAS_DBLTOFIX(fix_t, fracbits, x) \
+	JAS_CAST(fix_t, ((x) * JAS_CAST(double, JAS_FIX_ONE(fix_t, fracbits))))
+
+/******************************************************************************\
+* Basic arithmetic operations.
+* All other arithmetic operations are synthesized from these basic operations.
+* There are three macros for each type of arithmetic operation.
+* One macro always performs overflow/underflow checking, one never performs
+* overflow/underflow checking, and one is generic with its behavior
+* depending on compile-time flags.
+* Only the generic macros should be invoked directly by application code.
+\******************************************************************************/
+
+/* Calculate the sum of two fixed-point numbers. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_ADD			JAS_FIX_ADD_FAST
+#else
+#define JAS_FIX_ADD			JAS_FIX_ADD_OFLOW
+#endif
+
+/* Calculate the sum of two fixed-point numbers without overflow checking. */
+#define	JAS_FIX_ADD_FAST(fix_t, fracbits, x, y)	((x) + (y))
+
+/* Calculate the sum of two fixed-point numbers with overflow checking. */
+#define	JAS_FIX_ADD_OFLOW(fix_t, fracbits, x, y) \
+	((x) >= 0) ? \
+	  (((y) >= 0) ? ((x) + (y) >= 0 || JAS_FIX_OFLOW(), (x) + (y)) : \
+	  ((x) + (y))) : \
+	  (((y) >= 0) ? ((x) + (y)) : ((x) + (y) < 0 || JAS_FIX_OFLOW(), \
+	  (x) + (y)))
+
+/* Calculate the product of two fixed-point numbers. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_MUL			JAS_FIX_MUL_FAST
+#else
+#define JAS_FIX_MUL			JAS_FIX_MUL_OFLOW
+#endif
+
+/* Calculate the product of two fixed-point numbers without overflow
+  checking. */
+#define	JAS_FIX_MUL_FAST(fix_t, fracbits, bigfix_t, x, y) \
+	JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y)) >> \
+	  (fracbits))
+
+/* Calculate the product of two fixed-point numbers with overflow
+  checking. */
+#define JAS_FIX_MUL_OFLOW(fix_t, fracbits, bigfix_t, x, y) \
+	((JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> (fracbits)) == \
+	  JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \
+	  (fracbits))) ? \
+	  JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \
+	  (fracbits))) : JAS_FIX_OFLOW())
+
+/* Calculate the product of a fixed-point number and an int. */
+#if !defined(DEBUG_OVERFLOW)
+#define	JAS_FIX_MULBYINT	JAS_FIX_MULBYINT_FAST
+#else
+#define	JAS_FIX_MULBYINT	JAS_FIX_MULBYINT_OFLOW
+#endif
+
+/* Calculate the product of a fixed-point number and an int without overflow
+  checking. */
+#define	JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y) \
+	JAS_CAST(fix_t, ((x) * (y)))
+
+/* Calculate the product of a fixed-point number and an int with overflow
+  checking. */
+#define	JAS_FIX_MULBYINT_OFLOW(fix_t, fracbits, x, y) \
+	JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y)
+
+/* Calculate the quotient of two fixed-point numbers. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_DIV			JAS_FIX_DIV_FAST
+#else
+#define JAS_FIX_DIV			JAS_FIX_DIV_UFLOW
+#endif
+
+/* Calculate the quotient of two fixed-point numbers without underflow
+  checking. */
+#define	JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y) \
+	JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) << (fracbits)) / (y))
+
+/* Calculate the quotient of two fixed-point numbers with underflow
+  checking. */
+#define JAS_FIX_DIV_UFLOW(fix_t, fracbits, bigfix_t, x, y) \
+	JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y)
+
+/* Negate a fixed-point number. */
+#if !defined(DEBUG_OVERFLOW)
+#define	JAS_FIX_NEG			JAS_FIX_NEG_FAST
+#else
+#define	JAS_FIX_NEG			JAS_FIX_NEG_OFLOW
+#endif
+
+/* Negate a fixed-point number without overflow checking. */
+#define	JAS_FIX_NEG_FAST(fix_t, fracbits, x) \
+	(-(x))
+
+/* Negate a fixed-point number with overflow checking. */
+/* Yes, overflow is actually possible for two's complement representations,
+  although highly unlikely to occur. */
+#define	JAS_FIX_NEG_OFLOW(fix_t, fracbits, x) \
+	(((x) < 0) ? (-(x) > 0 || JAS_FIX_OFLOW(), -(x)) : (-(x)))
+
+/* Perform an arithmetic shift left of a fixed-point number. */
+#if !defined(DEBUG_OVERFLOW)
+#define	JAS_FIX_ASL			JAS_FIX_ASL_FAST
+#else
+#define	JAS_FIX_ASL			JAS_FIX_ASL_OFLOW
+#endif
+
+/* Perform an arithmetic shift left of a fixed-point number without overflow
+  checking. */
+#define	JAS_FIX_ASL_FAST(fix_t, fracbits, x, n) \
+	((x) << (n))
+
+/* Perform an arithmetic shift left of a fixed-point number with overflow
+  checking. */
+#define	JAS_FIX_ASL_OFLOW(fix_t, fracbits, x, n) \
+	((((x) << (n)) >> (n)) == (x) || JAS_FIX_OFLOW(), (x) << (n))
+
+/* Perform an arithmetic shift right of a fixed-point number. */
+#if !defined(DEBUG_OVERFLOW)
+#define	JAS_FIX_ASR			JAS_FIX_ASR_FAST
+#else
+#define	JAS_FIX_ASR			JAS_FIX_ASR_UFLOW
+#endif
+
+/* Perform an arithmetic shift right of a fixed-point number without underflow
+  checking. */
+#define	JAS_FIX_ASR_FAST(fix_t, fracbits, x, n) \
+	((x) >> (n))
+
+/* Perform an arithmetic shift right of a fixed-point number with underflow
+  checking. */
+#define	JAS_FIX_ASR_UFLOW(fix_t, fracbits, x, n) \
+	JAS_FIX_ASR_FAST(fix_t, fracbits, x, n)
+
+/******************************************************************************\
+* Other basic arithmetic operations.
+\******************************************************************************/
+
+/* Calculate the difference between two fixed-point numbers. */
+#define JAS_FIX_SUB(fix_t, fracbits, x, y) \
+	JAS_FIX_ADD(fix_t, fracbits, x, JAS_FIX_NEG(fix_t, fracbits, y))
+
+/* Add one fixed-point number to another. */
+#define JAS_FIX_PLUSEQ(fix_t, fracbits, x, y) \
+	((x) = JAS_FIX_ADD(fix_t, fracbits, x, y))
+
+/* Subtract one fixed-point number from another. */
+#define JAS_FIX_MINUSEQ(fix_t, fracbits, x, y) \
+	((x) = JAS_FIX_SUB(fix_t, fracbits, x, y))
+
+/* Multiply one fixed-point number by another. */
+#define	JAS_FIX_MULEQ(fix_t, fracbits, bigfix_t, x, y) \
+	((x) = JAS_FIX_MUL(fix_t, fracbits, bigfix_t, x, y))
+
+/******************************************************************************\
+* Miscellaneous operations.
+\******************************************************************************/
+
+/* Calculate the absolute value of a fixed-point number. */
+#define	JAS_FIX_ABS(fix_t, fracbits, x) \
+	(((x) >= 0) ? (x) : (JAS_FIX_NEG(fix_t, fracbits, x)))
+
+/* Is a fixed-point number an integer? */
+#define	JAS_FIX_ISINT(fix_t, fracbits, x) \
+	(JAS_FIX_FLOOR(fix_t, fracbits, x) == (x))
+
+/* Get the sign of a fixed-point number. */
+#define JAS_FIX_SGN(fix_t, fracbits, x) \
+	((x) >= 0 ? 1 : (-1))
+
+/******************************************************************************\
+* Relational operations.
+\******************************************************************************/
+
+/* Compare two fixed-point numbers. */
+#define JAS_FIX_CMP(fix_t, fracbits, x, y) \
+	((x) > (y) ? 1 : (((x) == (y)) ? 0 : (-1)))
+
+/* Less than. */
+#define	JAS_FIX_LT(fix_t, fracbits, x, y) \
+	((x) < (y))
+
+/* Less than or equal. */
+#define	JAS_FIX_LTE(fix_t, fracbits, x, y) \
+	((x) <= (y))
+
+/* Greater than. */
+#define	JAS_FIX_GT(fix_t, fracbits, x, y) \
+	((x) > (y))
+
+/* Greater than or equal. */
+#define	JAS_FIX_GTE(fix_t, fracbits, x, y) \
+	((x) >= (y))
+
+/******************************************************************************\
+* Rounding functions.
+\******************************************************************************/
+
+/* Round a fixed-point number to the nearest integer. */
+#define	JAS_FIX_ROUND(fix_t, fracbits, x) \
+	(((x) < 0) ? JAS_FIX_FLOOR(fix_t, fracbits, JAS_FIX_ADD(fix_t, fracbits, \
+	  (x), JAS_FIX_HALF(fix_t, fracbits))) : \
+	  JAS_FIX_NEG(fix_t, fracbits, JAS_FIX_FLOOR(fix_t, fracbits, \
+	  JAS_FIX_ADD(fix_t, fracbits, (-(x)), JAS_FIX_HALF(fix_t, fracbits)))))
+
+/* Round a fixed-point number to the nearest integer in the direction of
+  negative infinity (i.e., the floor function). */
+#define	JAS_FIX_FLOOR(fix_t, fracbits, x) \
+	((x) & (~(JAS_FIX_ONE(fix_t, fracbits) - 1)))
+
+/******************************************************************************\
+* The below macros are for internal library use only.  Do not invoke them
+* directly in application code.
+\******************************************************************************/
+
+/* Handle overflow. */
+#define	JAS_FIX_OFLOW() \
+	jas_eprintf("overflow error: file %s, line %d\n", __FILE__, __LINE__)
+
+/* Handle underflow. */
+#define	JAS_FIX_UFLOW() \
+	jas_eprintf("underflow error: file %s, line %d\n", __FILE__, __LINE__)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_icc.h
@@ -1,0 +1,417 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_icc.h
+ * @brief ICC Profile
+ */
+
+#ifndef JAS_ICC_H
+#define	JAS_ICC_H
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#include <jasper/jas_types.h>
+#include <jasper/jas_stream.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Profile file signature. */
+#define	JAS_ICC_MAGIC		0x61637370
+
+#define	JAS_ICC_HDRLEN	128
+
+/* Profile/device class signatures. */
+#define	JAS_ICC_CLAS_IN	0x73636e72 /* input device */
+#define	JAS_ICC_CLAS_DPY	0x6d6e7472 /* display device */
+#define	JAS_ICC_CLAS_OUT	0x70727472 /* output device */
+#define	JAS_ICC_CLAS_LNK	0x6c696e6b /* device link */
+#define	JAS_ICC_CLAS_CNV	0x73706163 /* color space conversion */
+#define	JAS_ICC_CLAS_ABS	0x61627374 /* abstract */
+#define	JAS_ICC_CLAS_NAM	0x6e6d636c /* named color */
+
+/* Color space signatures. */
+#define	JAS_ICC_COLORSPC_XYZ	0x58595a20 /* XYZ */
+#define	JAS_ICC_COLORSPC_LAB	0x4c616220 /* LAB */
+#define	JAS_ICC_COLORSPC_LUV	0x4c757620 /* LUV */
+#define	JAS_ICC_COLORSPC_YCBCR	0x59436272 /* YCbCr */
+#define	JAS_ICC_COLORSPC_YXY	0x59787920 /* Yxy */
+#define	JAS_ICC_COLORSPC_RGB	0x52474220 /* RGB */
+#define	JAS_ICC_COLORSPC_GRAY	0x47524159 /* Gray */
+#define	JAS_ICC_COLORSPC_HSV	0x48535620 /* HSV */
+#define	JAS_ICC_COLORSPC_HLS	0x484c5320 /* HLS */
+#define	JAS_ICC_COLORSPC_CMYK	0x434d594b /* CMYK */
+#define	JAS_ICC_COLORSPC_CMY	0x434d5920 /* CMY */
+#define	JAS_ICC_COLORSPC_2	0x32434c52 /* 2 channel color */
+#define	JAS_ICC_COLORSPC_3	0x33434c52 /* 3 channel color */
+#define	JAS_ICC_COLORSPC_4	0x34434c52 /* 4 channel color */
+#define	JAS_ICC_COLORSPC_5	0x35434c52 /* 5 channel color */
+#define	JAS_ICC_COLORSPC_6	0x36434c52 /* 6 channel color */
+#define	JAS_ICC_COLORSPC_7	0x37434c52 /* 7 channel color */
+#define	JAS_ICC_COLORSPC_8	0x38434c52 /* 8 channel color */
+#define	JAS_ICC_COLORSPC_9	0x39434c52 /* 9 channel color */
+#define	JAS_ICC_COLORSPC_10	0x41434c52 /* 10 channel color */
+#define	JAS_ICC_COLORSPC_11	0x42434c52 /* 11 channel color */
+#define	JAS_ICC_COLORSPC_12	0x43434c52 /* 12 channel color */
+#define	JAS_ICC_COLORSPC_13	0x44434c52 /* 13 channel color */
+#define	JAS_ICC_COLORSPC_14	0x45434c52 /* 14 channel color */
+#define	JAS_ICC_COLORSPC_15	0x46434c52 /* 15 channel color */
+
+/* Profile connection color space (PCS) signatures. */
+#define	JAS_ICC_REFCOLORSPC_XYZ		0x58595a20 /* CIE XYZ */
+#define	JAS_ICC_REFCOLORSPC_LAB		0x4c616220 /* CIE Lab */
+
+/* Primary platform signatures. */
+#define	JAS_ICC_PLATFORM_APPL	0x4150504c /* Apple Computer */
+#define	JAS_ICC_PLATFORM_MSFT	0x4d534654 /* Microsoft */
+#define	JAS_ICC_PLATFORM_SGI	0x53474920 /* Silicon Graphics */
+#define	JAS_ICC_PLATFORM_SUNW	0x53554e57 /* Sun Microsystems */
+#define	JAS_ICC_PLATFORM_TGNT	0x54474e54 /* Taligent */
+
+/* Profile flags. */
+#define	JAS_ICC_FLAGS_EMBED	0x01 /* embedded */
+#define	JAS_ICC_FLAGS_NOSEP	0x02 /* no separate use */
+
+/* Attributes. */
+#define	JAS_ICC_ATTR_TRANS	0x01 /* transparent */
+#define	JAS_ICC_ATTR_MATTE	0x02 /* matte */
+
+/* Rendering intents. */
+#define	JAS_ICC_INTENT_PER	0 /* perceptual */
+#define	JAS_ICC_INTENT_REL	1 /* relative colorimetric */
+#define	JAS_ICC_INTENT_SAT	2 /* saturation */
+#define	JAS_ICC_INTENT_ABS	3 /* absolute colorimetric */
+
+/* Tag signatures. */
+#define	JAS_ICC_TAG_ATOB0		0x41324230 /* */
+#define	JAS_ICC_TAG_ATOB1		0x41324231 /* */
+#define	JAS_ICC_TAG_ATOB2		0x41324232 /* */
+#define	JAS_ICC_TAG_BLUMATCOL		0x6258595a /* */
+#define	JAS_ICC_TAG_BLUTRC		0x62545243 /* */
+#define	JAS_ICC_TAG_BTOA0		0x42324130 /* */
+#define	JAS_ICC_TAG_BTOA1		0x42324131 /* */
+#define	JAS_ICC_TAG_BTOA2		0x42324132 /* */
+#define	JAS_ICC_TAG_CALTIME		0x63616c74 /* */
+#define	JAS_ICC_TAG_CHARTARGET		0x74617267 /* */
+#define	JAS_ICC_TAG_CPYRT		0x63707274 /* */
+#define	JAS_ICC_TAG_CRDINFO		0x63726469 /* */
+#define	JAS_ICC_TAG_DEVMAKERDESC	0x646d6e64 /* */
+#define	JAS_ICC_TAG_DEVMODELDESC	0x646d6464 /* */
+#define	JAS_ICC_TAG_DEVSET		0x64657673 /* */
+#define	JAS_ICC_TAG_GAMUT		0x67616d74 /* */
+#define	JAS_ICC_TAG_GRYTRC		0x6b545243 /* */
+#define	JAS_ICC_TAG_GRNMATCOL		0x6758595a /* */
+#define	JAS_ICC_TAG_GRNTRC		0x67545243 /* */
+#define	JAS_ICC_TAG_LUM			0x6c756d69 /* */
+#define	JAS_ICC_TAG_MEASURE		0x6d656173 /* */
+#define	JAS_ICC_TAG_MEDIABLKPT		0x626b7074 /* */
+#define	JAS_ICC_TAG_MEDIAWHIPT		0x77747074 /* */
+#define	JAS_ICC_TAG_NAMCOLR		0x6e636f6c /* */
+#define	JAS_ICC_TAG_NAMCOLR2		0x6e636c32 /* */
+#define	JAS_ICC_TAG_OUTRESP		0x72657370 /* */
+#define	JAS_ICC_TAG_PREVIEW0		0x70726530 /* */
+#define	JAS_ICC_TAG_PREVIEW1		0x70726531 /* */
+#define	JAS_ICC_TAG_PREVIEW2		0x70726532 /* */
+#define	JAS_ICC_TAG_PROFDESC		0x64657363 /* */
+#define	JAS_ICC_TAG_PROFSEQDESC		0x70736571 /* */
+#define	JAS_ICC_TAG_PSDCRD0		0x70736430 /* */
+#define	JAS_ICC_TAG_PSCRDD1		0x70736431 /* */
+#define	JAS_ICC_TAG_PSCRDD2		0x70736432 /* */
+#define	JAS_ICC_TAG_PSCRDD3		0x70736433 /* */
+#define	JAS_ICC_TAG_PS2CSA		0x70733273 /* */
+#define	JAS_ICC_TAG_PS2RENINTENT	0x70733269 /* */
+#define	JAS_ICC_TAG_REDMATCOL		0x7258595a /* */
+#define	JAS_ICC_TAG_REDTRC		0x72545243 /* */
+#define	JAS_ICC_TAG_SCRNGDES		0x73637264 /* */
+#define	JAS_ICC_TAG_SCRNG		0x7363726e /* */
+#define	JAS_ICC_TAG_TECH		0x74656368 /* */
+#define	JAS_ICC_TAG_UCRBG		0x62666420 /* */
+#define	JAS_ICC_TAG_VIEWCONDDESC	0x76756564 /* */
+#define	JAS_ICC_TAG_VIEWCOND		0x76696577 /* */
+
+/* Type signatures. */
+#define	JAS_ICC_TYPE_CRDINFO		0x63726469 /* CRD information */
+#define	JAS_ICC_TYPE_CURV		0x63757276 /* curve */
+#define	JAS_ICC_TYPE_DATA		0x64617461 /* data */
+#define	JAS_ICC_TYPE_TIME		0x6474696d /* date/time */
+#define	JAS_ICC_TYPE_DEVSET		0x64657673 /* device settings */
+#define	JAS_ICC_TYPE_LUT16		0x6d667432 /* */
+#define	JAS_ICC_TYPE_LUT8		0x6d667431 /* */
+#define	JAS_ICC_TYPE_MEASURE		0x6d656173 /* */
+#define	JAS_ICC_TYPE_NAMCOLR		0x6e636f6c /* */
+#define	JAS_ICC_TYPE_NAMCOLR2		0x6e636c32 /* */
+#define	JAS_ICC_TYPE_PROFSEQDESC	0x70736571 /* profile sequence description */
+#define	JAS_ICC_TYPE_RESPCURVSET16	0x72637332 /* response curve set 16 */
+#define	JAS_ICC_TYPE_SF32		0x73663332 /* signed 32-bit fixed-point */
+#define	JAS_ICC_TYPE_SCRNG		0x7363726e /* screening */
+#define	JAS_ICC_TYPE_SIG		0x73696720 /* signature */
+#define	JAS_ICC_TYPE_TXTDESC		0x64657363 /* text description */
+#define	JAS_ICC_TYPE_TXT		0x74657874 /* text */
+#define	JAS_ICC_TYPE_UF32		0x75663332 /* unsigned 32-bit fixed-point */
+#define	JAS_ICC_TYPE_UCRBG		0x62666420 /* */
+#define	JAS_ICC_TYPE_UI16		0x75693136 /* */
+#define	JAS_ICC_TYPE_UI32		0x75693332 /* */
+#define	JAS_ICC_TYPE_UI8		0x75693038 /* */
+#define	JAS_ICC_TYPE_UI64		0x75693634 /* */
+#define	JAS_ICC_TYPE_VIEWCOND		0x76696577 /* */
+#define	JAS_ICC_TYPE_XYZ		0x58595a20 /* XYZ */
+
+typedef uint_fast8_t jas_iccuint8_t;
+typedef uint_fast16_t jas_iccuint16_t;
+typedef uint_fast32_t jas_iccuint32_t;
+typedef int_fast32_t jas_iccsint32_t;
+typedef int_fast32_t jas_iccs15fixed16_t;
+typedef uint_fast32_t jas_iccu16fixed16_t;
+typedef uint_fast64_t jas_iccuint64_t;
+typedef uint_fast32_t jas_iccsig_t;
+
+typedef jas_iccsig_t jas_icctagsig_t;
+typedef jas_iccsig_t jas_icctagtype_t;
+typedef jas_iccsig_t jas_iccattrname_t;
+
+/* Date/time type. */
+typedef struct {
+	jas_iccuint16_t year;
+	jas_iccuint16_t month;
+	jas_iccuint16_t day;
+	jas_iccuint16_t hour;
+	jas_iccuint16_t min;
+	jas_iccuint16_t sec;
+} jas_icctime_t;
+
+/* XYZ type. */
+typedef struct {
+	jas_iccs15fixed16_t x;
+	jas_iccs15fixed16_t y;
+	jas_iccs15fixed16_t z;
+} jas_iccxyz_t;
+
+/* Curve type. */
+typedef struct {
+	jas_iccuint32_t numents;
+	jas_iccuint16_t *ents;
+} jas_icccurv_t;
+
+/* Text description type. */
+typedef struct {
+	jas_iccuint32_t asclen;
+	char *ascdata; /* ASCII invariant description */
+	jas_iccuint32_t uclangcode; /* Unicode language code */
+	jas_iccuint32_t uclen; /* Unicode localizable description count */
+	jas_uchar *ucdata; /* Unicode localizable description */
+	jas_iccuint16_t sccode; /* ScriptCode code */
+	jas_iccuint8_t maclen; /* Localizable Macintosh description count */
+	jas_uchar macdata[69]; /* Localizable Macintosh description */
+} jas_icctxtdesc_t;
+
+/* Text type. */
+typedef struct {
+	char *string;	/* ASCII character string */
+} jas_icctxt_t;
+
+typedef struct {
+	jas_iccuint8_t numinchans;
+	jas_iccuint8_t numoutchans;
+	jas_iccsint32_t e[3][3];
+	jas_iccuint8_t clutlen;
+	jas_iccuint8_t *clut;
+	jas_iccuint16_t numintabents;
+	jas_iccuint8_t **intabs;
+	jas_iccuint8_t *intabsbuf;
+	jas_iccuint16_t numouttabents;
+	jas_iccuint8_t **outtabs;
+	jas_iccuint8_t *outtabsbuf;
+} jas_icclut8_t;
+
+typedef struct {
+	jas_iccuint8_t numinchans;
+	jas_iccuint8_t numoutchans;
+	jas_iccsint32_t e[3][3];
+	jas_iccuint8_t clutlen;
+	jas_iccuint16_t *clut;
+	jas_iccuint16_t numintabents;
+	jas_iccuint16_t **intabs;
+	jas_iccuint16_t *intabsbuf;
+	jas_iccuint16_t numouttabents;
+	jas_iccuint16_t **outtabs;
+	jas_iccuint16_t *outtabsbuf;
+} jas_icclut16_t;
+
+struct jas_iccattrval_s;
+
+typedef struct {
+	void (*destroy)(struct jas_iccattrval_s *);
+	int (*copy)(struct jas_iccattrval_s *, const struct jas_iccattrval_s *);
+	int (*input)(struct jas_iccattrval_s *, jas_stream_t *, unsigned);
+//#ifdef JAS_ENABLE_ENCODER
+	int (*output)(struct jas_iccattrval_s *, jas_stream_t *);
+//#endif
+	unsigned (*getsize)(const struct jas_iccattrval_s *);
+	void (*dump)(const struct jas_iccattrval_s *, FILE *);
+} jas_iccattrvalops_t;
+
+/* Attribute value type (type and value information). */
+typedef struct jas_iccattrval_s {
+	unsigned refcnt; /* reference count */
+	jas_iccsig_t type; /* type */
+	const jas_iccattrvalops_t *ops; /* type-dependent operations */
+	union {
+		jas_iccxyz_t xyz;
+		jas_icccurv_t curv;
+		jas_icctxtdesc_t txtdesc;
+		jas_icctxt_t txt;
+		jas_icclut8_t lut8;
+		jas_icclut16_t lut16;
+	} data; /* value */
+} jas_iccattrval_t;
+
+/* Header type. */
+typedef struct {
+	jas_iccuint32_t size; /* profile size */
+	jas_iccsig_t cmmtype; /* CMM type signature */
+	jas_iccuint32_t version; /* profile version */
+	jas_iccsig_t clas; /* profile/device class signature */
+	jas_iccsig_t colorspc; /* color space of data */
+	jas_iccsig_t refcolorspc; /* profile connection space */
+	jas_icctime_t ctime; /* creation time */
+	jas_iccsig_t magic; /* profile file signature */
+	jas_iccsig_t platform; /* primary platform */
+	jas_iccuint32_t flags; /* profile flags */
+	jas_iccsig_t maker; /* device manufacturer signature */
+	jas_iccsig_t model; /* device model signature */
+	jas_iccuint64_t attr; /* device setup attributes */
+	jas_iccsig_t intent; /* rendering intent */
+	jas_iccxyz_t illum; /* illuminant */
+	jas_iccsig_t creator; /* profile creator signature */
+} jas_icchdr_t;
+
+typedef struct {
+	jas_iccsig_t name;
+	jas_iccattrval_t *val;
+} jas_iccattr_t;
+
+typedef struct {
+	unsigned numattrs;
+	unsigned maxattrs;
+	jas_iccattr_t *attrs;
+} jas_iccattrtab_t;
+
+typedef struct jas_icctagtabent_s {
+	jas_iccuint32_t tag;
+	jas_iccuint32_t off;
+	jas_iccuint32_t len;
+	void *data;
+	struct jas_icctagtabent_s *first;
+} jas_icctagtabent_t;
+
+typedef struct {
+	jas_iccuint32_t numents;
+	jas_icctagtabent_t *ents;
+} jas_icctagtab_t;
+
+/* ICC profile type. */
+typedef struct {
+	jas_icchdr_t hdr;
+	jas_icctagtab_t tagtab;
+	jas_iccattrtab_t *attrtab;
+} jas_iccprof_t;
+
+typedef struct {
+	jas_iccuint32_t type;
+	jas_iccattrvalops_t ops;
+} jas_iccattrvalinfo_t;
+
+JAS_DLLEXPORT jas_iccprof_t *jas_iccprof_load(jas_stream_t *in);
+JAS_DLLEXPORT int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out);
+JAS_DLLEXPORT void jas_iccprof_destroy(jas_iccprof_t *prof);
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT jas_iccattrval_t *jas_iccprof_getattr(const jas_iccprof_t *prof,
+  jas_iccattrname_t name);
+JAS_DLLEXPORT int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name,
+  jas_iccattrval_t *val);
+JAS_DLLEXPORT void jas_iccprof_dump(const jas_iccprof_t *prof, FILE *out);
+JAS_DLLEXPORT jas_iccprof_t *jas_iccprof_copy(const jas_iccprof_t *prof);
+JAS_DLLEXPORT int jas_iccprof_gethdr(const jas_iccprof_t *prof, jas_icchdr_t *hdr);
+JAS_DLLEXPORT int jas_iccprof_sethdr(jas_iccprof_t *prof, const jas_icchdr_t *hdr);
+
+JAS_DLLEXPORT void jas_iccattrval_destroy(jas_iccattrval_t *attrval);
+JAS_DLLEXPORT void jas_iccattrval_dump(const jas_iccattrval_t *attrval, FILE *out);
+JAS_DLLEXPORT int jas_iccattrval_allowmodify(jas_iccattrval_t **attrval);
+JAS_DLLEXPORT jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval);
+JAS_DLLEXPORT jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type);
+
+JAS_DLLEXPORT void jas_iccattrtab_dump(const jas_iccattrtab_t *attrtab, FILE *out);
+
+JAS_DLLEXPORT extern const jas_uchar jas_iccprofdata_srgb[];
+JAS_DLLEXPORT extern const unsigned jas_iccprofdata_srgblen;
+JAS_DLLEXPORT extern const jas_uchar jas_iccprofdata_sgray[];
+JAS_DLLEXPORT extern const unsigned jas_iccprofdata_sgraylen;
+JAS_DLLEXPORT jas_iccprof_t *jas_iccprof_createfrombuf(const jas_uchar *buf, unsigned len);
+JAS_DLLEXPORT jas_iccprof_t *jas_iccprof_createfromclrspc(unsigned clrspc);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_image.h
@@ -1,0 +1,772 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_image.h
+ * @brief JasPer Image Class
+ */
+
+#ifndef JAS_IMAGE_H
+#define JAS_IMAGE_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#include <jasper/jas_stream.h>
+#include <jasper/jas_types.h>
+#include <jasper/jas_seq.h> /* IWYU pragma: export */
+#include <jasper/jas_cm.h> /* IWYU pragma: export */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * @addtogroup image
+ * @{
+ */
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/*
+ * Miscellaneous constants.
+ */
+
+/* Basic units */
+#define JAS_IMAGE_KIBI			(JAS_CAST(size_t, 1024))
+#define JAS_IMAGE_MEBI			(JAS_IMAGE_KIBI * JAS_IMAGE_KIBI)
+
+/* The threshold at which image data is no longer stored in memory. */
+#define JAS_IMAGE_INMEMTHRESH	(256 * JAS_IMAGE_MEBI)
+
+/*
+ * Component types
+ */
+
+#define	JAS_IMAGE_CT_UNKNOWN	0x10000
+#define	JAS_IMAGE_CT_COLOR(n)	((n) & 0x7fff)
+#define	JAS_IMAGE_CT_OPACITY	0x08000
+
+#define	JAS_IMAGE_CT_RGB_R	0
+#define	JAS_IMAGE_CT_RGB_G	1
+#define	JAS_IMAGE_CT_RGB_B	2
+
+#define	JAS_IMAGE_CT_YCBCR_Y	0
+#define	JAS_IMAGE_CT_YCBCR_CB	1
+#define	JAS_IMAGE_CT_YCBCR_CR	2
+
+#define	JAS_IMAGE_CT_GRAY_Y	0
+
+/******************************************************************************\
+* Simple types.
+\******************************************************************************/
+
+/*!
+@brief Image coordinate. */
+typedef int_fast32_t jas_image_coord_t;
+#define JAS_IMAGE_COORD_MAX INT_FAST32_MAX
+#define JAS_IMAGE_COORD_MIN INT_FAST32_MIN
+
+/*!
+@brief Color space (e.g., RGB, YCbCr).
+*/
+typedef int_fast16_t jas_image_colorspc_t;
+
+/*!
+@brief Component type (e.g., color, opacity).
+*/
+typedef int_fast32_t jas_image_cmpttype_t;
+
+/*!
+@brief Component sample data format
+(e.g., real/integer, signedness, precision).
+*/
+typedef int_fast16_t jas_image_smpltype_t;
+
+/******************************************************************************\
+* Image class and supporting classes.
+\******************************************************************************/
+
+/*!
+@brief Image component class.
+*/
+typedef struct {
+
+	jas_image_coord_t tlx_;
+	/* The x-coordinate of the top-left corner of the component. */
+
+	jas_image_coord_t tly_;
+	/* The y-coordinate of the top-left corner of the component. */
+
+	jas_image_coord_t hstep_;
+	/* The horizontal sampling period in units of the reference grid. */
+
+	jas_image_coord_t vstep_;
+	/* The vertical sampling period in units of the reference grid. */
+
+	jas_image_coord_t width_;
+	/* The component width in samples. */
+
+	jas_image_coord_t height_;
+	/* The component height in samples. */
+
+	unsigned prec_;
+	/* The precision of the sample data (i.e., the number of bits per
+	sample).  If the samples are signed values, this quantity
+	includes the sign bit. */
+
+	int sgnd_;
+	/* The signedness of the sample data. */
+
+	jas_stream_t *stream_;
+	/* The stream containing the component data. */
+
+	unsigned cps_;
+	/* The number of characters per sample in the stream. */
+
+	jas_image_cmpttype_t type_;
+	/* The type of component (e.g., opacity, red, green, blue, luma). */
+
+} jas_image_cmpt_t;
+
+/*!
+@brief Image class.
+*/
+typedef struct {
+
+	jas_image_coord_t tlx_;
+	/* The x-coordinate of the top-left corner of the image bounding box. */
+
+	jas_image_coord_t tly_;
+	/* The y-coordinate of the top-left corner of the image bounding box. */
+
+	jas_image_coord_t brx_;
+	/* The x-coordinate of the bottom-right corner of the image bounding
+	  box (plus one). */
+
+	jas_image_coord_t bry_;
+	/* The y-coordinate of the bottom-right corner of the image bounding
+	  box (plus one). */
+
+	unsigned numcmpts_;
+	/* The number of components. */
+
+	unsigned maxcmpts_;
+	/* The maximum number of components that this image can have (i.e., the
+	  allocated size of the components array). */
+
+	jas_image_cmpt_t **cmpts_;
+	/* Per-component information. */
+
+	jas_clrspc_t clrspc_;
+
+	jas_cmprof_t *cmprof_;
+
+//	bool inmem_;
+
+} jas_image_t;
+
+/*!
+@brief Component parameters class.
+
+@details
+This data type exists solely/mainly for the purposes of the
+jas_image_create function.
+*/
+typedef struct {
+
+	jas_image_coord_t tlx;
+	/* The x-coordinate of the top-left corner of the component. */
+
+	jas_image_coord_t tly;
+	/* The y-coordinate of the top-left corner of the component. */
+
+	jas_image_coord_t hstep;
+	/* The horizontal sampling period in units of the reference grid. */
+
+	jas_image_coord_t vstep;
+	/* The vertical sampling period in units of the reference grid. */
+
+	jas_image_coord_t width;
+	/* The width of the component in samples. */
+
+	jas_image_coord_t height;
+	/* The height of the component in samples. */
+
+	unsigned prec;
+	/* The precision of the component sample data. */
+
+	int sgnd;
+	/* The signedness of the component sample data. */
+
+} jas_image_cmptparm_t;
+
+/******************************************************************************\
+* File format related classes.
+\******************************************************************************/
+
+/*!
+@brief The maximum number of image data formats supported.
+*/
+#define	JAS_IMAGE_MAXFMTS	32
+
+/*!
+@brief Image format-dependent operations.
+*/
+typedef struct {
+
+	jas_image_t *(*decode)(jas_stream_t *in, const char *opts);
+	/* Decode image data from a stream. */
+
+	int (*encode)(jas_image_t *image, jas_stream_t *out, const char *opts);
+	/* Encode image data to a stream. */
+
+	int (*validate)(jas_stream_t *in);
+	/* Determine if stream data is in a particular format. */
+
+} jas_image_fmtops_t;
+
+/*!
+@brief Image format information.
+*/
+typedef struct {
+
+	int id;
+	/* The ID for this format. */
+
+	char *name;
+	/* The name by which this format is identified. */
+
+	char *ext;
+	/* The file name extension associated with this format. */
+
+	char *desc;
+	/* A brief description of the format. */
+
+	jas_image_fmtops_t ops;
+	/* The operations for this format. */
+
+} jas_image_fmtinfo_t;
+
+/******************************************************************************\
+* Image operations.
+\******************************************************************************/
+
+/*!
+@brief Create an image.
+*/
+JAS_DLLEXPORT jas_image_t *jas_image_create(unsigned numcmpts,
+  const jas_image_cmptparm_t *cmptparms, jas_clrspc_t clrspc);
+
+/*!
+@brief Create an "empty" image.
+*/
+JAS_DLLEXPORT jas_image_t *jas_image_create0(void);
+
+/*!
+@brief Clone an image.
+*/
+JAS_DLLEXPORT jas_image_t *jas_image_copy(jas_image_t *image);
+
+/*!
+@brief Deallocate any resources associated with an image.
+*/
+JAS_DLLEXPORT void jas_image_destroy(jas_image_t *image);
+
+/*!
+@brief Get the width of the image in units of the image reference grid.
+*/
+#define jas_image_width(image) \
+	((image)->brx_ - (image)->tlx_)
+
+/*!
+@brief Get the height of the image in units of the image reference grid.
+*/
+#define	jas_image_height(image) \
+	((image)->bry_ - (image)->tly_)
+
+/*!
+@brief Get the x-coordinate of the top-left corner of the image bounding box
+on the reference grid.
+*/
+#define jas_image_tlx(image) \
+	((image)->tlx_)
+
+/*!
+@brief Get the y-coordinate of the top-left corner of the image bounding box
+  on the reference grid.
+*/
+#define jas_image_tly(image) \
+	((image)->tly_)
+
+/*!
+@brief Get the x-coordinate of the bottom-right corner of the image bounding box
+  on the reference grid (plus one).
+*/
+#define jas_image_brx(image) \
+	((image)->brx_)
+
+/*!
+@brief Get the y-coordinate of the bottom-right corner of the image bounding
+box on the reference grid (plus one).
+*/
+#define jas_image_bry(image) \
+	((image)->bry_)
+
+/*!
+@brief Get the number of image components.
+*/
+#define	jas_image_numcmpts(image) \
+	((image)->numcmpts_)
+
+/*!
+@brief Get the color model used by the image.
+*/
+#define	jas_image_clrspc(image) \
+	((image)->clrspc_)
+
+/*!
+@brief Set the color model for an image.
+*/
+#define jas_image_setclrspc(image, clrspc) \
+	((image)->clrspc_ = (clrspc))
+
+#define jas_image_cmpttype(image, cmptno) \
+	((image)->cmpts_[(cmptno)]->type_)
+#define jas_image_setcmpttype(image, cmptno, type) \
+	((image)->cmpts_[(cmptno)]->type_ = (type))
+
+/*!
+@brief Get the width of a component.
+*/
+#define	jas_image_cmptwidth(image, cmptno) \
+	((image)->cmpts_[cmptno]->width_)
+
+/*!
+@brief Get the height of a component.
+*/
+#define	jas_image_cmptheight(image, cmptno) \
+	((image)->cmpts_[cmptno]->height_)
+
+/*!
+@brief Get the signedness of the sample data for a component.
+*/
+#define	jas_image_cmptsgnd(image, cmptno) \
+	((image)->cmpts_[cmptno]->sgnd_)
+
+/*!
+@brief Get the precision of the sample data for a component.
+*/
+#define	jas_image_cmptprec(image, cmptno) \
+	((image)->cmpts_[cmptno]->prec_)
+
+/*!
+@brief Get the horizontal subsampling factor for a component.
+*/
+#define	jas_image_cmpthstep(image, cmptno) \
+	((image)->cmpts_[cmptno]->hstep_)
+
+/*!
+@brief Get the vertical subsampling factor for a component.
+*/
+#define	jas_image_cmptvstep(image, cmptno) \
+	((image)->cmpts_[cmptno]->vstep_)
+
+/*!
+@brief Get the x-coordinate of the top-left corner of a component.
+*/
+#define	jas_image_cmpttlx(image, cmptno) \
+	((image)->cmpts_[cmptno]->tlx_)
+
+/*!
+@brief Get the y-coordinate of the top-left corner of a component.
+*/
+#define	jas_image_cmpttly(image, cmptno) \
+	((image)->cmpts_[cmptno]->tly_)
+
+/*!
+@brief Get the x-coordinate of the bottom-right corner of a component
+(plus "one").
+*/
+#define	jas_image_cmptbrx(image, cmptno) \
+	((image)->cmpts_[cmptno]->tlx_ + (image)->cmpts_[cmptno]->width_ * \
+	  (image)->cmpts_[cmptno]->hstep_)
+
+/*!
+@brief Get the y-coordinate of the bottom-right corner of a component
+(plus "one").
+*/
+#define	jas_image_cmptbry(image, cmptno) \
+	((image)->cmpts_[cmptno]->tly_ + (image)->cmpts_[cmptno]->height_ * \
+	  (image)->cmpts_[cmptno]->vstep_)
+
+/*!
+@brief Test if all components are specified at the same positions in space.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT bool jas_image_cmpt_domains_same(const jas_image_t *image);
+
+/*!
+@brief Get the raw size of an image
+(i.e., the nominal size of the image without any compression.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT
+uint_fast32_t jas_image_rawsize(const jas_image_t *image);
+
+/*!
+@brief Create an image from a stream in some specified format.
+*/
+JAS_DLLEXPORT
+jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, const char *optstr);
+
+/*!
+@brief Write an image to a stream in a specified format.
+*/
+JAS_DLLEXPORT
+int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt,
+  const char *optstr);
+
+/*!
+@brief Read a rectangular region of an image component.
+
+@details
+The position and size of the rectangular region to be read is specified
+relative to the component's coordinate system.
+*/
+JAS_DLLEXPORT
+int jas_image_readcmpt(jas_image_t *image, unsigned cmptno,
+  jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width,
+  jas_image_coord_t height, jas_matrix_t *data);
+
+/*!
+@brief Write a rectangular region of an image component.
+*/
+JAS_DLLEXPORT
+int jas_image_writecmpt(jas_image_t *image, unsigned cmptno,
+  jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width,
+  jas_image_coord_t height, const jas_matrix_t *data);
+
+/*!
+@brief Delete a component from an image.
+*/
+JAS_DLLEXPORT void jas_image_delcmpt(jas_image_t *image, unsigned cmptno);
+
+/*!
+@brief Add a component to an image.
+*/
+JAS_DLLEXPORT int jas_image_addcmpt(jas_image_t *image, int cmptno,
+  const jas_image_cmptparm_t *cmptparm);
+
+/*!
+@brief Copy a component from one image to another.
+*/
+JAS_DLLEXPORT int jas_image_copycmpt(jas_image_t *dstimage, unsigned dstcmptno,
+  jas_image_t *srcimage, unsigned srccmptno);
+
+JAS_ATTRIBUTE_CONST
+static inline bool JAS_IMAGE_CDT_GETSGND(uint_least8_t dtype)
+{
+	return (dtype >> 7) & 1;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline uint_least8_t JAS_IMAGE_CDT_SETSGND(bool sgnd)
+{
+	return (uint_least8_t)sgnd << 7;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline uint_least8_t JAS_IMAGE_CDT_GETPREC(uint_least8_t dtype)
+{
+	return dtype & 0x7f;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline uint_least8_t JAS_IMAGE_CDT_SETPREC(uint_least8_t dtype)
+{
+	return dtype & 0x7f;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline uint_least8_t jas_image_cmptdtype(const jas_image_t *image, unsigned cmptno)
+{
+	return JAS_IMAGE_CDT_SETSGND(image->cmpts_[cmptno]->sgnd_) |
+		JAS_IMAGE_CDT_SETPREC(image->cmpts_[cmptno]->prec_);
+}
+
+/*!
+@brief Depalettize an image
+*/
+JAS_DLLEXPORT
+int jas_image_depalettize(jas_image_t *image, unsigned cmptno,
+  unsigned numlutents, const int_fast32_t *lutents, unsigned dtype,
+  unsigned newcmptno);
+
+/*!
+@brief Read a component sample for an image.
+*/
+JAS_DLLEXPORT
+int jas_image_readcmptsample(jas_image_t *image, unsigned cmptno, unsigned x,
+  unsigned y);
+
+/*!
+@brief Write a component sample for an image.
+*/
+JAS_DLLEXPORT
+void jas_image_writecmptsample(jas_image_t *image, unsigned cmptno,
+  unsigned x, unsigned y, int_fast32_t v);
+
+/*!
+@brief Get an image component by its type.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT
+int jas_image_getcmptbytype(const jas_image_t *image, jas_image_cmpttype_t ctype);
+
+/******************************************************************************\
+* Image format-related operations.
+\******************************************************************************/
+
+/*!
+@brief Clear the table of image formats.
+*/
+JAS_DLLEXPORT
+void jas_image_clearfmts(void);
+
+/*!
+@brief Add entry to table of image formats.
+*/
+JAS_DLLEXPORT
+int jas_image_addfmt(int id, const char *name, const char *ext,
+  const char *desc, const jas_image_fmtops_t *ops);
+
+/*!
+@brief Get the ID for the image format with the specified name.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT
+int jas_image_strtofmt(const char *s);
+
+/*!
+@brief Get the name of the image format with the specified ID.
+*/
+JAS_ATTRIBUTE_CONST
+JAS_DLLEXPORT
+const char *jas_image_fmttostr(int fmt);
+
+/*!
+@brief Lookup image format information by the format ID.
+*/
+JAS_ATTRIBUTE_CONST
+JAS_DLLEXPORT
+const jas_image_fmtinfo_t *jas_image_lookupfmtbyid(int id);
+
+/*!
+@brief Lookup image format information by the format name.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT
+const jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name);
+
+/*!
+@brief Guess the format of an image file based on its name.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT
+int jas_image_fmtfromname(const char *filename);
+
+/*!
+@brief Get the format of image data in a stream.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT
+int jas_image_getfmt(jas_stream_t *in);
+
+
+/*!
+@brief Get the color management profile of an image.
+*/
+#define	jas_image_cmprof(image)	((image)->cmprof_)
+
+/*!
+@brief ???
+*/
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT
+int jas_image_ishomosamp(const jas_image_t *image);
+
+/*!
+@brief ???
+*/
+JAS_DLLEXPORT
+int jas_image_sampcmpt(jas_image_t *image, unsigned cmptno, unsigned newcmptno,
+  jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs,
+  jas_image_coord_t vs, int sgnd, unsigned prec);
+
+/*!
+@brief Write sample data in a component of an image.
+*/
+JAS_DLLEXPORT int jas_image_writecmpt2(jas_image_t *image, unsigned cmptno, jas_image_coord_t x,
+  jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+  const long *buf);
+
+/*!
+@brief Read sample data in a component of an image.
+*/
+JAS_DLLEXPORT
+int jas_image_readcmpt2(jas_image_t *image, unsigned cmptno,
+  jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width,
+  jas_image_coord_t height, long *buf);
+
+/*!
+@brief Set the color management profile for an image.
+*/
+#define	jas_image_setcmprof(image, cmprof) ((image)->cmprof_ = cmprof)
+
+/*!
+@brief Change the color space for an image.
+*/
+JAS_DLLEXPORT jas_image_t *jas_image_chclrspc(jas_image_t *image, const jas_cmprof_t *outprof,
+  jas_cmxform_intent_t intent);
+
+/*!
+@brief Dump the information for an image (for debugging).
+*/
+JAS_DLLEXPORT void jas_image_dump(jas_image_t *image, FILE *out);
+
+/******************************************************************************\
+* Image format-dependent operations.
+\******************************************************************************/
+
+#if defined(JAS_INCLUDE_JPG_CODEC)
+/* Format-dependent operations for JPG support. */
+JAS_DLLEXPORT jas_image_t *jpg_decode(jas_stream_t *in, const char *optstr);
+JAS_DLLEXPORT int jpg_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+JAS_DLLEXPORT int jpg_validate(jas_stream_t *in);
+#endif
+
+#if defined(JAS_INCLUDE_MIF_CODEC)
+/* Format-dependent operations for MIF support. */
+JAS_DLLEXPORT jas_image_t *mif_decode(jas_stream_t *in, const char *optstr);
+JAS_DLLEXPORT int mif_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+JAS_DLLEXPORT int mif_validate(jas_stream_t *in);
+#endif
+
+#if defined(JAS_INCLUDE_PNM_CODEC)
+/* Format-dependent operations for PNM support. */
+JAS_DLLEXPORT jas_image_t *pnm_decode(jas_stream_t *in, const char *optstr);
+JAS_DLLEXPORT int pnm_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+JAS_DLLEXPORT int pnm_validate(jas_stream_t *in);
+#endif
+
+#if defined(JAS_INCLUDE_RAS_CODEC)
+/* Format-dependent operations for Sun Rasterfile support. */
+JAS_DLLEXPORT jas_image_t *ras_decode(jas_stream_t *in, const char *optstr);
+JAS_DLLEXPORT int ras_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+JAS_DLLEXPORT int ras_validate(jas_stream_t *in);
+#endif
+
+#if defined(JAS_INCLUDE_BMP_CODEC)
+/* Format-dependent operations for BMP support. */
+JAS_DLLEXPORT jas_image_t *bmp_decode(jas_stream_t *in, const char *optstr);
+JAS_DLLEXPORT int bmp_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+JAS_DLLEXPORT int bmp_validate(jas_stream_t *in);
+#endif
+
+#if defined(JAS_INCLUDE_JP2_CODEC)
+/* Format-dependent operations for JP2 support. */
+JAS_DLLEXPORT jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr);
+JAS_DLLEXPORT int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+JAS_DLLEXPORT int jp2_validate(jas_stream_t *in);
+#endif
+
+#if defined(JAS_INCLUDE_JPC_CODEC)
+/* Format-dependent operations for JPEG-2000 code stream support. */
+JAS_DLLEXPORT jas_image_t *jpc_decode(jas_stream_t *in, const char *optstr);
+JAS_DLLEXPORT int jpc_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+JAS_DLLEXPORT int jpc_validate(jas_stream_t *in);
+#endif
+
+#if defined(JAS_INCLUDE_PGX_CODEC)
+/* Format-dependent operations for PGX support. */
+JAS_DLLEXPORT jas_image_t *pgx_decode(jas_stream_t *in, const char *optstr);
+JAS_DLLEXPORT int pgx_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+JAS_DLLEXPORT int pgx_validate(jas_stream_t *in);
+#endif
+
+/*!
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_init.h
@@ -1,0 +1,117 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_init.h
+ * @brief JasPer Initialization/Cleanup Code
+ */
+
+#ifndef JAS_INIT_H
+#define JAS_INIT_H
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * @addtogroup init
+ * @{
+ */
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/*!
+@brief Initialize the JasPer library.
+
+@details
+This function must be called before any other code in the JasPer library
+is invoked.
+This function registers the codecs that are enabled by default.
+
+@returns
+If successful, zero is returned; otherwise, a nonzero value is returned.
+*/
+JAS_DLLEXPORT
+int jas_init(void);
+
+/*!
+@brief Perform any clean up for the JasPer library.
+
+@details
+This function performs any clean up for the JasPer library.
+*/
+JAS_DLLEXPORT
+void jas_cleanup(void);
+
+/*!
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_malloc.h
@@ -1,0 +1,122 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+
+/*!
+ * @file jas_malloc.h
+ * @brief JasPer Memory Allocator
+ */
+
+#ifndef JAS_MALLOC_H
+#define JAS_MALLOC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Allocate memory. */
+JAS_DLLEXPORT void *jas_malloc(size_t size);
+
+/* Free memory. */
+JAS_DLLEXPORT void jas_free(void *ptr);
+
+/* Resize a block of allocated memory. */
+JAS_DLLEXPORT void *jas_realloc(void *ptr, size_t size);
+
+/* Allocate a block of memory and initialize the contents to zero. */
+JAS_DLLEXPORT void *jas_calloc(size_t num_elements, size_t element_size);
+
+/* Allocate array (with overflow checking) . */
+JAS_DLLEXPORT void *jas_alloc2(size_t num_elements, size_t element_size);
+
+/* Allocate array of arrays (with overflow checking) . */
+JAS_DLLEXPORT void *jas_alloc3(size_t num_arrays, size_t array_size, size_t element_size);
+
+/* Resize a block of allocated memory (with overflow checking) . */
+JAS_DLLEXPORT void *jas_realloc2(void *ptr, size_t num_elements, size_t element_size);
+
+#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
+
+JAS_DLLEXPORT void jas_set_max_mem_usage(size_t max_mem);
+
+JAS_ATTRIBUTE_PURE
+JAS_DLLEXPORT size_t jas_get_mem_usage();
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_math.h
@@ -1,0 +1,368 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_math.h
+ * @brief Math-Related Code
+ */
+
+#ifndef	JAS_MATH_H
+#define	JAS_MATH_H
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+#include <jasper/jas_types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Macros
+\******************************************************************************/
+
+#define JAS_KIBI	JAS_CAST(size_t, 1024)
+#define JAS_MEBI	(JAS_KIBI * JAS_KIBI)
+
+/* Compute the absolute value. */
+#define	JAS_ABS(x) \
+	(((x) >= 0) ? (x) : (-(x)))
+
+/* Compute the minimum of two values. */
+#define	JAS_MIN(x, y) \
+	(((x) < (y)) ? (x) : (y))
+
+/* Compute the maximum of two values. */
+#define	JAS_MAX(x, y) \
+	(((x) > (y)) ? (x) : (y))
+
+/* Compute the remainder from division (where division is defined such
+  that the remainder is always nonnegative). */
+#define	JAS_MOD(x, y) \
+	(((x) < 0) ? (((-x) % (y)) ? ((y) - ((-(x)) % (y))) : (0)) : ((x) % (y)))
+
+/* Compute the integer with the specified number of least significant bits
+  set to one. */
+#define	JAS_ONES(n) \
+  ((1 << (n)) - 1)
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 6)
+/* suppress clang warning "shifting a negative signed value is
+   undefined" in the assertions below */
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshift-negative-value"
+#endif
+
+JAS_ATTRIBUTE_CONST
+JAS_ATTRIBUTE_DISABLE_USAN
+inline static int jas_int_asr(int x, unsigned n)
+{
+	// Ensure that the shift of a negative value appears to behave as a
+	// signed arithmetic shift.
+	assert(((-1) >> 1) == -1);
+	// The behavior is undefined when x is negative. */
+	// We tacitly assume the behavior is equivalent to a signed
+	// arithmetic right shift.
+	return x >> n;
+}
+
+JAS_ATTRIBUTE_CONST
+JAS_ATTRIBUTE_DISABLE_USAN
+inline static int jas_int_asl(int x, unsigned n)
+{
+	// Ensure that the shift of a negative value appears to behave as a
+	// signed arithmetic shift.
+	assert(((-1) << 1) == -2);
+	// The behavior is undefined when x is negative. */
+	// We tacitly assume the behavior is equivalent to a signed
+	// arithmetic left shift.
+	return x << n;
+}
+
+JAS_ATTRIBUTE_CONST
+JAS_ATTRIBUTE_DISABLE_USAN
+inline static int_least32_t jas_least32_asr(int_least32_t x, unsigned n)
+{
+	// Ensure that the shift of a negative value appears to behave as a
+	// signed arithmetic shift.
+	assert(((JAS_CAST(int_least32_t, -1)) >> 1) == JAS_CAST(int_least32_t, -1));
+	// The behavior is undefined when x is negative. */
+	// We tacitly assume the behavior is equivalent to a signed
+	// arithmetic right shift.
+	return x >> n;
+}
+
+JAS_ATTRIBUTE_CONST
+JAS_ATTRIBUTE_DISABLE_USAN
+inline static int_least32_t jas_least32_asl(int_least32_t x, unsigned n)
+{
+	// Ensure that the shift of a negative value appears to behave as a
+	// signed arithmetic shift.
+	assert(((JAS_CAST(int_least32_t, -1)) << 1) == JAS_CAST(int_least32_t, -2));
+	// The behavior is undefined when x is negative. */
+	// We tacitly assume the behavior is equivalent to a signed
+	// arithmetic left shift.
+	return x << n;
+}
+
+JAS_ATTRIBUTE_CONST
+JAS_ATTRIBUTE_DISABLE_USAN
+inline static int_fast32_t jas_fast32_asr(int_fast32_t x, unsigned n)
+{
+	// Ensure that the shift of a negative value appears to behave as a
+	// signed arithmetic shift.
+	assert(((JAS_CAST(int_fast32_t, -1)) >> 1) == JAS_CAST(int_fast32_t, -1));
+	// The behavior is undefined when x is negative. */
+	// We tacitly assume the behavior is equivalent to a signed
+	// arithmetic right shift.
+	return x >> n;
+}
+
+JAS_ATTRIBUTE_CONST
+JAS_ATTRIBUTE_DISABLE_USAN
+inline static int_fast32_t jas_fast32_asl(int_fast32_t x, unsigned n)
+{
+	// Ensure that the shift of a negative value appears to behave as a
+	// signed arithmetic shift.
+	assert(((JAS_CAST(int_fast32_t, -1)) << 1) == JAS_CAST(int_fast32_t, -2));
+	// The behavior is undefined when x is negative. */
+	// We tacitly assume the behavior is equivalent to a signed
+	// arithmetic left shift.
+	return x << n;
+}
+
+#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 6)
+#pragma GCC diagnostic pop
+#endif
+
+/******************************************************************************\
+* Safe integer arithmetic (i.e., with overflow checking).
+\******************************************************************************/
+
+/* Compute the product of two size_t integers with overflow checking. */
+inline static bool jas_safe_size_mul(size_t x, size_t y, size_t *result)
+{
+#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 5)
+	size_t result_buffer;
+	if (!result)
+		result = &result_buffer;
+	return !__builtin_mul_overflow(x, y, result);
+#else
+	/* Check if overflow would occur */
+	if (x && y > SIZE_MAX / x) {
+		/* Overflow would occur. */
+		return false;
+	}
+	if (result) {
+		*result = x * y;
+	}
+	return true;
+#endif
+}
+
+/* Compute the product of three size_t integers with overflow checking. */
+inline static bool jas_safe_size_mul3(size_t a, size_t b, size_t c,
+  size_t *result)
+{
+	size_t tmp;
+	if (!jas_safe_size_mul(a, b, &tmp) ||
+	  !jas_safe_size_mul(tmp, c, &tmp)) {
+		return false;
+	}
+	if (result) {
+		*result = tmp;
+	}
+	return true;
+}
+
+/* Compute the sum of two size_t integers with overflow checking. */
+inline static bool jas_safe_size_add(size_t x, size_t y, size_t *result)
+{
+#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 5)
+	size_t result_buffer;
+	if (!result)
+		result = &result_buffer;
+	return !__builtin_add_overflow(x, y, result);
+#else
+	if (y > SIZE_MAX - x) {
+		return false;
+	}
+	if (result) {
+		*result = x + y;
+	}
+	return true;
+#endif
+}
+
+/* Compute the difference of two size_t integers with overflow checking. */
+inline static bool jas_safe_size_sub(size_t x, size_t y, size_t *result)
+{
+#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 5)
+	size_t result_buffer;
+	if (!result)
+		result = &result_buffer;
+	return !__builtin_sub_overflow(x, y, result);
+#else
+	if (y > x) {
+		return false;
+	}
+	if (result) {
+		*result = x - y;
+	}
+	return true;
+#endif
+}
+
+/* Compute the product of two int_fast32_t integers with overflow checking. */
+inline static bool jas_safe_intfast32_mul(int_fast32_t x, int_fast32_t y,
+  int_fast32_t *result)
+{
+#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 5)
+	int_fast32_t result_buffer;
+	if (!result)
+		result = &result_buffer;
+	return !__builtin_mul_overflow(x, y, result);
+#else
+	if (x > 0) {
+		/* x is positive */
+		if (y > 0) {
+			/* x and y are positive */
+			if (x > INT_FAST32_MAX / y) {
+				return false;
+			}
+		} else {
+			/* x positive, y nonpositive */
+			if (y < INT_FAST32_MIN / x) {
+				return false;
+			}
+		}
+	} else {
+		/* x is nonpositive */
+		if (y > 0) {
+			/* x is nonpositive, y is positive */
+			if (x < INT_FAST32_MIN / y) {
+				return false;
+			}
+		} else { /* x and y are nonpositive */
+			if (x != 0 && y < INT_FAST32_MAX / x) {
+				return false;
+			}
+		}
+	}
+
+	if (result) {
+		*result = x * y;
+	}
+	return true;
+#endif
+}
+
+/* Compute the product of three int_fast32_t integers with overflow checking. */
+inline static bool jas_safe_intfast32_mul3(int_fast32_t a, int_fast32_t b,
+  int_fast32_t c, int_fast32_t *result)
+{
+	int_fast32_t tmp;
+	if (!jas_safe_intfast32_mul(a, b, &tmp) ||
+	  !jas_safe_intfast32_mul(tmp, c, &tmp)) {
+		return false;
+	}
+	if (result) {
+		*result = tmp;
+	}
+	return true;
+}
+
+/* Compute the sum of two int_fast32_t integers with overflow checking. */
+inline static bool jas_safe_intfast32_add(int_fast32_t x, int_fast32_t y,
+  int_fast32_t *result)
+{
+#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 5)
+	int_fast32_t result_buffer;
+	if (!result)
+		result = &result_buffer;
+	return !__builtin_add_overflow(x, y, result);
+#else
+	if ((y > 0 && x > INT_FAST32_MAX - y) ||
+	  (y < 0 && x < INT_FAST32_MIN - y)) {
+		return false;
+	}
+	if (result) {
+		*result = x + y;
+	}
+	return true;
+#endif
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_seq.h
@@ -1,0 +1,463 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_seq.h
+ * @brief Sequence/Matrix Library
+ */
+
+#ifndef JAS_SEQ_H
+#define JAS_SEQ_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h> /* IWYU pragma: keep */
+
+#include <jasper/jas_types.h>
+#include <jasper/jas_math.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* This matrix is a reference to another matrix. */
+#define JAS_MATRIX_REF	0x0001
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* An element in a sequence. */
+#ifdef JAS_ENABLE_32BIT
+typedef int_least32_t jas_seqent_t;
+#define PRIjas_seqent PRIiLEAST32
+#else
+typedef int_fast32_t jas_seqent_t;
+#define PRIjas_seqent PRIiFAST32
+#endif
+
+/* An element in a matrix. */
+#ifdef JAS_ENABLE_32BIT
+typedef int_least32_t jas_matent_t;
+#else
+typedef int_fast32_t jas_matent_t;
+#endif
+
+#ifdef JAS_ENABLE_32BIT
+typedef int_least32_t jas_matind_t;
+#else
+typedef int_fast32_t jas_matind_t;
+#endif
+
+/* Matrix. */
+
+typedef struct {
+
+	/* Additional state information. */
+	int flags_;
+
+	/* The starting horizontal index. */
+	jas_matind_t xstart_;
+
+	/* The starting vertical index. */
+	jas_matind_t ystart_;
+
+	/* The ending horizontal index. */
+	jas_matind_t xend_;
+
+	/* The ending vertical index. */
+	jas_matind_t yend_;
+
+	/* The number of rows in the matrix. */
+	jas_matind_t numrows_;
+
+	/* The number of columns in the matrix. */
+	jas_matind_t numcols_;
+
+	/* Pointers to the start of each row. */
+	jas_seqent_t **rows_;
+
+	/* The allocated size of the rows array. */
+	int_fast32_t maxrows_;
+
+	/* The matrix data buffer. */
+	jas_seqent_t *data_;
+
+	/* The allocated size of the data array. */
+	int_fast32_t datasize_;
+
+} jas_matrix_t;
+
+typedef jas_matrix_t jas_seq2d_t;
+typedef jas_matrix_t jas_seq_t;
+
+/******************************************************************************\
+* Functions/macros for matrix class.
+\******************************************************************************/
+
+/* Get the number of rows. */
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_matrix_numrows(const jas_matrix_t *matrix)
+{
+	return matrix->numrows_;
+}
+
+/* Get the number of columns. */
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_matrix_numcols(const jas_matrix_t *matrix)
+{
+	return matrix->numcols_;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_matrix_size(const jas_matrix_t *matrix)
+{
+	return jas_matrix_numcols(matrix) * jas_matrix_numrows(matrix);
+}
+
+JAS_ATTRIBUTE_PURE
+static inline bool jas_matrix_empty(const jas_matrix_t *matrix)
+{
+	return jas_matrix_numcols(matrix) == 0 || jas_matrix_numrows(matrix) == 0;
+}
+
+/* Get a matrix element. */
+JAS_ATTRIBUTE_PURE
+static inline jas_seqent_t jas_matrix_get(const jas_matrix_t *matrix, jas_matind_t i, jas_matind_t j)
+{
+	return matrix->rows_[i][j];
+}
+
+/* Set a matrix element. */
+static inline void jas_matrix_set(jas_matrix_t *matrix, jas_matind_t i, jas_matind_t j, jas_seqent_t v)
+{
+	matrix->rows_[i][j] = v;
+}
+
+/* Get an element from a matrix that is known to be a row or column vector. */
+JAS_ATTRIBUTE_PURE
+static inline jas_seqent_t jas_matrix_getv(const jas_matrix_t *matrix, jas_matind_t i)
+{
+	return matrix->numrows_ == 1
+		? matrix->rows_[0][i]
+		: matrix->rows_[i][0];
+}
+
+/* Set an element in a matrix that is known to be a row or column vector. */
+static inline void jas_matrix_setv(jas_matrix_t *matrix, jas_matind_t i, jas_seqent_t v)
+{
+	if (matrix->numrows_ == 1)
+		matrix->rows_[0][i] = v;
+	else
+		matrix->rows_[i][0] = v;
+}
+
+/* Get the address of an element in a matrix. */
+JAS_ATTRIBUTE_PURE
+static inline jas_seqent_t *jas_matrix_getref(const jas_matrix_t *matrix, jas_matind_t i, jas_matind_t j)
+{
+	return &matrix->rows_[i][j];
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_seqent_t *jas_matrix_getvref(const jas_matrix_t *matrix, jas_matind_t i)
+{
+	return matrix->numrows_ > 1
+		? jas_matrix_getref(matrix, i, 0)
+		: jas_matrix_getref(matrix, 0, i);
+}
+
+/* Create a matrix with the specified dimensions. */
+JAS_DLLEXPORT jas_matrix_t *jas_matrix_create(jas_matind_t numrows, jas_matind_t numcols);
+
+/* Destroy a matrix. */
+JAS_DLLEXPORT void jas_matrix_destroy(jas_matrix_t *matrix);
+
+/* Resize a matrix.  The previous contents of the matrix are lost. */
+JAS_DLLEXPORT int jas_matrix_resize(jas_matrix_t *matrix, jas_matind_t numrows, jas_matind_t numcols);
+
+JAS_DLLEXPORT int jas_matrix_output(jas_matrix_t *matrix, FILE *out);
+
+/* Create a matrix that references part of another matrix. */
+JAS_DLLEXPORT int jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, jas_matind_t r0,
+  jas_matind_t c0, jas_matind_t r1, jas_matind_t c1);
+
+/* Create a matrix that is a reference to a row of another matrix. */
+static inline int jas_matrix_bindrow(jas_matrix_t *mat0, jas_matrix_t *mat1, jas_matind_t r)
+{
+	return jas_matrix_bindsub(mat0, mat1, r, 0, r, mat1->numcols_ - 1);
+}
+
+/* Create a matrix that is a reference to a column of another matrix. */
+static inline int jas_matrix_bindcol(jas_matrix_t *mat0, jas_matrix_t *mat1, jas_matind_t c)
+{
+	return jas_matrix_bindsub(mat0, mat1, 0, c, mat1->numrows_ - 1, c);
+}
+
+/* Clip the values of matrix elements to the specified range. */
+JAS_DLLEXPORT void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,
+  jas_seqent_t maxval);
+
+/* Arithmetic shift left of all elements in a matrix. */
+JAS_DLLEXPORT void jas_matrix_asl(jas_matrix_t *matrix, unsigned n);
+
+/* Arithmetic shift right of all elements in a matrix. */
+JAS_DLLEXPORT void jas_matrix_asr(jas_matrix_t *matrix, unsigned n);
+
+/* Almost-but-not-quite arithmetic shift right of all elements in a matrix. */
+JAS_DLLEXPORT void jas_matrix_divpow2(jas_matrix_t *matrix, unsigned n);
+
+/* Set all elements of a matrix to the specified value. */
+JAS_DLLEXPORT void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val);
+
+/* The spacing between rows of a matrix. */
+JAS_ATTRIBUTE_PURE
+static inline size_t jas_matrix_rowstep(const jas_matrix_t *matrix)
+{
+	return matrix->numrows_ > 1
+		? (size_t)(matrix->rows_[1] - matrix->rows_[0])
+		: 0u;
+}
+
+/* The spacing between columns of a matrix. */
+JAS_ATTRIBUTE_PURE
+static inline size_t jas_matrix_step(const jas_matrix_t *matrix)
+{
+	return matrix->numrows_ > 1
+		? jas_matrix_rowstep(matrix)
+		: 1;
+}
+
+/* Compare two matrices for equality. */
+JAS_DLLEXPORT int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1);
+
+JAS_DLLEXPORT jas_matrix_t *jas_matrix_copy(jas_matrix_t *x);
+
+JAS_DLLEXPORT jas_matrix_t *jas_matrix_input(FILE *);
+
+JAS_ATTRIBUTE_CONST
+static inline jas_seqent_t jas_seqent_asl(jas_seqent_t x, unsigned n)
+{
+#ifdef JAS_ENABLE_32BIT
+	return jas_least32_asl(x, n);
+#else
+	return jas_fast32_asl(x, n);
+#endif
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jas_seqent_t jas_seqent_asr(jas_seqent_t x, unsigned n)
+{
+#ifdef JAS_ENABLE_32BIT
+	return jas_least32_asr(x, n);
+#else
+	return jas_fast32_asr(x, n);
+#endif
+}
+
+/******************************************************************************\
+* Functions/macros for 2-D sequence class.
+\******************************************************************************/
+
+JAS_DLLEXPORT jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x);
+
+JAS_DLLEXPORT jas_matrix_t *jas_seq2d_create(jas_matind_t xstart, jas_matind_t ystart,
+  jas_matind_t xend, jas_matind_t yend);
+
+static inline void jas_seq2d_destroy(jas_seq2d_t *s)
+{
+	jas_matrix_destroy(s);
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_seq2d_xstart(const jas_seq2d_t *s)
+{
+	return s->xstart_;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_seq2d_ystart(const jas_seq2d_t *s)
+{
+	return s->ystart_;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_seq2d_xend(const jas_seq2d_t *s)
+{
+	return s->xend_;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_seq2d_yend(const jas_seq2d_t *s)
+{
+	return s->yend_;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_seqent_t *jas_seq2d_getref(const jas_seq2d_t *s, jas_matind_t x, jas_matind_t y)
+{
+	return jas_matrix_getref(s, y - s->ystart_, x - s->xstart_);
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_seqent_t jas_seq2d_get(const jas_seq2d_t *s, jas_matind_t x, jas_matind_t y)
+{
+	return jas_matrix_get(s, y - s->ystart_, x - s->xstart_);
+}
+
+JAS_ATTRIBUTE_PURE
+static inline size_t jas_seq2d_rowstep(const jas_seq2d_t *s)
+{
+	return jas_matrix_rowstep(s);
+}
+
+JAS_ATTRIBUTE_PURE
+static inline unsigned jas_seq2d_width(const jas_seq2d_t *s)
+{
+	return (unsigned)(s->xend_ - s->xstart_);
+}
+
+JAS_ATTRIBUTE_PURE
+static inline unsigned jas_seq2d_height(const jas_seq2d_t *s)
+{
+	return (unsigned)(s->yend_ - s->ystart_);
+}
+
+static inline void jas_seq2d_setshift(jas_seq2d_t *s, jas_matind_t x, jas_matind_t y)
+{
+	s->xstart_ = x;
+	s->ystart_ = y;
+	s->xend_ = s->xstart_ + s->numcols_;
+	s->yend_ = s->ystart_ + s->numrows_;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_seq2d_size(const jas_seq2d_t *s)
+{
+	return jas_seq2d_width(s) * jas_seq2d_height(s);
+}
+
+JAS_ATTRIBUTE_PURE
+static inline bool jas_seq2d_empty(const jas_seq2d_t *s)
+{
+	return jas_seq2d_width(s) == 0 || jas_seq2d_height(s) == 0;
+}
+
+JAS_DLLEXPORT int jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, jas_matind_t xstart,
+  jas_matind_t ystart, jas_matind_t xend, jas_matind_t yend);
+
+/******************************************************************************\
+* Functions/macros for 1-D sequence class.
+\******************************************************************************/
+
+static inline jas_seq_t *jas_seq_create(jas_matind_t start, jas_matind_t end)
+{
+	return jas_seq2d_create(start, 0, end, 1);
+}
+
+static inline void jas_seq_destroy(jas_seq_t *seq)
+{
+	jas_seq2d_destroy(seq);
+}
+
+static inline void jas_seq_set(jas_seq_t *seq, jas_matind_t i, jas_seqent_t v)
+{
+	seq->rows_[0][i - seq->xstart_] = v;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_seqent_t *jas_seq_getref(const jas_seq_t *seq, jas_matind_t i)
+{
+	return &seq->rows_[0][i - seq->xstart_];
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_seqent_t jas_seq_get(const jas_seq_t *seq, jas_matind_t i)
+{
+	return seq->rows_[0][i - seq->xstart_];
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_seq_start(const jas_seq_t *seq)
+{
+	return seq->xstart_;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline jas_matind_t jas_seq_end(const jas_seq_t *seq)
+{
+	return seq->xend_;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_stream.h
@@ -1,0 +1,1047 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_stream.h
+ * @brief I/O Stream Class
+ */
+
+#ifndef JAS_STREAM_H
+#define JAS_STREAM_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h> /* IWYU pragma: export */
+#include <jasper/jas_types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * @addtogroup iostreams
+ * @{
+ */
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* On most UNIX systems, we probably need to define O_BINARY ourselves. */
+#ifndef O_BINARY
+#define O_BINARY	0
+#endif
+
+/*
+ * Stream open flags.
+ */
+
+/* The stream was opened for reading. */
+#define JAS_STREAM_READ	0x0001
+/* The stream was opened for writing. */
+#define JAS_STREAM_WRITE	0x0002
+/* The stream was opened for appending. */
+#define JAS_STREAM_APPEND	0x0004
+/* The stream was opened in binary mode. */
+#define JAS_STREAM_BINARY	0x0008
+/* The stream should be created/truncated. */
+#define JAS_STREAM_CREATE	0x0010
+
+/*
+ * Stream buffering flags.
+ */
+
+/* The stream is unbuffered. */
+#define JAS_STREAM_UNBUF	0x0000
+/* The stream is line buffered. */
+#define JAS_STREAM_LINEBUF	0x0001
+/* The stream is fully buffered. */
+#define JAS_STREAM_FULLBUF	0x0002
+/* The buffering mode mask. */
+#define	JAS_STREAM_BUFMODEMASK	0x000f
+
+/* The memory associated with the buffer needs to be deallocated when the
+  stream is destroyed. */
+#define JAS_STREAM_FREEBUF	0x0008
+/* The buffer is currently being used for reading. */
+#define JAS_STREAM_RDBUF	0x0010
+/* The buffer is currently being used for writing. */
+#define JAS_STREAM_WRBUF	0x0020
+
+/*
+ * Stream error flags.
+ */
+
+/* The end-of-file has been encountered (on reading). */
+#define JAS_STREAM_EOF	0x0001
+/* An I/O error has been encountered on the stream. */
+#define JAS_STREAM_ERR	0x0002
+/* The read/write limit has been exceeded. */
+#define	JAS_STREAM_RWLIMIT	0x0004
+/* The error mask. */
+#define JAS_STREAM_ERRMASK \
+	(JAS_STREAM_EOF | JAS_STREAM_ERR | JAS_STREAM_RWLIMIT)
+
+/*
+ * Other miscellaneous constants.
+ */
+
+/* The default buffer size (for fully-buffered operation). */
+#define JAS_STREAM_BUFSIZE	8192
+/* The default permission mask for file creation. */
+#define JAS_STREAM_PERMS	0666
+
+/* The maximum number of characters that can always be put back on a stream. */
+#define	JAS_STREAM_MAXPUTBACK	16
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/*
+ * Generic file object.
+ */
+
+typedef void jas_stream_obj_t;
+
+/*
+ * Generic file object operations.
+ */
+
+typedef struct {
+
+	/* Read characters from a file object. */
+	int (*read_)(jas_stream_obj_t *obj, char *buf, unsigned cnt);
+
+	/* Write characters to a file object. */
+	int (*write_)(jas_stream_obj_t *obj, const char *buf, unsigned cnt);
+
+	/* Set the position for a file object. */
+	long (*seek_)(jas_stream_obj_t *obj, long offset, int origin);
+
+	/* Close a file object. */
+	int (*close_)(jas_stream_obj_t *obj);
+
+} jas_stream_ops_t;
+
+/*
+ * Stream object.
+ */
+
+typedef struct {
+
+	/* The mode in which the stream was opened. */
+	int openmode_;
+
+	/* The buffering mode. */
+	int bufmode_;
+
+	/* The stream status. */
+	int flags_;
+
+	/* The start of the buffer area to use for reading/writing. */
+	jas_uchar *bufbase_;
+
+	/* The start of the buffer area excluding the extra initial space for
+	  character putback. */
+	jas_uchar *bufstart_;
+
+	/* The buffer size. */
+	int bufsize_;
+
+	/* The current position in the buffer. */
+	jas_uchar *ptr_;
+
+	/* The number of characters that must be read/written before
+	the buffer needs to be filled/flushed. */
+	int cnt_;
+
+	/* A trivial buffer to be used for unbuffered operation. */
+	jas_uchar tinybuf_[JAS_STREAM_MAXPUTBACK + 1];
+
+	/* The operations for the underlying stream file object. */
+	const jas_stream_ops_t *ops_;
+
+	/* The underlying stream file object. */
+	jas_stream_obj_t *obj_;
+
+	/* The number of characters read/written. */
+	long rwcnt_;
+
+	/* The maximum number of characters that may be read/written. */
+	long rwlimit_;
+
+} jas_stream_t;
+
+/*
+ * Regular file object.
+ */
+
+/*
+ * File descriptor file object.
+ */
+typedef struct {
+	int fd;
+	int flags;
+	char pathname[L_tmpnam + 1];
+} jas_stream_fileobj_t;
+
+/* Delete underlying file object upon stream close. */
+#define	JAS_STREAM_FILEOBJ_DELONCLOSE	0x01
+/* Do not close underlying file object upon stream close. */
+#define JAS_STREAM_FILEOBJ_NOCLOSE	0x02
+
+/*
+ * Memory file object.
+ */
+
+typedef struct {
+
+	/* The data associated with this file. */
+	jas_uchar *buf_;
+
+	/* The allocated size of the buffer for holding file data. */
+	size_t bufsize_;
+
+	/* The length of the file. */
+	uint_fast32_t len_;
+
+	/* The seek position. */
+	uint_fast32_t pos_;
+
+	/* Is the buffer growable? */
+	int growable_;
+
+	/* Was the buffer allocated internally? */
+	int myalloc_;
+
+} jas_stream_memobj_t;
+
+/******************************************************************************\
+* Macros/functions for opening and closing streams.
+\******************************************************************************/
+
+/*!
+@brief Open a file as a stream.
+
+@param filename
+A pointer to the pathname of the file to be opened.
+@param mode
+A pointer to the string specifying the open mode.
+The open mode is similar to that used by the fopen function in the
+C standard library.
+
+@return
+Upon success, a pointer to the opened stream is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_DLLEXPORT
+jas_stream_t *jas_stream_fopen(const char *filename, const char *mode);
+
+/*!
+@brief Open a memory buffer as a stream.
+
+@param buffer
+A pointer to the buffer to be used to store stream data.
+@param buffer_size
+The size of the buffer.
+
+@details
+<ul>
+<li>
+If buffer is 0 and buffer_size > 0:
+a buffer is dynamically allocated with size buffer_size and this buffer is
+not growable.
+<li>
+If buffer is 0 and buffer_size is 0:
+a buffer is dynamically allocated whose size will automatically grow to
+accommodate the amount of data written.
+<li>
+If buffer is not 0:
+buffer_size (which, in this case, is not currently allowed to be zero) is
+the size of the (nongrowable) buffer pointed to by buffer.
+</ul>
+
+@warning
+TODO/FIXME: The type of the buffer_size parameter will be
+changed to size_t in the future.
+
+@warning
+TODO/FIXME:
+In a later release, this function will be changed to have the same
+prototype as jas_stream_memopen2, at which point jas_stream_memopen2
+will be removed.
+*/
+JAS_DLLEXPORT
+jas_stream_t *jas_stream_memopen(char *buffer, int buffer_size);
+
+/*!
+@warning
+This function will be renamed jas_stream_memopen in a future release.
+Do not use this function.
+*/
+JAS_DLLEXPORT
+jas_stream_t *jas_stream_memopen2(char *buffer, size_t buffer_size);
+
+/*!
+@brief Open a file descriptor as a stream.
+
+@param fd
+The file descriptor of the file to open as a stream.
+@param mode
+A pointer to a string specifying the open mode.
+The format of this string is similar to that of the fdopen function
+in the C standard library.
+
+@return
+Upon success, a pointer to the opened stream is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_DLLEXPORT
+jas_stream_t *jas_stream_fdopen(int fd, const char *mode);
+
+/*!
+@brief Open a stdio (i.e., C standard library) stream as a stream.
+
+@param path
+A pointer to a string containing the path of the filename associated
+with the stdio stream.
+@param mode
+A pointer to a string containing the open mode to be used for the
+(JasPer) stream.
+This string is similar to that used by the fdopen function in the
+C standard library.
+@param fp
+A pointer to the stdio stream.
+
+@details
+It is unspecified whether the open mode specified by mode can be
+changed from the open mode used for opening the stdio stream.
+
+@return
+Upon success, a pointer to the opened stream is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_DLLEXPORT
+jas_stream_t *jas_stream_freopen(const char *path, const char *mode, FILE *fp);
+
+/*!
+@brief Open a temporary file as a stream.
+
+@details
+A temporary file is created and opened as a stream.
+The temporary file is deleted when closed via jas_stream_close().
+Some operating systems provide a mechanism for ensuring that a file
+is removed when closed.
+Such functionality may be used by the implementation when available.
+
+@return
+Upon success, a pointer to the opened stream is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_DLLEXPORT jas_stream_t *jas_stream_tmpfile(void);
+
+/*!
+@brief Close a stream.
+
+@param stream
+A (nonnull) pointer to the stream to be closed.
+
+@details
+The close operation will implicitly flush any pending output
+to the stream before closing.
+If such a flush operation fails, this will be reflected in
+the return value of this function.
+For many systems, it is likely that the main reason that this function
+can fail is due to an I/O error when flushing buffered output.
+
+@return
+If no errors are encountered when closing the stream, 0 is returned.
+Otherwise, a nonzero value is returned.
+*/
+JAS_DLLEXPORT
+int jas_stream_close(jas_stream_t *stream);
+
+/******************************************************************************\
+* Macros/functions for getting/setting the stream state.
+\******************************************************************************/
+
+/*!
+@brief Get the EOF indicator for a stream.
+
+@param stream
+The stream whose EOF indicator is to be queried.
+
+@return
+The value of the EOF indicator is returned.
+A nonzero value indicates that the stream has encountered EOF.
+*/
+#define jas_stream_eof(stream) \
+	(((stream)->flags_ & JAS_STREAM_EOF) != 0)
+
+/*!
+@brief Get the error indicator for a stream.
+@param stream
+The stream whose error indicator is to be queried.
+@return
+The value of the error indicator is returned.
+A nonzero value indicates that the stream has encountered an error
+of some type (such as an I/O error).
+Note that EOF is not an error.
+*/
+#define jas_stream_error(stream) \
+	(((stream)->flags_ & JAS_STREAM_ERR) != 0)
+
+/*!
+@brief Clear the error indicator for a stream.
+@param stream
+The stream whose error indicator is to be cleared.
+
+@todo
+TODO/FIXME: Should this macro evaluate to void?
+*/
+#define jas_stream_clearerr(stream) \
+	((stream)->flags_ &= ~(JAS_STREAM_ERR | JAS_STREAM_EOF))
+
+/*!
+@brief Get the read/write limit for a stream.
+@param stream
+A pointer to the stream whose read/write limit is to be queried.
+@return
+The read/write limit for the stream is returned.
+This operation cannot fail.
+A negative read/write limit indicates no limit (i.e., an limit that is
+effectively infinite).
+*/
+#define	jas_stream_getrwlimit(stream) \
+	(((const jas_stream_t *)(stream))->rwlimit_)
+
+/*!
+@brief Set the read/write limit for a stream.
+@param stream
+A pointer to the stream whose read/write limit is to be set.
+@param rwlimit
+The new value for the read/write limit.
+
+@details
+A negative read/write limit is treated as if it were infinity
+(i.e., there is no read/write limit).
+
+@return
+The old read/write limit is returned.
+*/
+JAS_DLLEXPORT long jas_stream_setrwlimit(jas_stream_t *stream, long rwlimit);
+
+/*!
+@brief Get the read/write count for a stream.
+
+@param stream
+A pointer to the stream whose read/write count is to be queried.
+
+@return
+The read/write count is returned.
+This operation cannot fail.
+*/
+#define	jas_stream_getrwcount(stream) \
+	(((const jas_stream_t *)(stream))->rwcnt_)
+
+/*!
+@brief Set the read/write count for a stream.
+@param stream
+A pointer to the stream whose read/write count is to be set.
+@param rw_count
+The new value for the read/write count.
+@return
+The old value of the read/write count is returned.
+This operation cannot fail.
+@todo
+TODO/FIXME: Should this macro evaluate to void?
+*/
+JAS_DLLEXPORT long jas_stream_setrwcount(jas_stream_t *stream, long rw_count);
+
+/******************************************************************************\
+* Macros/functions for I/O.
+\******************************************************************************/
+
+/* Read a character from a stream. */
+#ifndef NDEBUG
+/*!
+@brief jas_stream_getc
+Read a character from a stream.
+*/
+#define	jas_stream_getc(stream)	jas_stream_getc_func(stream)
+#else
+#define jas_stream_getc(stream)	jas_stream_getc_macro(stream)
+#endif
+
+/* Write a character to a stream. */
+#ifndef NDEBUG
+/*!
+@brief jas_stream_putc
+Write a character to a stream.
+*/
+#define jas_stream_putc(stream, c)	jas_stream_putc_func(stream, c)
+#else
+#define jas_stream_putc(stream, c)	jas_stream_putc_macro(stream, c)
+#endif
+
+/*!
+@brief Read characters from a stream into a buffer.
+
+@param stream
+A pointer to the stream from which to read data.
+@param buffer
+A pointer to the start of the buffer.
+@param count
+A count of the number of characters to read (nominally).
+
+@details
+If @c count is zero, the function has no effect (and therefore cannot fail).
+Otherwise, the function attempts to read @c count characters from the
+stream @c stream into the buffer starting at @c buffer.
+The number of characters read can be less than @c count, due to
+end-of-file (EOF) or an I/O error.
+
+@return
+The number of characters read is returned.
+In the case that the number of characters read is less than @c count,
+jas_stream_eof() and/or jas_stream_error() must be used
+to distinguish between:
+<ol>
+<li>a failure due to an I/O error
+<li>a failure due to the read/write limit being exceeded
+<li>EOF.
+</ol>
+TODO/CHECK: can items 1 and 2 be distinguished currently?
+
+@warning
+TODO/FIXME/CHECK: jas_stream_error should be true if RWLIMIT exceeded?
+or need a jas_stream_rwlimit predicate?
+
+@warning
+TODO/FIXME: In the future, the type of the count parameter and the
+return type will be changed to size_t.
+*/
+JAS_DLLEXPORT
+unsigned jas_stream_read(jas_stream_t *stream, void *buffer, unsigned count);
+
+/*!
+@brief Attempt to retrieve one or more pending characters of input
+from a stream into a buffer
+without actually removing the characters from the stream.
+
+@param stream
+A pointer to the stream from which to retrieve pending input.
+@param buffer
+A pointer to the start of the buffer.
+@param count
+A count of how many characters to retrieve.
+
+@details
+The extent to which one can peek into the stream is limited.
+Therefore, this function can fail if count is sufficiently large.
+
+@return
+Returns the number of bytes copied to the given buffer, or 0 on error
+or EOF.
+
+@warning
+TODO/FIXME: peeking at EOF should be distinguishable from an I/O error
+*/
+JAS_DLLEXPORT
+unsigned jas_stream_peek(jas_stream_t *stream, void *buffer, size_t count);
+
+/*!
+@brief Write characters from a buffer to a stream.
+@param stream
+A pointer to the stream to which to write data.
+@param buffer
+A pointer to the start of the buffer.
+@param count
+A count of the number of characters to write.
+
+@details
+If @c count is zero, the function has no effect (and therefore cannot fail).
+Otherwise, the function will attempt to write @c count characters
+from the buffer starting at @c buffer to the stream @c stream.
+The number of characters written can be less than @c count due to
+an I/O error or the read/write limit being exceeded.
+
+@return
+Upon success, the number of characters successfully written is returned.
+If an error occurs, the value returned will be less than @c count.
+The jas_stream_error() and jas_stream_rwlimit() function (TODO/CHECK: the latter
+of which does not currently exist?) can be used to distinguish between:
+<ol>
+<li>failure due to an I/O error
+<li>failure due to the read/write limit being exceeded
+</ol>
+
+@warning
+TODO/FIXME:
+The type of the count parameter should be size_t.
+The return type should be size_t.
+*/
+JAS_DLLEXPORT
+unsigned jas_stream_write(jas_stream_t *stream, const void *buffer,
+  unsigned count);
+
+/*!
+@brief Write formatted output to a stream.
+
+@param stream
+A pointer to the stream to which to write output.
+@param format
+A pointer to a format string similar to the printf function in the C standard
+library.
+
+@details
+The function prints the information associated with the format string
+to the specified stream.
+
+@return
+Upon success, the number of characters output to the stream is returned.
+If an error is encountered, a negative value is returned.
+
+@todo
+I think that the return type of int is okay here.
+It is consistent with printf and friends.
+*/
+JAS_DLLEXPORT
+int jas_stream_printf(jas_stream_t *stream, const char *format, ...);
+
+/*!
+@brief Write a string to a stream.
+
+@param stream
+A pointer to the stream to which the string should be written.
+@param s
+A pointer to a null-terminated string for output.
+
+@details
+The null character is not output.
+
+@return
+Upon success, a nonnegative value is returned.
+Upon failure, a negative value is returned.
+*/
+JAS_DLLEXPORT int jas_stream_puts(jas_stream_t *stream, const char *s);
+
+/*!
+@brief Read a line of input from a stream.
+
+@param stream
+A pointer to the stream from which to read input.
+@param buffer
+A pointer to the start of the buffer to hold to input to be read.
+@param buffer_size
+The size of the buffer in characters.
+
+@details
+The function reads a line of input from a stream into a buffer.
+If a newline character is read, it is placed in the buffer.
+Since the buffer may be too small to hold the input,
+this operation can fail due to attempted buffer overrun.
+
+@return
+If the operation fails (e.g., due to an I/O error or attempted buffer overrun),
+a null pointer is returned.
+Otherwise, buffer is returned.
+*/
+JAS_DLLEXPORT char *
+jas_stream_gets(jas_stream_t *stream, char *buffer, int buffer_size);
+
+/*!
+@brief Look at the next character to be read from a stream without actually
+removing the character from the stream.
+
+@param stream
+A pointer to the stream to be examined.
+
+@details
+This function examines the next character that would be read from the
+stream and returns this character without actually removing it from the
+stream.
+
+@return
+If the peek operation fails (e.g., due to EOF or I/O error),
+EOF is returned.
+Otherwise, the character that would be next read from the stream
+is returned.
+*/
+#define	jas_stream_peekc(stream) \
+	(((stream)->cnt_ <= 0) ? jas_stream_fillbuf(stream, 0) : \
+	  ((int)(*(stream)->ptr_)))
+
+/*!
+@brief Put a character back on a stream.
+
+@param stream
+A pointer to the stream to which the character should be put back.
+@param c
+The character to put back.
+
+@details
+The character @c c (which was presumably read previously from the stream
+@c stream) is put back on the stream (as if it had not yet been read).
+In other words, this function undoes the effect of jas_stream_getc().
+It is unspecified what happens if the character put back was not the
+one originally read.
+The number of characters that can be pushed back onto the stream
+for subsequent reading is limited.
+Trying to push back too many characters on a stream will result in an error.
+The approximate limit is given by the value of JAS_STREAM_MAXPUTBACK.
+
+@return
+Upon success, zero is returned.
+If the specified character cannot be pushed back, a negative value is returned.
+*/
+JAS_DLLEXPORT int
+jas_stream_ungetc(jas_stream_t *stream, int c);
+
+/******************************************************************************\
+* Macros/functions for getting/setting the stream position.
+\******************************************************************************/
+
+/*!
+@brief Determine if stream supports seeking.
+
+@param stream
+A pointer to the stream to query.
+
+@details
+The function is a predicate that tests if the underlying file object
+supports seek operations.
+
+@return
+If the underlying file object supports seek operations, a (strictly)
+positive value is returned.
+Otherwise, 0 is returned.
+*/
+JAS_ATTRIBUTE_PURE JAS_DLLEXPORT
+int jas_stream_isseekable(jas_stream_t *stream);
+
+/*!
+@brief Set the current position within the stream.
+
+@param stream
+A pointer to the stream for which to set the current position.
+@param offset
+The new position for the stream.
+@param origin
+The origin to which this new position is relative.
+
+@details
+The origin can be SEEK_CUR, SEEK_SET, or SEEK_END
+in a similar fashion as the fseek function in the C standard library
+(and the lseek function in POSIX).
+
+@return
+Upon success, the new stream position is returned.
+Upon failure, a negative value is returned.
+*/
+JAS_DLLEXPORT
+long jas_stream_seek(jas_stream_t *stream, long offset, int origin);
+
+/*!
+@brief Get the current position within the stream.
+@param stream
+A pointer to the stream whose current position is to be queried.
+
+@details
+The current position of the stream is returned.
+
+@return
+Upon success, the current stream position is returned.
+If an error is encountered, a negative value is returned.
+*/
+JAS_ATTRIBUTE_PURE JAS_DLLEXPORT
+long jas_stream_tell(jas_stream_t *stream);
+
+/*!
+@brief Seek to the beginning of a stream.
+@param stream
+A pointer to the stream whose position is to be set.
+@details
+The stream position is set to the start of the stream.
+This function is equivalent to returning the value
+of jas_stream_seek(stream, 0, SEEK_SET).
+@return
+Upon success, the new stream position is returned.
+Otherwise, a negative value is returned.
+*/
+JAS_DLLEXPORT int jas_stream_rewind(jas_stream_t *stream);
+
+/******************************************************************************\
+* Macros/functions for flushing.
+\******************************************************************************/
+
+/*!
+@brief Flush any pending output to a stream.
+@param stream
+A pointer to the stream for which output should be flushed.
+@details
+The function flushes any buffered output to the underlying file object.
+@return
+Upon success, zero is returned.
+Otherwise, a negative value is returned.
+*/
+JAS_DLLEXPORT int jas_stream_flush(jas_stream_t *stream);
+
+/******************************************************************************\
+* Miscellaneous macros/functions.
+\******************************************************************************/
+
+/*!
+@brief Copy data from one stream to another.
+
+@param destination
+A pointer to the stream that is the destination for the copy.
+@param source
+A pointer to the stream that is the source for the copy.
+@param count
+The number of characters to copy.
+
+@details
+The function copies the specified number of characters from the
+source stream to the destination stream.
+
+@return
+Upon success, 0 is returned; otherwise, -1 is returned.
+
+@todo
+TODO/FIXME: count should probably be a size_t; return type ssize_t?
+*/
+JAS_DLLEXPORT int jas_stream_copy(jas_stream_t *destination, jas_stream_t *source, int count);
+
+/*!
+@brief Print a hex dump of data read from a stream.
+
+@param stream
+A pointer to the stream from which to read data.
+@param fp
+A pointer to a stdio stream (i.e., FILE) to which to print the hex dump.
+@param count
+The number of characters to include in the hex dump.
+
+@details
+This function prints a hex dump of data read from a stream to a
+stdio stream.
+This function is most likely to be useful for debugging.
+
+@return
+Upon success, 0 is returned.
+Otherwise, a negative value is returned.
+
+@todo
+TODO/FIXME: should count be unsigned int or size_t instead of int?
+*/
+JAS_DLLEXPORT
+int jas_stream_display(jas_stream_t *stream, FILE *fp, int count);
+
+/*!
+@brief Consume (i.e., discard) characters from stream.
+
+@param stream
+A pointer to the stream from which to discard data.
+@param count
+The number of characters to discard.
+
+@details
+This function reads and discards  the specified number of characters from the
+given stream.
+
+@return
+This function returns the number of characters read and discarded.
+If an error or EOF is encountered, the number of characters read
+will be less than count.
+To distinguish EOF from an I/O error, jas_stream_eof() and jas_stream_error()
+can be used.
+
+@warning
+TODO/FIXME: count be size_t and return type should be ssize_t
+*/
+JAS_DLLEXPORT int jas_stream_gobble(jas_stream_t *stream, int count);
+
+/*!
+@brief Write a fill character multiple times to a stream.
+
+@param stream
+A pointer to the stream to which to write.
+@param count
+The number of times to write the fill character to the stream.
+@param value
+The fill character.
+
+@details
+This function writes the given fill character to a stream a
+specified number of times.
+If a count of zero is specified, the function should have no effect.
+
+@return
+The number of times the fill character was written to the stream is
+returned.
+If this value is less than the specified count, an error must have
+occurred.
+
+@todo
+TODO: should the count be size_t; return type maybe size_t?
+*/
+JAS_DLLEXPORT int jas_stream_pad(jas_stream_t *stream, int count, int value);
+
+/*!
+@brief Get the size of the file associated with the specified stream.
+
+@param stream
+
+@details
+This function queries the size (i.e., length) of the underlying file object
+associated with the specified stream.
+The specified stream must be seekable.
+
+@return
+Upon success, the size of the stream is returned.
+If an error occurs, a negative value is returned.
+
+@warning
+TODO/FIXME: the return type should be ssize_t?
+*/
+JAS_ATTRIBUTE_PURE JAS_DLLEXPORT
+long jas_stream_length(jas_stream_t *stream);
+
+/******************************************************************************\
+* Internal functions.
+\******************************************************************************/
+
+/* The following functions are for internal use only!  If you call them
+directly, you will die a horrible, miserable, and painful death! */
+
+/* These prototypes need to be here for the sake of the stream_getc and
+stream_putc macros. */
+/* Library users must not invoke these functions directly. */
+JAS_DLLEXPORT int jas_stream_fillbuf(jas_stream_t *stream, int getflag);
+JAS_DLLEXPORT int jas_stream_flushbuf(jas_stream_t *stream, int c);
+JAS_DLLEXPORT int jas_stream_getc_func(jas_stream_t *stream);
+JAS_DLLEXPORT int jas_stream_putc_func(jas_stream_t *stream, int c);
+
+/* Read a character from a stream. */
+static inline int jas_stream_getc2(jas_stream_t *stream)
+{
+	if (--stream->cnt_ < 0)
+		return jas_stream_fillbuf(stream, 1);
+
+	++stream->rwcnt_;
+	return (int)(*stream->ptr_++);
+}
+
+static inline int jas_stream_getc_macro(jas_stream_t *stream)
+{
+	if (stream->flags_ & (JAS_STREAM_ERR | JAS_STREAM_EOF | JAS_STREAM_RWLIMIT))
+		return EOF;
+
+	if (stream->rwlimit_ >= 0 && stream->rwcnt_ >= stream->rwlimit_) {
+		stream->flags_ |= JAS_STREAM_RWLIMIT;
+		return EOF;
+	}
+
+	return jas_stream_getc2(stream);
+}
+
+/* Write a character to a stream. */
+static inline int jas_stream_putc2(jas_stream_t *stream, jas_uchar c)
+{
+	stream->bufmode_ |= JAS_STREAM_WRBUF;
+
+	if (--stream->cnt_ < 0)
+		return jas_stream_flushbuf(stream, c);
+	else {
+		++stream->rwcnt_;
+		return (int)(*stream->ptr_++ = c);
+	}
+}
+
+static inline int jas_stream_putc_macro(jas_stream_t *stream, jas_uchar c)
+{
+	if (stream->flags_ & (JAS_STREAM_ERR | JAS_STREAM_EOF | JAS_STREAM_RWLIMIT))
+	    return EOF;
+
+	if (stream->rwlimit_ >= 0 && stream->rwcnt_ >= stream->rwlimit_) {
+		stream->flags_ |= JAS_STREAM_RWLIMIT;
+		return EOF;
+	}
+
+	return jas_stream_putc2(stream, c);
+}
+
+/*!
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_string.h
@@ -1,0 +1,94 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_string.h
+ * @brief String Library
+ */
+
+#ifndef	JAS_STRING_H
+#define	JAS_STRING_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Copy a string (a la strdup). */
+JAS_DLLEXPORT char *jas_strdup(const char *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_types.h
@@ -1,0 +1,134 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jas_types.h
+ * @brief Primitive Types
+ */
+
+#ifndef JAS_TYPES_H
+#define JAS_TYPES_H
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#define INT_MAX 0x7fffffff
+#define UINT_FAST32_MAX 0xffffffff
+#define SIZE_MAX UINT_FAST32_MAX
+#define INT_FAST32_MIN ((s32int)0x80000000)
+#define INT_FAST32_MAX INT_MAX
+#define LONG_MAX INT_MAX
+
+typedef s8int int_least8_t;
+typedef s16int int_fast16_t;
+typedef s32int int_fast32_t;
+typedef s32int int_least32_t;
+typedef s64int int_fast64_t;
+
+typedef u8int uint_least8_t;
+typedef u8int uint_fast8_t;
+typedef u16int uint_fast16_t;
+typedef u16int uint_least16_t;
+typedef u32int uint_fast32_t;
+typedef u32int uint_least32_t;
+typedef u64int uint_least64_t;
+typedef u64int uint_fast64_t;
+
+typedef unsigned char jas_uchar;
+typedef unsigned int jas_uint;
+typedef unsigned long jas_ulong;
+typedef long long jas_longlong;
+typedef unsigned long long jas_ulonglong;
+
+typedef enum { false, true } bool;
+
+#define PRIxFAST32 "x"
+#define PRIxFAST16 PRIxFAST32
+#define PRIuFAST32 "u"
+#define PRIuFAST16 PRIuFAST32
+#define PRIiFAST32 "i"
+#define PRIiLEAST32 PRIiFAST32
+#define PRIxLEAST16 "x"
+#define PRIdPTR "lld"
+#define _HUGE_ENUF 1e+300
+#define INFINITY ((float)(_HUGE_ENUF * _HUGE_ENUF))
+
+/* The below macro is intended to be used for type casts.  By using this
+  macro, type casts can be easily located in the source code with
+  tools like "grep". */
+#define	JAS_CAST(t, e) \
+	((t) (e))
+
+/* The number of bits in the integeral type uint_fast32_t. */
+/* NOTE: This could underestimate the size on some exotic architectures. */
+#define JAS_UINTFAST32_NUMBITS (8 * sizeof(uint_fast32_t))
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jasper.h
@@ -1,0 +1,101 @@
+/*
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*!
+ * @file jasper.h
+ * @brief JasPer Main Header
+ */
+
+#ifndef JAS_JASPER_H
+#define JAS_JASPER_H
+
+// IWYU pragma: begin_exports
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#include <jasper/jas_types.h>
+
+#include <jasper/jas_init.h>
+#include <jasper/jas_cm.h>
+#include <jasper/jas_icc.h>
+#include <jasper/jas_fix.h>
+#include <jasper/jas_debug.h>
+#include <jasper/jas_image.h>
+#include <jasper/jas_math.h>
+#include <jasper/jas_malloc.h>
+#include <jasper/jas_seq.h>
+#include <jasper/jas_stream.h>
+#include <jasper/jas_string.h>
+
+#pragma lib "./libjp29.a"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+// IWYU pragma: end_exports
+
+#endif
--- /dev/null
+++ b/jp2.c
@@ -1,0 +1,97 @@
+#include <jasper/jasper.h>
+#include <draw.h>
+#include <memdraw.h>
+
+static void
+usage(void)
+{
+	fprint(2, "usage: %s < FILE.jp2 > FILE.pic\n", argv0);
+	exits("usage");
+}
+
+void
+main(int argc, char **argv)
+{
+	jas_stream_t *s;
+	jas_image_t *im;
+	jas_cmprof_t *cp;
+	int c, i, w, h, x, y;
+	jas_image_cmpttype_t comps[] = {
+		JAS_IMAGE_CT_RGB_R,
+		JAS_IMAGE_CT_RGB_G,
+		JAS_IMAGE_CT_RGB_B,
+	};
+	u8int *rgb;
+	long *b;
+	Memimage *m;
+
+	ARGBEGIN{
+	default:
+		usage();
+	}ARGEND
+
+	if(argc != 0)
+		usage();
+
+	memimageinit();
+	jas_init();
+
+	if((cp = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)) == nil){
+		werrstr("failed to create color space");
+		goto error;
+	}
+	if((s = jas_stream_fdopen(0, "rb")) == nil){
+		werrstr("failed to open");
+		goto error;
+	}
+	if((im = jas_image_decode(s, -1, "")) == nil){
+		werrstr("failed to decode: %r");
+		goto error;
+	}
+	jas_stream_close(s);
+	if((im = jas_image_chclrspc(im, cp, JAS_CMXFORM_INTENT_PER)) == nil){
+		werrstr("failed to change color space");
+		goto error;
+	}
+	w = jas_image_width(im);
+	h = jas_image_height(im);
+	if((b = malloc(w*h*sizeof(*b))) == nil){
+		werrstr("memory");
+		goto error;
+	}
+	if((rgb = malloc(w*h*3)) == nil){
+		werrstr("memory");
+		goto error;
+	}
+
+	for(i = 0; i < 3; i++){
+		if((c = jas_image_getcmptbytype(im, comps[i])) < 0){
+			werrstr("failed to get component R");
+			goto error;
+		}
+		if(jas_image_readcmpt2(im, c, 0, 0, w, h, b) < 0){
+			werrstr("read component failed");
+			goto error;
+		}
+		for(y = 0; y < h; y++){
+			for(x = 0; x < w; x++){
+				rgb[3*(y*w + x) + 2-i] = b[y*w + x];
+			}
+		}
+	}
+	jas_image_destroy(im);
+	free(b);
+
+	if((m = allocmemimage(Rect(0,0,w,h), RGB24)) == nil){
+		werrstr("memory");
+		goto error;
+	}
+	loadmemimage(m, m->r, rgb, w*h*3);
+	writememimage(1, m);
+	freememimage(m);
+
+	exits(nil);
+error:
+	fprint(2, "%r\n");
+	exits("error");
+}
--- /dev/null
+++ b/jp2_cod.c
@@ -1,0 +1,958 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JP2 Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jp2_cod.h"
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Function prototypes.
+\******************************************************************************/
+
+#define	ONES(n)	((1 << (n)) - 1)
+
+static const jp2_boxinfo_t *jp2_boxinfolookup(int type);
+
+static int jp2_getuint8(jas_stream_t *in, uint_fast8_t *val);
+static int jp2_getuint16(jas_stream_t *in, uint_fast16_t *val);
+static int jp2_getuint32(jas_stream_t *in, uint_fast32_t *val);
+static int jp2_getuint64(jas_stream_t *in, uint_fast64_t *val);
+static int jp2_putuint8(jas_stream_t *out, uint_fast8_t val);
+static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val);
+static int jp2_putuint32(jas_stream_t *out, uint_fast32_t val);
+static int jp2_putuint64(jas_stream_t *out, uint_fast64_t val);
+
+static int jp2_getint(jas_stream_t *in, int s, int n, int_fast32_t *val);
+
+static void jp2_box_dump(const jp2_box_t *box, FILE *out);
+
+static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_jp_putdata(const jp2_box_t *box, jas_stream_t *out);
+static int jp2_ftyp_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_ftyp_putdata(const jp2_box_t *box, jas_stream_t *out);
+static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_ihdr_putdata(const jp2_box_t *box, jas_stream_t *out);
+static void jp2_bpcc_destroy(jp2_box_t *box);
+static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_bpcc_putdata(const jp2_box_t *box, jas_stream_t *out);
+static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_colr_putdata(const jp2_box_t *box, jas_stream_t *out);
+static void jp2_colr_dumpdata(const jp2_box_t *box, FILE *out);
+static void jp2_colr_destroy(jp2_box_t *box);
+static void jp2_cdef_destroy(jp2_box_t *box);
+static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_cdef_putdata(const jp2_box_t *box, jas_stream_t *out);
+static void jp2_cdef_dumpdata(const jp2_box_t *box, FILE *out);
+static void jp2_cmap_destroy(jp2_box_t *box);
+static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_cmap_putdata(const jp2_box_t *box, jas_stream_t *out);
+static void jp2_cmap_dumpdata(const jp2_box_t *box, FILE *out);
+static void jp2_pclr_destroy(jp2_box_t *box);
+static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_pclr_putdata(const jp2_box_t *box, jas_stream_t *out);
+static void jp2_pclr_dumpdata(const jp2_box_t *box, FILE *out);
+
+/******************************************************************************\
+* Local data.
+\******************************************************************************/
+
+static const jp2_boxinfo_t jp2_boxinfos[] = {
+	{JP2_BOX_JP, 0, "JP",
+	  {0, 0, jp2_jp_getdata, jp2_jp_putdata, 0}},
+	{JP2_BOX_FTYP, 0, "FTYP",
+	  {0, 0, jp2_ftyp_getdata, jp2_ftyp_putdata, 0}},
+	{JP2_BOX_JP2H, JP2_BOX_SUPER, "JP2H",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_IHDR, 0, "IHDR",
+	  {0, 0, jp2_ihdr_getdata, jp2_ihdr_putdata, 0}},
+	{JP2_BOX_BPCC, 0, "BPCC",
+	  {0, jp2_bpcc_destroy, jp2_bpcc_getdata, jp2_bpcc_putdata, 0}},
+	{JP2_BOX_COLR, 0, "COLR",
+	  {0, jp2_colr_destroy, jp2_colr_getdata, jp2_colr_putdata, jp2_colr_dumpdata}},
+	{JP2_BOX_PCLR, 0, "PCLR",
+	  {0, jp2_pclr_destroy, jp2_pclr_getdata, jp2_pclr_putdata, jp2_pclr_dumpdata}},
+	{JP2_BOX_CMAP, 0, "CMAP",
+	  {0, jp2_cmap_destroy, jp2_cmap_getdata, jp2_cmap_putdata, jp2_cmap_dumpdata}},
+	{JP2_BOX_CDEF, 0, "CDEF",
+	  {0, jp2_cdef_destroy, jp2_cdef_getdata, jp2_cdef_putdata, jp2_cdef_dumpdata}},
+	{JP2_BOX_RES, JP2_BOX_SUPER, "RES",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_RESC, 0, "RESC",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_RESD, 0, "RESD",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_JP2C, JP2_BOX_NODATA, "JP2C",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_JP2I, 0, "JP2I",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_XML, 0, "XML",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_UUID, 0, "UUID",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_UINF, JP2_BOX_SUPER, "UINF",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_ULST, 0, "ULST",
+	  {0, 0, 0, 0, 0}},
+	{JP2_BOX_URL, 0, "URL",
+	  {0, 0, 0, 0, 0}},
+	{0, 0, 0, {0, 0, 0, 0, 0}},
+};
+
+static const jp2_boxinfo_t jp2_boxinfo_unk = {
+	0, 0, "Unknown", {0, 0, 0, 0, 0}
+};
+
+/******************************************************************************\
+* Box constructor.
+\******************************************************************************/
+
+static jp2_box_t *jp2_box_create0(void)
+{
+	jp2_box_t *box;
+	if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
+		return 0;
+	}
+	memset(box, 0, sizeof(jp2_box_t));
+	// Mark the box data as never having been constructed
+	// so that we will not errantly attempt to destroy it later.
+	box->ops = &jp2_boxinfo_unk.ops;
+	return box;
+}
+
+jp2_box_t *jp2_box_create(int type)
+{
+	const jp2_boxinfo_t *boxinfo = jp2_boxinfolookup(type);
+	assert(boxinfo != NULL);
+	if (boxinfo == &jp2_boxinfo_unk) {
+		// on error, jp2_boxinfolookup() returns &jp2_boxinfo_unk
+		return NULL;
+	}
+
+	jp2_box_t *box;
+	if (!(box = jp2_box_create0())) {
+		return 0;
+	}
+	box->type = type;
+	box->len = 0;
+	box->info = boxinfo;
+	box->ops = &boxinfo->ops;
+	return box;
+}
+
+/******************************************************************************\
+* Box destructor.
+\******************************************************************************/
+
+void jp2_box_destroy(jp2_box_t *box)
+{
+	if (box->ops->destroy) {
+		(*box->ops->destroy)(box);
+	}
+	jas_free(box);
+}
+
+static void jp2_bpcc_destroy(jp2_box_t *box)
+{
+	jp2_bpcc_t *bpcc = &box->data.bpcc;
+	if (bpcc->bpcs) {
+		jas_free(bpcc->bpcs);
+		bpcc->bpcs = 0;
+	}
+}
+
+static void jp2_cdef_destroy(jp2_box_t *box)
+{
+	jp2_cdef_t *cdef = &box->data.cdef;
+	if (cdef->ents) {
+		jas_free(cdef->ents);
+		cdef->ents = 0;
+	}
+}
+
+/******************************************************************************\
+* Box input.
+\******************************************************************************/
+
+jp2_box_t *jp2_box_get(jas_stream_t *in)
+{
+	jp2_box_t *box;
+	const jp2_boxinfo_t *boxinfo;
+	jas_stream_t *tmpstream;
+	uint_fast32_t len;
+	uint_fast64_t extlen;
+	bool dataflag;
+
+	tmpstream = 0;
+
+	if (!(box = jp2_box_create0())) {
+		goto error;
+	}
+	if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) {
+		goto error;
+	}
+	boxinfo = jp2_boxinfolookup(box->type);
+	box->info = boxinfo;
+	box->len = len;
+	JAS_DBGLOG(10, (
+	  "preliminary processing of JP2 box: "
+	  "type=%c%s%c (0x%08x); length=%"PRIuFAST32"\n",
+	  '"', boxinfo->name, '"', box->type, box->len
+	  ));
+	size_t hdrlen;
+	if (box->len == 1) {
+		JAS_DBGLOG(10, ("big length\n"));
+		if (jp2_getuint64(in, &extlen)) {
+			goto error;
+		}
+		if (extlen > 0xffffffffUL) {
+			jas_eprintf("warning: cannot handle large 64-bit box length\n");
+			goto error;
+		}
+		box->len = extlen;
+		hdrlen = JP2_BOX_HDRLEN(true);
+	} else {
+		hdrlen = JP2_BOX_HDRLEN(false);
+	}
+	if (box->len != 0 && box->len < 8) {
+		goto error;
+	}
+	if (box->len > 0x7fffffffUL) {
+		/* this limit is the largest value which can
+		   be passed to jas_stream_copy() without
+		   overflowing */
+		goto error;
+	}
+
+	dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
+
+	if (dataflag) {
+		if (box->len < hdrlen)
+			goto error;
+		box->datalen = box->len - hdrlen;
+
+		if (!(tmpstream = jas_stream_memopen(0, 0))) {
+			goto error;
+		}
+		if (jas_stream_copy(tmpstream, in, box->datalen)) {
+			jas_eprintf("cannot copy box data\n");
+			goto error;
+		}
+		jas_stream_rewind(tmpstream);
+
+		// From here onwards, the box data will need to be destroyed.
+		// So, initialize the box operations.
+		box->ops = &boxinfo->ops;
+
+		if (box->ops->getdata) {
+			if ((*box->ops->getdata)(box, tmpstream)) {
+				jas_eprintf("cannot parse box data\n");
+				goto error;
+			}
+		}
+		jas_stream_close(tmpstream);
+	}
+
+	if (jas_getdbglevel() >= 1) {
+		jp2_box_dump(box, stderr);
+	}
+
+	return box;
+
+error:
+	if (box) {
+		jp2_box_destroy(box);
+	}
+	if (tmpstream) {
+		jas_stream_close(tmpstream);
+	}
+	return 0;
+}
+
+static void jp2_box_dump(const jp2_box_t *box, FILE *out)
+{
+	const jp2_boxinfo_t *boxinfo = box->info;
+	assert(boxinfo);
+
+	fprintf(out, "JP2 box: ");
+	fprintf(out, "type=%c%s%c (0x%08"PRIxFAST32"); length=%"PRIuFAST32"\n", '"',
+	  boxinfo->name, '"', box->type, box->len);
+	if (box->ops->dumpdata) {
+		(*box->ops->dumpdata)(box, out);
+	}
+}
+
+static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+	jp2_jp_t *jp = &box->data.jp;
+	if (jp2_getuint32(in, &jp->magic)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jp2_ftyp_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+	if (box->datalen < 8)
+		return -1;
+
+	jp2_ftyp_t *ftyp = &box->data.ftyp;
+	unsigned int i;
+	if (jp2_getuint32(in, &ftyp->majver) || jp2_getuint32(in, &ftyp->minver)) {
+		return -1;
+	}
+	ftyp->numcompatcodes = (box->datalen - 8) / 4;
+	if (ftyp->numcompatcodes > JP2_FTYP_MAXCOMPATCODES) {
+		return -1;
+	}
+	for (i = 0; i < ftyp->numcompatcodes; ++i) {
+		if (jp2_getuint32(in, &ftyp->compatcodes[i])) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+	jp2_ihdr_t *ihdr = &box->data.ihdr;
+	if (jp2_getuint32(in, &ihdr->height) || jp2_getuint32(in, &ihdr->width) ||
+	  jp2_getuint16(in, &ihdr->numcmpts) || jp2_getuint8(in, &ihdr->bpc) ||
+	  jp2_getuint8(in, &ihdr->comptype) || jp2_getuint8(in, &ihdr->csunk) ||
+	  jp2_getuint8(in, &ihdr->ipr)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+	if (box->datalen > 0xffff)
+		/* excessive number of components - this is a
+		   pessimistic limit, because in jp2_ihdr_getdata(),
+		   it's a 16 bit integer */
+		return -1;
+
+	jp2_bpcc_t *bpcc = &box->data.bpcc;
+	unsigned int i;
+	bpcc->bpcs = 0;
+	bpcc->numcmpts = box->datalen;
+	if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts, sizeof(uint_fast8_t)))) {
+		return -1;
+	}
+	for (i = 0; i < bpcc->numcmpts; ++i) {
+		if (jp2_getuint8(in, &bpcc->bpcs[i])) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static void jp2_colr_dumpdata(const jp2_box_t *box, FILE *out)
+{
+	const jp2_colr_t *colr = &box->data.colr;
+	fprintf(out, "method=%d; pri=%d; approx=%d\n", (int)colr->method, (int)colr->pri, (int)colr->approx);
+	switch (colr->method) {
+	case JP2_COLR_ENUM:
+		fprintf(out, "csid=%d\n", (int)colr->csid);
+		break;
+	case JP2_COLR_ICC:
+		jas_memdump(out, colr->iccp, colr->iccplen);
+		break;
+	}
+}
+
+static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+	if (box->datalen < 3)
+		return -1;
+
+	jp2_colr_t *colr = &box->data.colr;
+	colr->csid = 0;
+	colr->iccp = 0;
+	colr->iccplen = 0;
+
+	if (jp2_getuint8(in, &colr->method) || jp2_getuint8(in, &colr->pri) ||
+	  jp2_getuint8(in, &colr->approx)) {
+		return -1;
+	}
+	switch (colr->method) {
+	case JP2_COLR_ENUM:
+		if (jp2_getuint32(in, &colr->csid)) {
+			return -1;
+		}
+		break;
+	case JP2_COLR_ICC:
+		colr->iccplen = box->datalen - 3;
+		if (colr->iccplen > 1024 * 1024)
+			/* refuse to read ICC profiles larger than 1
+			   MB (I have no idea how large ICC profiles
+			   can get, but I believe this limit might be
+			   very pessimistic and should be lowered
+			   further) */
+			return -1;
+		if (!(colr->iccp = jas_alloc2(colr->iccplen, sizeof(uint_fast8_t)))) {
+			return -1;
+		}
+		if (jas_stream_read(in, colr->iccp, colr->iccplen) != colr->iccplen) {
+			return -1;
+		}
+		break;
+	}
+	return 0;
+}
+
+static void jp2_cdef_dumpdata(const jp2_box_t *box, FILE *out)
+{
+	const jp2_cdef_t *cdef = &box->data.cdef;
+	unsigned int i;
+	for (i = 0; i < cdef->numchans; ++i) {
+		fprintf(out,
+		  "channo=%"PRIuFAST16"; type=%"PRIuFAST16"; assoc=%"PRIuFAST16"\n",
+		  cdef->ents[i].channo, cdef->ents[i].type, cdef->ents[i].assoc);
+	}
+}
+
+static void jp2_colr_destroy(jp2_box_t *box)
+{
+	jp2_colr_t *colr = &box->data.colr;
+	if (colr->iccp) {
+		jas_free(colr->iccp);
+	}
+}
+
+static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+	jp2_cdef_t *cdef = &box->data.cdef;
+	jp2_cdefchan_t *chan;
+	unsigned int channo;
+	cdef->ents = 0;
+	if (jp2_getuint16(in, &cdef->numchans)) {
+		return -1;
+	}
+	if (!(cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)))) {
+		return -1;
+	}
+	for (channo = 0; channo < cdef->numchans; ++channo) {
+		chan = &cdef->ents[channo];
+		if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) ||
+		  jp2_getuint16(in, &chan->assoc)) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Box output.
+\******************************************************************************/
+
+int jp2_box_put(jp2_box_t *box, jas_stream_t *out)
+{
+	jas_stream_t *tmpstream;
+	bool extlen;
+	bool dataflag;
+
+	tmpstream = 0;
+
+	dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
+
+	if (dataflag) {
+		if (!(tmpstream = jas_stream_memopen(0, 0))) {
+			goto error;
+		}
+		if (box->ops->putdata) {
+			if ((*box->ops->putdata)(box, tmpstream)) {
+				goto error;
+			}
+		}
+		box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
+		jas_stream_rewind(tmpstream);
+	}
+	extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
+	if (jp2_putuint32(out, extlen ? 1 : box->len)) {
+		goto error;
+	}
+	if (jp2_putuint32(out, box->type)) {
+		goto error;
+	}
+	if (extlen) {
+		if (jp2_putuint64(out, box->len)) {
+			goto error;
+		}
+	}
+
+	if (dataflag) {
+		if (jas_stream_copy(out, tmpstream, box->len -
+		  JP2_BOX_HDRLEN(false))) {
+			jas_eprintf("cannot copy box data\n");
+			goto error;
+		}
+		jas_stream_close(tmpstream);
+	}
+
+	return 0;
+
+error:
+
+	if (tmpstream) {
+		jas_stream_close(tmpstream);
+	}
+	return -1;
+}
+
+static int jp2_jp_putdata(const jp2_box_t *box, jas_stream_t *out)
+{
+	const jp2_jp_t *jp = &box->data.jp;
+	if (jp2_putuint32(out, jp->magic)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jp2_ftyp_putdata(const jp2_box_t *box, jas_stream_t *out)
+{
+	const jp2_ftyp_t *ftyp = &box->data.ftyp;
+	unsigned int i;
+	if (jp2_putuint32(out, ftyp->majver) || jp2_putuint32(out, ftyp->minver)) {
+		return -1;
+	}
+	for (i = 0; i < ftyp->numcompatcodes; ++i) {
+		if (jp2_putuint32(out, ftyp->compatcodes[i])) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static int jp2_ihdr_putdata(const jp2_box_t *box, jas_stream_t *out)
+{
+	const jp2_ihdr_t *ihdr = &box->data.ihdr;
+	if (jp2_putuint32(out, ihdr->height) || jp2_putuint32(out, ihdr->width) ||
+	  jp2_putuint16(out, ihdr->numcmpts) || jp2_putuint8(out, ihdr->bpc) ||
+	  jp2_putuint8(out, ihdr->comptype) || jp2_putuint8(out, ihdr->csunk) ||
+	  jp2_putuint8(out, ihdr->ipr)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jp2_bpcc_putdata(const jp2_box_t *box, jas_stream_t *out)
+{
+	const jp2_bpcc_t *bpcc = &box->data.bpcc;
+	unsigned int i;
+	for (i = 0; i < bpcc->numcmpts; ++i) {
+		if (jp2_putuint8(out, bpcc->bpcs[i])) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static int jp2_colr_putdata(const jp2_box_t *box, jas_stream_t *out)
+{
+	const jp2_colr_t *colr = &box->data.colr;
+	if (jp2_putuint8(out, colr->method) || jp2_putuint8(out, colr->pri) ||
+	  jp2_putuint8(out, colr->approx)) {
+		return -1;
+	}
+	switch (colr->method) {
+	case JP2_COLR_ENUM:
+		if (jp2_putuint32(out, colr->csid)) {
+			return -1;
+		}
+		break;
+	case JP2_COLR_ICC:
+		if (jas_stream_write(out, colr->iccp, colr->iccplen) != colr->iccplen)
+			return -1;
+		break;
+	}
+	return 0;
+}
+
+static int jp2_cdef_putdata(const jp2_box_t *box, jas_stream_t *out)
+{
+	const jp2_cdef_t *cdef = &box->data.cdef;
+	unsigned int i;
+
+	if (jp2_putuint16(out, cdef->numchans)) {
+		return -1;
+	}
+
+	for (i = 0; i < cdef->numchans; ++i) {
+		const jp2_cdefchan_t *ent = &cdef->ents[i];
+		if (jp2_putuint16(out, ent->channo) ||
+		  jp2_putuint16(out, ent->type) ||
+		  jp2_putuint16(out, ent->assoc)) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Input operations for primitive types.
+\******************************************************************************/
+
+static int jp2_getuint8(jas_stream_t *in, uint_fast8_t *val)
+{
+	int c;
+	if ((c = jas_stream_getc(in)) == EOF) {
+		return -1;
+	}
+	if (val) {
+		*val = c;
+	}
+	return 0;
+}
+
+static int jp2_getuint16(jas_stream_t *in, uint_fast16_t *val)
+{
+	jas_uchar buffer[2];
+	if (jas_stream_read(in, buffer, sizeof(buffer)) != sizeof(buffer))
+		return -1;
+	*val = (uint_fast16_t)buffer[0] << 8 | (uint_fast16_t)buffer[1];
+	return 0;
+}
+
+static int jp2_getuint32(jas_stream_t *in, uint_fast32_t *val)
+{
+	jas_uchar buffer[4];
+	if (jas_stream_read(in, buffer, sizeof(buffer)) != sizeof(buffer))
+		return -1;
+	*val = (uint_fast32_t)buffer[0] << 24 | (uint_fast32_t)buffer[1] << 16
+		| (uint_fast32_t)buffer[2] << 8 | (uint_fast32_t)buffer[3];
+	return 0;
+}
+
+static int jp2_getuint64(jas_stream_t *in, uint_fast64_t *val)
+{
+	uint_fast64_t tmpval;
+	int i;
+	int c;
+
+	tmpval = 0;
+	for (i = 0; i < 8; ++i) {
+		tmpval <<= 8;
+		if ((c = jas_stream_getc(in)) == EOF) {
+			return -1;
+		}
+		tmpval |= (c & 0xff);
+	}
+	*val = tmpval;
+
+	return 0;
+}
+
+/******************************************************************************\
+* Output operations for primitive types.
+\******************************************************************************/
+
+static int jp2_putuint8(jas_stream_t *out, uint_fast8_t val)
+{
+	if (jas_stream_putc(out, val & 0xff) == EOF) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val)
+{
+	if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
+	  jas_stream_putc(out, val & 0xff) == EOF) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jp2_putuint32(jas_stream_t *out, uint_fast32_t val)
+{
+	if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF ||
+	  jas_stream_putc(out, (val >> 16) & 0xff) == EOF ||
+	  jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
+	  jas_stream_putc(out, val & 0xff) == EOF) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jp2_putuint64(jas_stream_t *out, uint_fast64_t val)
+{
+	if (jp2_putuint32(out, (val >> 32) & 0xffffffffUL) ||
+	  jp2_putuint32(out, val & 0xffffffffUL)) {
+		return -1;
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Miscellaneous code.
+\******************************************************************************/
+
+static const jp2_boxinfo_t *jp2_boxinfolookup(int type)
+{
+	const jp2_boxinfo_t *boxinfo;
+	for (boxinfo = jp2_boxinfos; boxinfo->name; ++boxinfo) {
+		if (boxinfo->type == type) {
+			return boxinfo;
+		}
+	}
+	return &jp2_boxinfo_unk;
+}
+
+
+
+
+
+static void jp2_cmap_destroy(jp2_box_t *box)
+{
+	jp2_cmap_t *cmap = &box->data.cmap;
+	if (cmap->ents) {
+		jas_free(cmap->ents);
+	}
+}
+
+static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+	jp2_cmap_t *cmap = &box->data.cmap;
+	jp2_cmapent_t *ent;
+	unsigned int i;
+	cmap->ents = 0;
+
+	cmap->numchans = (box->datalen) / 4;
+	if (cmap->numchans > 0xff)
+		/* excessive number of channels - this is a
+		   pessimistic limit, because in jp2_pclr_getdata(),
+		   it's a 8 bit integer */
+		return -1;
+
+	if (!(cmap->ents = jas_alloc2(cmap->numchans, sizeof(jp2_cmapent_t)))) {
+		return -1;
+	}
+	for (i = 0; i < cmap->numchans; ++i) {
+		ent = &cmap->ents[i];
+		if (jp2_getuint16(in, &ent->cmptno) ||
+		  jp2_getuint8(in, &ent->map) ||
+		  jp2_getuint8(in, &ent->pcol)) {
+			return -1;
+		}
+	}
+	
+	return 0;
+}
+
+static int jp2_cmap_putdata(const jp2_box_t *box, jas_stream_t *out)
+{
+	/* Eliminate compiler warning about unused variables. */
+	USED(box);
+	USED(out);
+
+	return -1;
+}
+
+static void jp2_cmap_dumpdata(const jp2_box_t *box, FILE *out)
+{
+	const jp2_cmap_t *cmap = &box->data.cmap;
+	unsigned int i;
+	fprintf(out, "numchans = %d\n", (int) cmap->numchans);
+	for (i = 0; i < cmap->numchans; ++i) {
+		const jp2_cmapent_t *ent = &cmap->ents[i];
+		fprintf(out, "cmptno=%d; map=%d; pcol=%d\n",
+		  (int) ent->cmptno, (int) ent->map, (int) ent->pcol);
+	}
+}
+
+static void jp2_pclr_destroy(jp2_box_t *box)
+{
+	jp2_pclr_t *pclr = &box->data.pclr;
+	if (pclr->lutdata) {
+		jas_free(pclr->lutdata);
+	}
+	if (pclr->bpc)
+		jas_free(pclr->bpc);
+}
+
+static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+	jp2_pclr_t *pclr = &box->data.pclr;
+	int lutsize;
+	unsigned int i;
+	unsigned int j;
+	int_fast32_t x;
+
+	pclr->lutdata = 0;
+	pclr->bpc = 0;
+
+	if (jp2_getuint16(in, &pclr->numlutents) ||
+	  jp2_getuint8(in, &pclr->numchans)) {
+		return -1;
+	}
+
+	// verify in range data as per I.5.3.4 - Palette box
+	if (pclr->numchans < 1 || pclr->numlutents < 1 || pclr->numlutents > 1024) {
+		return -1;
+	}
+
+	lutsize = pclr->numlutents * pclr->numchans;
+	if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) {
+		return -1;
+	}
+	if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) {
+		return -1;
+	}
+	for (i = 0; i < pclr->numchans; ++i) {
+		if (jp2_getuint8(in, &pclr->bpc[i])) {
+			return -1;
+		}
+	}
+	for (i = 0; i < pclr->numlutents; ++i) {
+		for (j = 0; j < pclr->numchans; ++j) {
+			if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,
+			  (pclr->bpc[j] & 0x7f) + 1, &x)) {
+				return -1;
+			}
+			pclr->lutdata[i * pclr->numchans + j] = x;
+		}
+	}
+	return 0;
+}
+
+static int jp2_pclr_putdata(const jp2_box_t *box, jas_stream_t *out)
+{
+#if 0
+	const jp2_pclr_t *pclr = &box->data.pclr;
+#endif
+	/* Eliminate warning about unused variable. */
+	USED(box);
+	USED(out);
+	return -1;
+}
+
+static void jp2_pclr_dumpdata(const jp2_box_t *box, FILE *out)
+{
+	const jp2_pclr_t *pclr = &box->data.pclr;
+	unsigned int i;
+	int j;
+	fprintf(out, "numents=%d; numchans=%d\n", (int) pclr->numlutents,
+	  (int) pclr->numchans);
+	for (i = 0; i < pclr->numlutents; ++i) {
+		for (j = 0; j < pclr->numchans; ++j) {
+			fprintf(out, "LUT[%d][%d]=%"PRIiFAST32"\n", i, j,
+			  pclr->lutdata[i * pclr->numchans + j]);
+		}
+	}
+}
+
+static int jp2_getint(jas_stream_t *in, int s, int n, int_fast32_t *val)
+{
+	int c;
+	int i;
+	uint_fast32_t v;
+	int m;
+
+	m = (n + 7) / 8;
+
+	v = 0;
+	for (i = 0; i < m; ++i) {
+		if ((c = jas_stream_getc(in)) == EOF) {
+			return -1;
+		}
+		v = (v << 8) | c;
+	}
+	v &= ONES(n);
+	if (s) {
+		int sb;
+		sb = v & (1 << (8 * m - 1));
+		*val = ((~v) + 1) & ONES(8 * m);
+		if (sb) {
+			*val = -*val;
+		}
+	} else {
+		*val = v;
+	}
+
+	return 0;
+}
+
+const jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo)
+{
+	unsigned int i;
+	jp2_cdefchan_t *cdefent;
+	for (i = 0; i < cdef->numchans; ++i) {
+		cdefent = &cdef->ents[i];
+		if (cdefent->channo == JAS_CAST(unsigned int, channo)) {
+			return cdefent;
+		}
+	}
+	return 0;
+}
--- /dev/null
+++ b/jp2_cod.h
@@ -1,0 +1,313 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JP2 Library
+ *
+ * $Id$
+ */
+
+#ifndef JP2_COD_H
+#define JP2_COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+
+/******************************************************************************\
+* Macros.
+\******************************************************************************/
+
+#define	JP2_SPTOBPC(s, p) \
+	((((p) - 1) & 0x7f) | (((s) & 1) << 7))
+
+/******************************************************************************\
+* Box class.
+\******************************************************************************/
+
+#define	JP2_BOX_HDRLEN(ext) ((ext) ? 16 : 8)
+
+/* Box types. */
+#define	JP2_BOX_JP		0x6a502020	/* Signature */
+#define JP2_BOX_FTYP	0x66747970	/* File Type */
+#define	JP2_BOX_JP2H	0x6a703268	/* JP2 Header */
+#define	JP2_BOX_IHDR	0x69686472	/* Image Header */
+#define	JP2_BOX_BPCC	0x62706363	/* Bits Per Component */
+#define	JP2_BOX_COLR	0x636f6c72	/* Color Specification */
+#define	JP2_BOX_PCLR	0x70636c72	/* Palette */
+#define	JP2_BOX_CMAP	0x636d6170	/* Component Mapping */
+#define	JP2_BOX_CDEF	0x63646566	/* Channel Definition */
+#define	JP2_BOX_RES		0x72657320	/* Resolution */
+#define	JP2_BOX_RESC	0x72657363	/* Capture Resolution */
+#define	JP2_BOX_RESD	0x72657364	/* Default Display Resolution */
+#define	JP2_BOX_JP2C	0x6a703263	/* Contiguous Code Stream */
+#define	JP2_BOX_JP2I	0x6a703269	/* Intellectual Property */
+#define	JP2_BOX_XML		0x786d6c20	/* XML */
+#define	JP2_BOX_UUID	0x75756964	/* UUID */
+#define	JP2_BOX_UINF	0x75696e66	/* UUID Info */
+#define	JP2_BOX_ULST	0x75637374	/* UUID List */
+#define	JP2_BOX_URL		0x75726c20	/* URL */
+
+#define	JP2_BOX_SUPER	0x01
+#define	JP2_BOX_NODATA	0x02
+
+/* JP box data. */
+
+#define	JP2_JP_MAGIC	0x0d0a870a
+#define	JP2_JP_LEN		12
+
+typedef struct {
+	uint_fast32_t magic;
+} jp2_jp_t;
+
+/* FTYP box data. */
+
+#define	JP2_FTYP_MAXCOMPATCODES	32
+#define	JP2_FTYP_MAJVER		0x6a703220
+#define	JP2_FTYP_MINVER		0
+#define	JP2_FTYP_COMPATCODE		JP2_FTYP_MAJVER
+
+typedef struct {
+	uint_fast32_t majver;
+	uint_fast32_t minver;
+	uint_fast32_t numcompatcodes;
+	uint_fast32_t compatcodes[JP2_FTYP_MAXCOMPATCODES];
+} jp2_ftyp_t;
+
+/* IHDR box data. */
+
+#define	JP2_IHDR_COMPTYPE	7
+#define	JP2_IHDR_BPCNULL	255
+
+typedef struct {
+	uint_fast32_t width;
+	uint_fast32_t height;
+	uint_fast16_t numcmpts;
+	uint_fast8_t bpc;
+	uint_fast8_t comptype;
+	uint_fast8_t csunk;
+	uint_fast8_t ipr;
+} jp2_ihdr_t;
+
+/* BPCC box data. */
+
+typedef struct {
+	uint_fast16_t numcmpts;
+	uint_fast8_t *bpcs;
+} jp2_bpcc_t;
+
+/* COLR box data. */
+
+#define	JP2_COLR_ENUM	1
+#define	JP2_COLR_ICC	2
+#define	JP2_COLR_PRI	0
+
+#define	JP2_COLR_SRGB	16
+#define	JP2_COLR_SGRAY	17
+#define	JP2_COLR_SYCC	18
+
+typedef struct {
+	uint_fast8_t method;
+	uint_fast8_t pri;
+	uint_fast8_t approx;
+	uint_fast32_t csid;
+	uint_fast8_t *iccp;
+	size_t iccplen;
+	/* XXX - Someday we ought to add ICC profile data here. */
+} jp2_colr_t;
+
+/* PCLR box data. */
+
+typedef struct {
+	uint_fast16_t numlutents;
+	uint_fast8_t numchans;
+	int_fast32_t *lutdata;
+	uint_fast8_t *bpc;
+} jp2_pclr_t;
+
+/* CDEF box per-channel data. */
+
+#define JP2_CDEF_RGB_R	1
+#define JP2_CDEF_RGB_G	2
+#define JP2_CDEF_RGB_B	3
+
+#define JP2_CDEF_YCBCR_Y	1
+#define JP2_CDEF_YCBCR_CB	2
+#define JP2_CDEF_YCBCR_CR	3
+
+#define	JP2_CDEF_GRAY_Y	1
+
+#define	JP2_CDEF_TYPE_COLOR	0
+#define	JP2_CDEF_TYPE_OPACITY	1
+#define	JP2_CDEF_TYPE_UNSPEC	65535
+#define	JP2_CDEF_ASOC_ALL	0
+#define	JP2_CDEF_ASOC_NONE	65535
+
+typedef struct {
+	uint_fast16_t channo;
+	uint_fast16_t type;
+	uint_fast16_t assoc;
+} jp2_cdefchan_t;
+
+/* CDEF box data. */
+
+typedef struct {
+	uint_fast16_t numchans;
+	jp2_cdefchan_t *ents;
+} jp2_cdef_t;
+
+typedef struct {
+	uint_fast16_t cmptno;
+	uint_fast8_t map;
+	uint_fast8_t pcol;
+} jp2_cmapent_t;
+
+typedef struct {
+	uint_fast16_t numchans;
+	jp2_cmapent_t *ents;
+} jp2_cmap_t;
+
+#define	JP2_CMAP_DIRECT		0
+#define	JP2_CMAP_PALETTE	1
+
+/* Generic box. */
+
+struct jp2_boxops_s;
+typedef struct {
+
+	const struct jp2_boxops_s *ops;
+	const struct jp2_boxinfo_s *info;
+
+	uint_fast32_t type;
+
+	/* The length of the box including the (variable-length) header. */
+	uint_fast64_t len;
+
+	/* The length of the box data. */
+	uint_fast32_t datalen;
+
+	union {
+		jp2_jp_t jp;
+		jp2_ftyp_t ftyp;
+		jp2_ihdr_t ihdr;
+		jp2_bpcc_t bpcc;
+		jp2_colr_t colr;
+		jp2_pclr_t pclr;
+		jp2_cdef_t cdef;
+		jp2_cmap_t cmap;
+	} data;
+
+} jp2_box_t;
+
+typedef struct jp2_boxops_s {
+	void (*init)(jp2_box_t *box);
+	void (*destroy)(jp2_box_t *box);
+	int (*getdata)(jp2_box_t *box, jas_stream_t *in);
+	int (*putdata)(const jp2_box_t *box, jas_stream_t *out);
+	void (*dumpdata)(const jp2_box_t *box, FILE *out);
+} jp2_boxops_t;
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+typedef struct jp2_boxinfo_s {
+	int type;
+	int flags;
+	const char *name;
+	jp2_boxops_t ops;
+} jp2_boxinfo_t;
+
+/******************************************************************************\
+* Box class.
+\******************************************************************************/
+
+jp2_box_t *jp2_box_create(int type);
+void jp2_box_destroy(jp2_box_t *box);
+jp2_box_t *jp2_box_get(jas_stream_t *in);
+int jp2_box_put(jp2_box_t *box, jas_stream_t *out);
+
+JAS_ATTRIBUTE_CONST
+static inline uint_least8_t JP2_DTYPETOBPC(uint_least8_t dtype)
+{
+	return (JAS_IMAGE_CDT_GETSGND(dtype) << 7) | (JAS_IMAGE_CDT_GETPREC(dtype) - 1);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline uint_least8_t JP2_BPCTODTYPE(uint_least8_t bpc)
+{
+	return JAS_IMAGE_CDT_SETSGND(bpc >> 7) | JAS_IMAGE_CDT_SETPREC((bpc & 0x7f) + 1);
+}
+
+#define ICC_CS_RGB	0x52474220
+#define ICC_CS_YCBCR	0x59436272
+#define ICC_CS_GRAY	0x47524159
+
+const jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo);
+
+
+#endif
--- /dev/null
+++ b/jp2_dec.c
@@ -1,0 +1,603 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JP2 Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jp2_dec.h"
+#include "jp2_cod.h"
+
+#include "jasper/jas_image.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_types.h"
+
+#define	JP2_VALIDATELEN	(JAS_MIN(JP2_JP_LEN + 16, JAS_STREAM_MAXPUTBACK))
+
+static jp2_dec_t *jp2_dec_create(void);
+static void jp2_dec_destroy(jp2_dec_t *dec);
+static int jp2_getcs(jp2_colr_t *colr);
+static int fromiccpcs(int cs);
+static int jp2_getct(int colorspace, int type, int assoc);
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr)
+{
+	jp2_box_t *box;
+	int found;
+	jas_image_t *image;
+	jp2_dec_t *dec;
+	bool samedtype;
+	int dtype;
+	unsigned int i;
+	jp2_cmap_t *cmapd;
+	jp2_pclr_t *pclrd;
+	jp2_cdef_t *cdefd;
+	unsigned int channo;
+	int newcmptno;
+	int_fast32_t *lutents;
+#if 0
+	jp2_cdefchan_t *cdefent;
+	int cmptno;
+#endif
+	jp2_cmapent_t *cmapent;
+	jas_icchdr_t icchdr;
+	jas_iccprof_t *iccprof;
+
+	box = 0;
+
+	JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr));
+
+	if (!(dec = jp2_dec_create())) {
+		goto error;
+	}
+
+	/* Get the first box.  This should be a JP box. */
+	if (!(box = jp2_box_get(in))) {
+		jas_eprintf("error: cannot get box\n");
+		goto error;
+	}
+	if (box->type != JP2_BOX_JP) {
+		jas_eprintf("error: expecting signature box\n");
+		goto error;
+	}
+	if (box->data.jp.magic != JP2_JP_MAGIC) {
+		jas_eprintf("incorrect magic number\n");
+		goto error;
+	}
+	jp2_box_destroy(box);
+
+	/* Get the second box.  This should be a FTYP box. */
+	if (!(box = jp2_box_get(in))) {
+		goto error;
+	}
+	if (box->type != JP2_BOX_FTYP) {
+		jas_eprintf("expecting file type box\n");
+		goto error;
+	}
+	jp2_box_destroy(box);
+
+	/* Get more boxes... */
+	found = 0;
+	while ((box = jp2_box_get(in))) {
+		if (jas_getdbglevel() >= 1) {
+			jas_eprintf("got box type %s\n", box->info->name);
+		}
+		switch (box->type) {
+		case JP2_BOX_JP2C:
+			found = 1;
+			break;
+		case JP2_BOX_IHDR:
+			if (!dec->ihdr) {
+				dec->ihdr = box;
+				box = 0;
+			}
+			break;
+		case JP2_BOX_BPCC:
+			if (!dec->bpcc) {
+				dec->bpcc = box;
+				box = 0;
+			}
+			break;
+		case JP2_BOX_CDEF:
+			if (!dec->cdef) {
+				dec->cdef = box;
+				box = 0;
+			}
+			break;
+		case JP2_BOX_PCLR:
+			if (!dec->pclr) {
+				dec->pclr = box;
+				box = 0;
+			}
+			break;
+		case JP2_BOX_CMAP:
+			if (!dec->cmap) {
+				dec->cmap = box;
+				box = 0;
+			}
+			break;
+		case JP2_BOX_COLR:
+			if (!dec->colr) {
+				dec->colr = box;
+				box = 0;
+			}
+			break;
+		}
+		if (box) {
+			jp2_box_destroy(box);
+			box = 0;
+		}
+		if (found) {
+			break;
+		}
+	}
+
+	if (!found) {
+		jas_eprintf("error: no code stream found\n");
+		goto error;
+	}
+
+	if (!(dec->image = jpc_decode(in, optstr))) {
+		jas_eprintf("error: cannot decode code stream\n");
+		goto error;
+	}
+
+	/* An IHDR box must be present. */
+	if (!dec->ihdr) {
+		jas_eprintf("error: missing IHDR box\n");
+		goto error;
+	}
+
+	/* Does the number of components indicated in the IHDR box match
+	  the value specified in the code stream? */
+	if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint,
+	  jas_image_numcmpts(dec->image))) {
+		jas_eprintf("warning: number of components mismatch\n");
+	}
+
+	/* At least one component must be present. */
+	if (!jas_image_numcmpts(dec->image)) {
+		jas_eprintf("error: no components\n");
+		goto error;
+	}
+
+	/* Determine if all components have the same data type. */
+	samedtype = true;
+	dtype = jas_image_cmptdtype(dec->image, 0);
+	for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
+		if (jas_image_cmptdtype(dec->image, i) != dtype) {
+			samedtype = false;
+			break;
+		}
+	}
+
+	/* Is the component data type indicated in the IHDR box consistent
+	  with the data in the code stream? */
+	if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
+	  (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
+		jas_eprintf("warning: component data type mismatch\n");
+	}
+
+	/* Is the compression type supported? */
+	if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
+		jas_eprintf("error: unsupported compression type\n");
+		goto error;
+	}
+
+	if (dec->bpcc) {
+		/* Is the number of components indicated in the BPCC box
+		  consistent with the code stream data? */
+		if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(
+		  dec->image))) {
+			jas_eprintf("warning: number of components mismatch\n");
+		}
+		/* Is the component data type information indicated in the BPCC
+		  box consistent with the code stream data? */
+		if (!samedtype) {
+			for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
+			  ++i) {
+				if (jas_image_cmptdtype(dec->image, i) !=
+				  JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
+					jas_eprintf("warning: component data type mismatch\n");
+				}
+			}
+		} else {
+			jas_eprintf("warning: superfluous BPCC box\n");
+		}
+	}
+
+	/* A COLR box must be present. */
+	if (!dec->colr) {
+		jas_eprintf("error: no COLR box\n");
+		goto error;
+	}
+
+	switch (dec->colr->data.colr.method) {
+	case JP2_COLR_ENUM:
+		jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
+		break;
+	case JP2_COLR_ICC:
+		iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
+		  dec->colr->data.colr.iccplen);
+		if (!iccprof) {
+			jas_eprintf("error: failed to parse ICC profile\n");
+			goto error;
+		}
+		jas_iccprof_gethdr(iccprof, &icchdr);
+		//jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
+		jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
+		dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
+		if (!dec->image->cmprof_) {
+			jas_iccprof_destroy(iccprof);
+			goto error;
+		}
+		jas_iccprof_destroy(iccprof);
+		break;
+	}
+
+	/* If a CMAP box is present, a PCLR box must also be present. */
+	if (dec->cmap && !dec->pclr) {
+		jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
+		jp2_box_destroy(dec->cmap);
+		dec->cmap = 0;
+	}
+
+	/* If a CMAP box is not present, a PCLR box must not be present. */
+	if (!dec->cmap && dec->pclr) {
+		jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
+		jp2_box_destroy(dec->pclr);
+		dec->pclr = 0;
+	}
+
+	/* Determine the number of channels (which is essentially the number
+	  of components after any palette mappings have been applied). */
+	dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans :
+	  JAS_CAST(jas_uint, jas_image_numcmpts(dec->image));
+
+	/* Perform a basic sanity check on the CMAP box if present. */
+	if (dec->cmap) {
+		for (i = 0; i < dec->numchans; ++i) {
+			/* Is the component number reasonable? */
+			if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint,
+			  jas_image_numcmpts(dec->image))) {
+				jas_eprintf("error: invalid component number in CMAP box\n");
+				goto error;
+			}
+			/* Is the LUT index reasonable? */
+			if (dec->cmap->data.cmap.ents[i].pcol >=
+			  dec->pclr->data.pclr.numchans) {
+				jas_eprintf("error: invalid CMAP LUT index\n");
+				goto error;
+			}
+		}
+	}
+
+	/* Allocate space for the channel-number to component-number LUT. */
+	if (!(dec->chantocmptlut = jas_alloc2(dec->numchans,
+	  sizeof(uint_fast16_t)))) {
+		jas_eprintf("error: no memory\n");
+		goto error;
+	}
+
+	if (!dec->cmap) {
+		for (i = 0; i < dec->numchans; ++i) {
+			dec->chantocmptlut[i] = i;
+		}
+	} else {
+		cmapd = &dec->cmap->data.cmap;
+		pclrd = &dec->pclr->data.pclr;
+		for (channo = 0; channo < cmapd->numchans; ++channo) {
+			cmapent = &cmapd->ents[channo];
+			if (cmapent->map == JP2_CMAP_DIRECT) {
+				dec->chantocmptlut[channo] = channo;
+			} else if (cmapent->map == JP2_CMAP_PALETTE) {
+				if (!pclrd->numlutents) {
+					goto error;
+				}
+				lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));
+				if (!lutents) {
+					goto error;
+				}
+				for (i = 0; i < pclrd->numlutents; ++i) {
+					lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
+				}
+				newcmptno = jas_image_numcmpts(dec->image);
+				jas_image_depalettize(dec->image, cmapent->cmptno,
+				  pclrd->numlutents, lutents,
+				  JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
+				dec->chantocmptlut[channo] = newcmptno;
+				jas_free(lutents);
+#if 0
+				if (dec->cdef) {
+					cdefent = jp2_cdef_lookup(cdefd, channo);
+					if (!cdefent) {
+						abort();
+					}
+				jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
+				} else {
+				jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
+				}
+#else
+				/* suppress -Wunused-but-set-variable */
+				(void)cdefd;
+#endif
+			} else {
+				jas_eprintf("error: invalid MTYP in CMAP box\n");
+				goto error;
+			}
+		}
+	}
+
+	/* Mark all components as being of unknown type. */
+
+	for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
+		jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
+	}
+
+	/* Determine the type of each component. */
+	if (dec->cdef) {
+		for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) {
+			/* Is the channel number reasonable? */
+			if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) {
+				jas_eprintf("error: invalid channel number in CDEF box\n");
+				goto error;
+			}
+			jas_image_setcmpttype(dec->image,
+			  dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
+			  jp2_getct(jas_image_clrspc(dec->image),
+			  dec->cdef->data.cdef.ents[i].type,
+			  dec->cdef->data.cdef.ents[i].assoc));
+		}
+	} else {
+		for (i = 0; i < dec->numchans; ++i) {
+			jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
+			  jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
+		}
+	}
+
+	/* Delete any components that are not of interest. */
+	for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
+		if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
+			jas_image_delcmpt(dec->image, i - 1);
+		}
+	}
+
+	/* Ensure that some components survived. */
+	if (!jas_image_numcmpts(dec->image)) {
+		jas_eprintf("error: no components\n");
+		goto error;
+	}
+#if 0
+jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
+#endif
+
+	/* Prevent the image from being destroyed later. */
+	image = dec->image;
+	dec->image = 0;
+
+	jp2_dec_destroy(dec);
+
+	return image;
+
+error:
+	if (box) {
+		jp2_box_destroy(box);
+	}
+	if (dec) {
+		jp2_dec_destroy(dec);
+	}
+	return 0;
+}
+
+int jp2_validate(jas_stream_t *in)
+{
+	unsigned char buf[JP2_VALIDATELEN];
+#if 0
+	jas_stream_t *tmpstream;
+	jp2_box_t *box;
+#endif
+
+	assert(JAS_STREAM_MAXPUTBACK >= JP2_VALIDATELEN);
+
+	/* Read the validation data (i.e., the data used for detecting
+	  the format). */
+	if (jas_stream_peek(in, buf, sizeof(buf)) != sizeof(buf))
+		return -1;
+
+	/* Is the box type correct? */
+	if ((((uint_least32_t)buf[4] << 24) | ((uint_least32_t)buf[5] << 16) | ((uint_least32_t)buf[6] << 8) | (uint_least32_t)buf[7]) !=
+	  JP2_BOX_JP)
+	{
+		return -1;
+	}
+
+	return 0;
+}
+
+static jp2_dec_t *jp2_dec_create(void)
+{
+	jp2_dec_t *dec;
+
+	if (!(dec = jas_malloc(sizeof(jp2_dec_t)))) {
+		return 0;
+	}
+	dec->ihdr = 0;
+	dec->bpcc = 0;
+	dec->cdef = 0;
+	dec->pclr = 0;
+	dec->image = 0;
+	dec->chantocmptlut = 0;
+	dec->cmap = 0;
+	dec->colr = 0;
+	return dec;
+}
+
+static void jp2_dec_destroy(jp2_dec_t *dec)
+{
+	if (dec->ihdr) {
+		jp2_box_destroy(dec->ihdr);
+	}
+	if (dec->bpcc) {
+		jp2_box_destroy(dec->bpcc);
+	}
+	if (dec->cdef) {
+		jp2_box_destroy(dec->cdef);
+	}
+	if (dec->pclr) {
+		jp2_box_destroy(dec->pclr);
+	}
+	if (dec->image) {
+		jas_image_destroy(dec->image);
+	}
+	if (dec->cmap) {
+		jp2_box_destroy(dec->cmap);
+	}
+	if (dec->colr) {
+		jp2_box_destroy(dec->colr);
+	}
+	if (dec->chantocmptlut) {
+		jas_free(dec->chantocmptlut);
+	}
+	jas_free(dec);
+}
+
+static int jp2_getct(int colorspace, int type, int assoc)
+{
+	if (type == 1 && assoc == 0) {
+		return JAS_IMAGE_CT_OPACITY;
+	}
+	if (type == 0 && assoc >= 1 && assoc <= 65534) {
+		switch (colorspace) {
+		case JAS_CLRSPC_FAM_RGB:
+			switch (assoc) {
+			case JP2_CDEF_RGB_R:
+				return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R);
+			case JP2_CDEF_RGB_G:
+				return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G);
+			case JP2_CDEF_RGB_B:
+				return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B);
+			}
+			break;
+		case JAS_CLRSPC_FAM_YCBCR:
+			switch (assoc) {
+			case JP2_CDEF_YCBCR_Y:
+				return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y);
+			case JP2_CDEF_YCBCR_CB:
+				return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB);
+			case JP2_CDEF_YCBCR_CR:
+				return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR);
+			}
+			break;
+		case JAS_CLRSPC_FAM_GRAY:
+			switch (assoc) {
+			case JP2_CDEF_GRAY_Y:
+				return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y);
+			}
+			break;
+		default:
+			return JAS_IMAGE_CT_COLOR(assoc - 1);
+		}
+	}
+	return JAS_IMAGE_CT_UNKNOWN;
+}
+
+static int jp2_getcs(jp2_colr_t *colr)
+{
+	if (colr->method == JP2_COLR_ENUM) {
+		switch (colr->csid) {
+		case JP2_COLR_SRGB:
+			return JAS_CLRSPC_SRGB;
+		case JP2_COLR_SYCC:
+			return JAS_CLRSPC_SYCBCR;
+		case JP2_COLR_SGRAY:
+			return JAS_CLRSPC_SGRAY;
+		}
+	}
+	return JAS_CLRSPC_UNKNOWN;
+}
+
+static int fromiccpcs(int cs)
+{
+	switch (cs) {
+	case ICC_CS_RGB:
+		return JAS_CLRSPC_GENRGB;
+	case ICC_CS_YCBCR:
+		return JAS_CLRSPC_GENYCBCR;
+	case ICC_CS_GRAY:
+		return JAS_CLRSPC_GENGRAY;
+	}
+	return JAS_CLRSPC_UNKNOWN;
+}
--- /dev/null
+++ b/jp2_dec.h
@@ -1,0 +1,84 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JP2_DEC_H
+#define JP2_DEC_H
+
+#include "jasper/jas_image.h"
+#include "jp2_cod.h"
+
+typedef struct {
+
+	jp2_box_t *pclr;
+	jp2_box_t *cdef;
+	jp2_box_t *ihdr;
+	jp2_box_t *bpcc;
+	jp2_box_t *cmap;
+	jp2_box_t *colr;
+	jas_image_t *image;
+	uint_fast16_t numchans;
+	uint_fast16_t *chantocmptlut;
+
+} jp2_dec_t;
+
+#endif
--- /dev/null
+++ b/jpc_bs.c
@@ -1,0 +1,440 @@
+/*
+ * Copyright (c) 1999-2000, Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Bit Stream Class
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_bs.h"
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static jpc_bitstream_t *jpc_bitstream_alloc(void);
+
+/******************************************************************************\
+* Code for opening and closing bit streams.
+\******************************************************************************/
+
+/* Open a bit stream from a stream. */
+jpc_bitstream_t *jpc_bitstream_sopen(jas_stream_t *stream, const char *mode)
+{
+	jpc_bitstream_t *bitstream;
+
+	/* Ensure that the open mode is valid. */
+#if 0 /* This causes a string literal too long error (with c99 pedantic mode).  Why is this so? */
+	assert(!strcmp(mode, "r") || !strcmp(mode, "w") || !strcmp(mode, "r+")
+	  || !strcmp(mode, "w+"));
+#endif
+
+	if (!(bitstream = jpc_bitstream_alloc())) {
+		return 0;
+	}
+
+	/* By default, do not close the underlying (character) stream, upon
+	  the close of the bit stream. */
+	bitstream->flags_ = JPC_BITSTREAM_NOCLOSE;
+
+	bitstream->stream_ = stream;
+	bitstream->openmode_ = (mode[0] == 'w') ? JPC_BITSTREAM_WRITE :
+	  JPC_BITSTREAM_READ;
+
+	/* Mark the data buffer as empty. */
+	bitstream->cnt_ = (bitstream->openmode_ == JPC_BITSTREAM_READ) ? 0 : 8;
+	bitstream->buf_ = 0;
+
+	return bitstream;
+}
+
+/* Close a bit stream. */
+int jpc_bitstream_close(jpc_bitstream_t *bitstream)
+{
+	int ret = 0;
+
+	/* Align to the next byte boundary while considering the effects of
+	  bit stuffing. */
+	if (jpc_bitstream_align(bitstream)) {
+		ret = -1;
+	}
+
+	/* If necessary, close the underlying (character) stream. */
+	if (!(bitstream->flags_ & JPC_BITSTREAM_NOCLOSE) && bitstream->stream_) {
+		if (jas_stream_close(bitstream->stream_)) {
+			ret = -1;
+		}
+		bitstream->stream_ = 0;
+	}
+
+	jas_free(bitstream);
+	return ret;
+}
+
+/* Allocate a new bit stream. */
+static jpc_bitstream_t *jpc_bitstream_alloc()
+{
+	jpc_bitstream_t *bitstream;
+
+	/* Allocate memory for the new bit stream object. */
+	if (!(bitstream = jas_malloc(sizeof(jpc_bitstream_t)))) {
+		return 0;
+	}
+	/* Initialize all of the data members. */
+	bitstream->stream_ = 0;
+	bitstream->cnt_ = 0;
+	bitstream->flags_ = 0;
+	bitstream->openmode_ = 0;
+
+	return bitstream;
+}
+
+/******************************************************************************\
+* Code for reading/writing from/to bit streams.
+\******************************************************************************/
+
+/* Get a bit from a bit stream. */
+int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream)
+{
+	int ret;
+	JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func(%p)\n", bitstream));
+	ret = jpc_bitstream_getbit_macro(bitstream);
+	JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func -> %d\n", ret));
+	return ret;
+}
+
+/* Put a bit to a bit stream. */
+int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int b)
+{
+	int ret;
+	JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func(%p, %d)\n", bitstream, b));
+	ret = jpc_bitstream_putbit_macro(bitstream, b);
+	JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func() -> %d\n", ret));
+	return ret;
+}
+
+/* Get one or more bits from a bit stream. */
+long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n)
+{
+	long v;
+	int u;
+
+	/* We can reliably get at most 31 bits since ISO/IEC 9899 only
+	  guarantees that a long can represent values up to 2^31-1. */
+	//assert(n >= 0 && n < 32);
+	if (n < 0 || n >= 32) {
+		return -1;
+	}
+
+	/* Get the number of bits requested from the specified bit stream. */
+	v = 0;
+	while (--n >= 0) {
+		if ((u = jpc_bitstream_getbit(bitstream)) < 0) {
+			return -1;
+		}
+		v = (v << 1) | u;
+	}
+	return v;
+}
+
+/* Put one or more bits to a bit stream. */
+int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v)
+{
+	int m;
+
+	/* We can reliably put at most 31 bits since ISO/IEC 9899 only
+	  guarantees that a long can represent values up to 2^31-1. */
+	//assert(n >= 0 && n < 32);
+	if (n < 0 || n >= 32) {
+		return EOF;
+	}
+	/* Ensure that only the bits to be output are nonzero. */
+	assert(!(v & (~JAS_ONES(n))));
+
+	/* Put the desired number of bits to the specified bit stream. */
+	m = n - 1;
+	while (--n >= 0) {
+		if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) {
+			return EOF;
+		}
+		v <<= 1;
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Code for buffer filling and flushing.
+\******************************************************************************/
+
+/* Fill the buffer for a bit stream. */
+int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream)
+{
+	int c;
+	/* Note: The count has already been decremented by the caller. */
+	assert(bitstream->openmode_ & JPC_BITSTREAM_READ);
+	assert(bitstream->cnt_ <= 0);
+
+	if (bitstream->flags_ & JPC_BITSTREAM_ERR) {
+		bitstream->cnt_ = 0;
+		return -1;
+	}
+
+	if (bitstream->flags_ & JPC_BITSTREAM_EOF) {
+		bitstream->buf_ = 0x7f;
+		bitstream->cnt_ = 7;
+		return 1;
+	}
+
+	bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
+	if ((c = jas_stream_getc((bitstream)->stream_)) == EOF) {
+		bitstream->flags_ |= JPC_BITSTREAM_EOF;
+		return 1;
+	}
+	bitstream->cnt_ = (bitstream->buf_ == 0xff00) ? 6 : 7;
+	bitstream->buf_ |= c & ((1 << (bitstream->cnt_ + 1)) - 1);
+	return (bitstream->buf_ >> bitstream->cnt_) & 1;
+}
+
+
+/******************************************************************************\
+* Code related to flushing.
+\******************************************************************************/
+
+/* Does the bit stream need to be aligned to a byte boundary (considering
+  the effects of bit stuffing)? */
+int jpc_bitstream_needalign(const jpc_bitstream_t *bitstream)
+{
+	if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
+		/* The bit stream is open for reading. */
+		/* If there are any bits buffered for reading, or the
+		  previous byte forced a stuffed bit, alignment is
+		  required. */
+		if ((bitstream->cnt_ < 8 && bitstream->cnt_ > 0) ||
+		  ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+			return 1;
+		}
+	} else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+		/* The bit stream is open for writing. */
+		/* If there are any bits buffered for writing, or the
+		  previous byte forced a stuffed bit, alignment is
+		  required. */
+		if ((bitstream->cnt_ < 8 && bitstream->cnt_ >= 0) ||
+		  ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+			return 1;
+		}
+	} else {
+		/* This should not happen.  Famous last words, eh? :-) */
+		assert(0);
+		return -1;
+	}
+	return 0;
+}
+
+/* How many additional bytes would be output if we align the bit stream? */
+int jpc_bitstream_pending(const jpc_bitstream_t *bitstream)
+{
+	if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+		/* The bit stream is being used for writing. */
+#if 1
+		/* XXX - Is this really correct?  Check someday... */
+		if (bitstream->cnt_ < 8) {
+			return 1;
+		}
+#else
+		if (bitstream->cnt_ < 8) {
+			if (((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+				return 2;
+			}
+			return 1;
+		}
+#endif
+		return 0;
+	} else {
+		/* This operation should not be invoked on a bit stream that
+		  is being used for reading. */
+		return -1;
+	}
+}
+
+/* Align the bit stream to a byte boundary. */
+int jpc_bitstream_align(jpc_bitstream_t *bitstream)
+{
+	int ret = -1;
+	if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
+		ret = jpc_bitstream_inalign(bitstream, 0, 0);
+	} else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+		ret = jpc_bitstream_outalign(bitstream, 0);
+	} else {
+		assert(false);
+		JAS_UNREACHABLE();
+	}
+	return ret;
+}
+
+/* Align a bit stream in the input case. */
+int jpc_bitstream_inalign(jpc_bitstream_t *bitstream, int fillmask,
+  int filldata)
+{
+	int n;
+	int v;
+	int u;
+	int numfill;
+	int m;
+
+	numfill = 7;
+	m = 0;
+	v = 0;
+	if (bitstream->cnt_ > 0) {
+		n = bitstream->cnt_;
+	} else if (!bitstream->cnt_) {
+		n = ((bitstream->buf_ & 0xff) == 0xff) ? 7 : 0;
+	} else {
+		n = 0;
+	}
+	if (n > 0) {
+		if ((u = jpc_bitstream_getbits(bitstream, n)) < 0) {
+			return -1;
+		}
+		m += n;
+		v = (v << n) | u;
+	}
+	if ((bitstream->buf_ & 0xff) == 0xff) {
+		if ((u = jpc_bitstream_getbits(bitstream, 7)) < 0) {
+			return -1;
+		}
+		v = (v << 7) | u;
+		m += 7;
+	}
+	if (m > numfill) {
+		v >>= m - numfill;
+	} else {
+		filldata >>= numfill - m;
+		fillmask >>= numfill - m;
+	}
+	if (((~(v ^ filldata)) & fillmask) != fillmask) {
+		/* The actual fill pattern does not match the expected one. */
+		return 1;
+	}
+
+	return 0;
+}
+
+/* Align a bit stream in the output case. */
+int jpc_bitstream_outalign(jpc_bitstream_t *bitstream, int filldata)
+{
+	int n;
+	int v;
+
+	/* Ensure that this bit stream is open for writing. */
+	assert(bitstream->openmode_ & JPC_BITSTREAM_WRITE);
+
+	/* Ensure that the first bit of fill data is zero. */
+	/* Note: The first bit of fill data must be zero.  If this were not
+	  the case, the fill data itself could cause further bit stuffing to
+	  be required (which would cause numerous complications). */
+	assert(!(filldata & (~0x3f)));
+
+	if (!bitstream->cnt_) {
+		if ((bitstream->buf_ & 0xff) == 0xff) {
+			n = 7;
+			v = filldata;
+		} else {
+			n = 0;
+			v = 0;
+		}
+	} else if (bitstream->cnt_ > 0 && bitstream->cnt_ < 8) {
+		n = bitstream->cnt_;
+		v = filldata >> (7 - n);
+	} else {
+		return 0;
+	}
+
+	/* Write the appropriate fill data to the bit stream. */
+	if (n > 0) {
+		if (jpc_bitstream_putbits(bitstream, n, v)) {
+			return -1;
+		}
+	}
+	if (bitstream->cnt_ < 8) {
+		assert(bitstream->cnt_ >= 0 && bitstream->cnt_ < 8);
+		assert((bitstream->buf_ & 0xff) != 0xff);
+		/* Force the pending byte of output to be written to the
+		  underlying (character) stream. */
+		if (jas_stream_putc(bitstream->stream_, bitstream->buf_ & 0xff) == EOF) {
+			return -1;
+		}
+		bitstream->cnt_ = 8;
+		bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
+	}
+
+	return 0;
+}
--- /dev/null
+++ b/jpc_bs.h
@@ -1,0 +1,229 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Bit Stream Class
+ *
+ * $Id$
+ */
+
+#ifndef JPC_BS_H
+#define JPC_BS_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/*
+ * Bit stream open mode flags.
+ */
+
+/* Bit stream open for reading. */
+#define	JPC_BITSTREAM_READ	0x01
+/* Bit stream open for writing. */
+#define	JPC_BITSTREAM_WRITE	0x02
+
+/*
+ * Bit stream flags.
+ */
+
+/* Do not close underlying character stream. */
+#define	JPC_BITSTREAM_NOCLOSE	0x01
+/* End of file has been reached while reading. */
+#define	JPC_BITSTREAM_EOF	0x02
+/* An I/O error has occured. */
+#define	JPC_BITSTREAM_ERR	0x04
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Bit stream class. */
+
+typedef struct {
+
+	/* Some miscellaneous flags. */
+	int flags_;
+
+	/* The input/output buffer. */
+	uint_fast16_t buf_;
+
+	/* The number of bits remaining in the byte being read/written. */
+	int cnt_;
+
+	/* The underlying stream associated with this bit stream. */
+	jas_stream_t *stream_;
+
+	/* The mode in which this bit stream was opened. */
+	int openmode_;
+
+} jpc_bitstream_t;
+
+/******************************************************************************\
+* Functions/macros for opening and closing bit streams..
+\******************************************************************************/
+
+/* Open a stream as a bit stream. */
+jpc_bitstream_t *jpc_bitstream_sopen(jas_stream_t *stream, const char *mode);
+
+/* Close a bit stream. */
+int jpc_bitstream_close(jpc_bitstream_t *bitstream);
+
+/******************************************************************************\
+* Functions/macros for reading from and writing to bit streams..
+\******************************************************************************/
+
+/* Read a bit from a bit stream. */
+#ifndef NDEBUG
+#define	jpc_bitstream_getbit(bitstream) \
+	jpc_bitstream_getbit_func(bitstream)
+#else
+#define jpc_bitstream_getbit(bitstream) \
+	jpc_bitstream_getbit_macro(bitstream)
+#endif
+
+/* Write a bit to a bit stream. */
+#ifndef NDEBUG
+#define	jpc_bitstream_putbit(bitstream, v) \
+	jpc_bitstream_putbit_func(bitstream, v)
+#else
+#define	jpc_bitstream_putbit(bitstream, v) \
+	jpc_bitstream_putbit_macro(bitstream, v)
+#endif
+
+/* Read one or more bits from a bit stream. */
+long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n);
+
+/* Write one or more bits to a bit stream. */
+int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v);
+
+/******************************************************************************\
+* Functions/macros for flushing and aligning bit streams.
+\******************************************************************************/
+
+/* Align the current position within the bit stream to the next byte
+  boundary. */
+int jpc_bitstream_align(jpc_bitstream_t *bitstream);
+
+/* Align the current position in the bit stream with the next byte boundary,
+  ensuring that certain bits consumed in the process match a particular
+  pattern. */
+int jpc_bitstream_inalign(jpc_bitstream_t *bitstream, int fillmask,
+  int filldata);
+
+/* Align the current position in the bit stream with the next byte boundary,
+  writing bits from the specified pattern (if necessary) in the process. */
+int jpc_bitstream_outalign(jpc_bitstream_t *bitstream, int filldata);
+
+/* Check if a bit stream needs alignment. */
+JAS_ATTRIBUTE_PURE
+int jpc_bitstream_needalign(const jpc_bitstream_t *bitstream);
+
+/* How many additional bytes would be output if the bit stream was aligned? */
+JAS_ATTRIBUTE_PURE
+int jpc_bitstream_pending(const jpc_bitstream_t *bitstream);
+
+/******************************************************************************\
+* Functions/macros for querying state information for bit streams.
+\******************************************************************************/
+
+/* Has EOF been encountered on a bit stream? */
+#define jpc_bitstream_eof(bitstream) \
+	((bitstream)->flags_ & JPC_BITSTREAM_EOF)
+
+/******************************************************************************\
+* Internals.
+\******************************************************************************/
+
+/* DO NOT DIRECTLY INVOKE ANY OF THE MACROS OR FUNCTIONS BELOW.  THEY ARE
+  FOR INTERNAL USE ONLY. */
+
+int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream);
+
+int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int v);
+
+int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream);
+
+#define	jpc_bitstream_getbit_macro(bitstream) \
+	  ((--(bitstream)->cnt_ >= 0) ? \
+	  ((int)(((bitstream)->buf_ >> (bitstream)->cnt_) & 1)) : \
+	  jpc_bitstream_fillbuf(bitstream))
+
+#define jpc_bitstream_putbit_macro(bitstream, bit) \
+	  ((--(bitstream)->cnt_ < 0) ? \
+	  ((bitstream)->buf_ = ((bitstream)->buf_ << 8) & 0xffff, \
+	  (bitstream)->cnt_ = ((bitstream)->buf_ == 0xff00) ? 6 : 7, \
+	  (bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \
+	  (jas_stream_putc((bitstream)->stream_, (bitstream)->buf_ >> 8) == EOF) \
+	  ? (EOF) : ((bit) & 1)) : \
+	  ((bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \
+	  (bit) & 1))
+
+#endif
--- /dev/null
+++ b/jpc_cod.h
@@ -1,0 +1,78 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef JPC_COD_H
+#define JPC_COD_H
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* The nominal word size used by this implementation. */
+#define	JPC_PREC	32
+
+#endif
--- /dev/null
+++ b/jpc_cs.c
@@ -1,0 +1,1699 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JPEG-2000 Code Stream Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_cs.h"
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+#include "jasper/jas_image.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Marker segment table entry. */
+typedef struct {
+	int id;
+	const char *name;
+	jpc_msops_t ops;
+} jpc_mstabent_t;
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static const jpc_mstabent_t *jpc_mstab_lookup(int id);
+
+static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static void jpc_poc_destroyparms(jpc_ms_t *ms);
+
+static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+
+static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+
+static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out);
+
+static void jpc_siz_destroyparms(jpc_ms_t *ms);
+static void jpc_qcd_destroyparms(jpc_ms_t *ms);
+static void jpc_qcc_destroyparms(jpc_ms_t *ms);
+static void jpc_cod_destroyparms(jpc_ms_t *ms);
+static void jpc_coc_destroyparms(jpc_ms_t *ms);
+static void jpc_unk_destroyparms(jpc_ms_t *ms);
+static void jpc_ppm_destroyparms(jpc_ms_t *ms);
+static void jpc_ppt_destroyparms(jpc_ms_t *ms);
+static void jpc_crg_destroyparms(jpc_ms_t *ms);
+static void jpc_com_destroyparms(jpc_ms_t *ms);
+
+static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms);
+static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
+  jas_stream_t *in, uint_fast16_t len);
+static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
+  jas_stream_t *out);
+static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms);
+static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+  jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms);
+static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+  jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+static const jpc_mstabent_t jpc_mstab[] = {
+	{JPC_MS_SOC, "SOC", {0, 0, 0, 0}},
+	{JPC_MS_SOT, "SOT", {0, jpc_sot_getparms, jpc_sot_putparms,
+	  jpc_sot_dumpparms}},
+	{JPC_MS_SOD, "SOD", {0, 0, 0, 0}},
+	{JPC_MS_EOC, "EOC", {0, 0, 0, 0}},
+	{JPC_MS_SIZ, "SIZ", {jpc_siz_destroyparms, jpc_siz_getparms,
+	  jpc_siz_putparms, jpc_siz_dumpparms}},
+	{JPC_MS_COD, "COD", {jpc_cod_destroyparms, jpc_cod_getparms,
+	  jpc_cod_putparms, jpc_cod_dumpparms}},
+	{JPC_MS_COC, "COC", {jpc_coc_destroyparms, jpc_coc_getparms,
+	  jpc_coc_putparms, jpc_coc_dumpparms}},
+	{JPC_MS_RGN, "RGN", {0, jpc_rgn_getparms, jpc_rgn_putparms,
+	  jpc_rgn_dumpparms}},
+	{JPC_MS_QCD, "QCD", {jpc_qcd_destroyparms, jpc_qcd_getparms,
+	  jpc_qcd_putparms, jpc_qcd_dumpparms}},
+	{JPC_MS_QCC, "QCC", {jpc_qcc_destroyparms, jpc_qcc_getparms,
+	  jpc_qcc_putparms, jpc_qcc_dumpparms}},
+	{JPC_MS_POC, "POC", {jpc_poc_destroyparms, jpc_poc_getparms,
+	  jpc_poc_putparms, jpc_poc_dumpparms}},
+	{JPC_MS_TLM, "TLM", {jpc_unk_destroyparms, jpc_unk_getparms, jpc_unk_putparms, 0}},
+	{JPC_MS_PLM, "PLM", {jpc_unk_destroyparms, jpc_unk_getparms, jpc_unk_putparms, 0}},
+	{JPC_MS_PPM, "PPM", {jpc_ppm_destroyparms, jpc_ppm_getparms,
+	  jpc_ppm_putparms, jpc_ppm_dumpparms}},
+	{JPC_MS_PPT, "PPT", {jpc_ppt_destroyparms, jpc_ppt_getparms,
+	  jpc_ppt_putparms, jpc_ppt_dumpparms}},
+	{JPC_MS_SOP, "SOP", {0, jpc_sop_getparms, jpc_sop_putparms,
+	  jpc_sop_dumpparms}},
+	{JPC_MS_EPH, "EPH", {0, 0, 0, 0}},
+	{JPC_MS_CRG, "CRG", {jpc_crg_destroyparms, jpc_crg_getparms,
+	  jpc_crg_putparms, jpc_crg_dumpparms}},
+	{JPC_MS_COM, "COM", {jpc_com_destroyparms, jpc_com_getparms,
+	  jpc_com_putparms, jpc_com_dumpparms}},
+	{-1, "UNKNOWN",  {jpc_unk_destroyparms, jpc_unk_getparms,
+	  jpc_unk_putparms, jpc_unk_dumpparms}}
+};
+
+/******************************************************************************\
+* Code stream manipulation functions.
+\******************************************************************************/
+
+/* Create a code stream state object. */
+jpc_cstate_t *jpc_cstate_create()
+{
+	jpc_cstate_t *cstate;
+	if (!(cstate = jas_malloc(sizeof(jpc_cstate_t)))) {
+		return 0;
+	}
+	cstate->numcomps = 0;
+	return cstate;
+}
+
+/* Destroy a code stream state object. */
+void jpc_cstate_destroy(jpc_cstate_t *cstate)
+{
+	jas_free(cstate);
+}
+
+/* Read a marker segment from a stream. */
+jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate)
+{
+	jpc_ms_t *ms;
+	const jpc_mstabent_t *mstabent;
+	jas_stream_t *tmpstream;
+
+	if (!(ms = jpc_ms_create(0))) {
+		return 0;
+	}
+
+	/* Get the marker type. */
+	if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN) {
+		jpc_ms_destroy(ms);
+		return 0;
+	}
+
+	mstabent = jpc_mstab_lookup(ms->id);
+	ms->ops = &mstabent->ops;
+
+	/* Get the marker segment length and parameters if present. */
+	/* Note: It is tacitly assumed that a marker segment cannot have
+	  parameters unless it has a length field.  That is, there cannot
+	  be a parameters field without a length field and vice versa. */
+	if (JPC_MS_HASPARMS(ms->id)) {
+		/* Get the length of the marker segment. */
+		if (jpc_getuint16(in, &ms->len) || ms->len < 3) {
+			jpc_ms_destroy(ms);
+			return 0;
+		}
+		/* Calculate the length of the marker segment parameters. */
+		ms->len -= 2;
+		/* Create and prepare a temporary memory stream from which to
+		  read the marker segment parameters. */
+		/* Note: This approach provides a simple way of ensuring that
+		  we never read beyond the end of the marker segment (even if
+		  the marker segment length is errantly set too small). */
+		if (!(tmpstream = jas_stream_memopen(0, 0))) {
+			jpc_ms_destroy(ms);
+			return 0;
+		}
+		if (jas_stream_copy(tmpstream, in, ms->len) ||
+		  jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) {
+			jas_stream_close(tmpstream);
+			jpc_ms_destroy(ms);
+			return 0;
+		}
+		/* Get the marker segment parameters. */
+		if ((*ms->ops->getparms)(ms, cstate, tmpstream)) {
+			ms->ops = 0;
+			jpc_ms_destroy(ms);
+			jas_stream_close(tmpstream);
+			return 0;
+		}
+
+		if (jas_getdbglevel() > 0) {
+			jpc_ms_dump(ms, stderr);
+		}
+
+		if (JAS_CAST(jas_ulong, jas_stream_tell(tmpstream)) != ms->len) {
+			jas_eprintf(
+			  "warning: trailing garbage in marker segment (%ld bytes)\n",
+			  ms->len - jas_stream_tell(tmpstream));
+		}
+
+		/* Close the temporary stream. */
+		jas_stream_close(tmpstream);
+
+	} else {
+		/* There are no marker segment parameters. */
+		ms->len = 0;
+
+		if (jas_getdbglevel() > 0) {
+			jpc_ms_dump(ms, stderr);
+		}
+	}
+
+	/* Update the code stream state information based on the type of
+	  marker segment read. */
+	/* Note: This is a bit of a hack, but I'm not going to define another
+	  type of virtual function for this one special case. */
+	if (ms->id == JPC_MS_SIZ) {
+		cstate->numcomps = ms->parms.siz.numcomps;
+	}
+
+	return ms;
+}
+
+/* Write a marker segment to a stream. */
+int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms)
+{
+	jas_stream_t *tmpstream;
+	int len;
+
+	/* Output the marker segment type. */
+	if (jpc_putuint16(out, ms->id)) {
+		return -1;
+	}
+
+	/* Output the marker segment length and parameters if necessary. */
+	if (ms->ops->putparms) {
+		/* Create a temporary stream in which to buffer the
+		  parameter data. */
+		if (!(tmpstream = jas_stream_memopen(0, 0))) {
+			return -1;
+		}
+		if ((*ms->ops->putparms)(ms, cstate, tmpstream)) {
+			jas_stream_close(tmpstream);
+			return -1;
+		}
+		/* Get the number of bytes of parameter data written. */
+		if ((len = jas_stream_tell(tmpstream)) < 0) {
+			jas_stream_close(tmpstream);
+			return -1;
+		}
+		ms->len = len;
+		/* Write the marker segment length and parameter data to
+		  the output stream. */
+		if (jas_stream_seek(tmpstream, 0, SEEK_SET) < 0 ||
+		  jpc_putuint16(out, ms->len + 2) ||
+		  jas_stream_copy(out, tmpstream, ms->len) < 0) {
+			jas_stream_close(tmpstream);
+			return -1;
+		}
+		/* Close the temporary stream. */
+		jas_stream_close(tmpstream);
+	}
+
+	/* This is a bit of a hack, but I'm not going to define another
+	  type of virtual function for this one special case. */
+	if (ms->id == JPC_MS_SIZ) {
+		cstate->numcomps = ms->parms.siz.numcomps;
+	}
+
+	if (jas_getdbglevel() > 0) {
+		jpc_ms_dump(ms, stderr);
+	}
+
+	return 0;
+}
+
+/******************************************************************************\
+* Marker segment operations.
+\******************************************************************************/
+
+/* Create a marker segment of the specified type. */
+jpc_ms_t *jpc_ms_create(int type)
+{
+	jpc_ms_t *ms;
+	const jpc_mstabent_t *mstabent;
+
+	if (!(ms = jas_malloc(sizeof(jpc_ms_t)))) {
+		return 0;
+	}
+	ms->id = type;
+	ms->len = 0;
+	mstabent = jpc_mstab_lookup(ms->id);
+	ms->ops = &mstabent->ops;
+	memset(&ms->parms, 0, sizeof(jpc_msparms_t));
+	return ms;
+}
+
+/* Destroy a marker segment. */
+void jpc_ms_destroy(jpc_ms_t *ms)
+{
+	if (ms->ops && ms->ops->destroyparms) {
+		(*ms->ops->destroyparms)(ms);
+	}
+	jas_free(ms);
+}
+
+/* Dump a marker segment to a stream for debugging. */
+void jpc_ms_dump(jpc_ms_t *ms, FILE *out)
+{
+	const jpc_mstabent_t *mstabent;
+	mstabent = jpc_mstab_lookup(ms->id);
+	fprintf(out, "type = 0x%04"PRIxFAST16" (%s);", ms->id, mstabent->name);
+	if (JPC_MS_HASPARMS(ms->id)) {
+		fprintf(out, " len = %"PRIuFAST16";", ms->len + 2);
+		if (ms->ops->dumpparms) {
+			(*ms->ops->dumpparms)(ms, out);
+		} else {
+			fprintf(out, "\n");
+		}
+	} else {
+		fprintf(out, "\n");
+	}
+}
+
+/******************************************************************************\
+* SOT marker segment operations.
+\******************************************************************************/
+
+static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_sot_t *sot = &ms->parms.sot;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	if (jpc_getuint16(in, &sot->tileno) ||
+	  jpc_getuint32(in, &sot->len) ||
+	  jpc_getuint8(in, &sot->partno) ||
+	  jpc_getuint8(in, &sot->numparts)) {
+		return -1;
+	}
+	if (sot->tileno > 65534 || sot->len < 12 || sot->partno > 254) {
+		return -1;
+	}
+	if (jas_stream_eof(in)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_sot_t *sot = &ms->parms.sot;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	if (jpc_putuint16(out, sot->tileno) ||
+	  jpc_putuint32(out, sot->len) ||
+	  jpc_putuint8(out, sot->partno) ||
+	  jpc_putuint8(out, sot->numparts)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_sot_t *sot = &ms->parms.sot;
+	fprintf(out,
+	  "tileno = %"PRIuFAST16"; len = %"PRIuFAST32"; partno = %d; numparts = %d\n",
+	  sot->tileno, sot->len, sot->partno, sot->numparts);
+	return 0;
+}
+
+/******************************************************************************\
+* SIZ marker segment operations.
+\******************************************************************************/
+
+static void jpc_siz_destroyparms(jpc_ms_t *ms)
+{
+	jpc_siz_t *siz = &ms->parms.siz;
+	if (siz->comps) {
+		jas_free(siz->comps);
+	}
+}
+
+static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+  jas_stream_t *in)
+{
+	jpc_siz_t *siz = &ms->parms.siz;
+	unsigned int i;
+	uint_fast8_t tmp;
+
+	siz->comps = 0;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	if (jpc_getuint16(in, &siz->caps) ||
+	  jpc_getuint32(in, &siz->width) ||
+	  jpc_getuint32(in, &siz->height) ||
+	  jpc_getuint32(in, &siz->xoff) ||
+	  jpc_getuint32(in, &siz->yoff) ||
+	  jpc_getuint32(in, &siz->tilewidth) ||
+	  jpc_getuint32(in, &siz->tileheight) ||
+	  jpc_getuint32(in, &siz->tilexoff) ||
+	  jpc_getuint32(in, &siz->tileyoff) ||
+	  jpc_getuint16(in, &siz->numcomps)) {
+		goto error;
+	}
+	if (!siz->width || !siz->height) {
+		jas_eprintf("reference grid cannot have zero area\n");
+		goto error;
+	}
+	if (!siz->tilewidth || !siz->tileheight) {
+		jas_eprintf("tile cannot have zero area\n");
+		goto error;
+	}
+	if (!siz->numcomps || siz->numcomps > 16384) {
+		jas_eprintf("number of components not in permissible range\n");
+		goto error;
+	}
+	if (siz->xoff >= siz->width) {
+		jas_eprintf("XOsiz not in permissible range\n");
+		goto error;
+	}
+	if (siz->yoff >= siz->height) {
+		jas_eprintf("YOsiz not in permissible range\n");
+		goto error;
+	}
+	if (siz->tilexoff > siz->xoff || siz->tilexoff + siz->tilewidth <= siz->xoff) {
+		jas_eprintf("XTOsiz not in permissible range\n");
+		goto error;
+	}
+	if (siz->tileyoff > siz->yoff || siz->tileyoff + siz->tileheight <= siz->yoff) {
+		jas_eprintf("YTOsiz not in permissible range\n");
+		goto error;
+	}
+
+	if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
+		goto error;
+	}
+	for (i = 0; i < siz->numcomps; ++i) {
+		if (jpc_getuint8(in, &tmp) ||
+		  jpc_getuint8(in, &siz->comps[i].hsamp) ||
+		  jpc_getuint8(in, &siz->comps[i].vsamp)) {
+			goto error;
+		}
+		if (siz->comps[i].hsamp == 0) {
+			jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
+			goto error;
+		}
+		if (siz->comps[i].vsamp == 0) {
+			jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
+			goto error;
+		}
+		siz->comps[i].sgnd = (tmp >> 7) & 1;
+		siz->comps[i].prec = (tmp & 0x7f) + 1;
+		/* we need at least 1 bit of precision for unsigned
+		   samples and 2 bits for signed samples */
+		if (siz->comps[i].prec < 1U + siz->comps[i].sgnd ||
+		    siz->comps[i].prec > 38) {
+			jas_eprintf("invalid component bit depth %d\n", siz->comps[i].prec);
+			goto error;
+		}
+	}
+	if (jas_stream_eof(in)) {
+		goto error;
+	}
+	return 0;
+
+error:
+	if (siz->comps) {
+		jas_free(siz->comps);
+	}
+	return -1;
+}
+
+static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_siz_t *siz = &ms->parms.siz;
+	unsigned int i;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	assert(siz->width && siz->height && siz->tilewidth &&
+	  siz->tileheight && siz->numcomps);
+	if (jpc_putuint16(out, siz->caps) ||
+	  jpc_putuint32(out, siz->width) ||
+	  jpc_putuint32(out, siz->height) ||
+	  jpc_putuint32(out, siz->xoff) ||
+	  jpc_putuint32(out, siz->yoff) ||
+	  jpc_putuint32(out, siz->tilewidth) ||
+	  jpc_putuint32(out, siz->tileheight) ||
+	  jpc_putuint32(out, siz->tilexoff) ||
+	  jpc_putuint32(out, siz->tileyoff) ||
+	  jpc_putuint16(out, siz->numcomps)) {
+		return -1;
+	}
+	for (i = 0; i < siz->numcomps; ++i) {
+		if (jpc_putuint8(out, ((siz->comps[i].sgnd & 1) << 7) |
+		  ((siz->comps[i].prec - 1) & 0x7f)) ||
+		  jpc_putuint8(out, siz->comps[i].hsamp) ||
+		  jpc_putuint8(out, siz->comps[i].vsamp)) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_siz_t *siz = &ms->parms.siz;
+	unsigned int i;
+	fprintf(out, "caps = 0x%02"PRIxFAST16";\n", siz->caps);
+	fprintf(out, "width = %"PRIuFAST32"; height = %"PRIuFAST32"; xoff = %"PRIuFAST32"; yoff = %" PRIuFAST32 ";\n",
+	  siz->width, siz->height, siz->xoff, siz->yoff);
+	fprintf(out, "tilewidth = %"PRIuFAST32"; tileheight = %"PRIuFAST32"; "
+	  "tilexoff = %"PRIuFAST32"; tileyoff = %" PRIuFAST32 ";\n",
+	  siz->tilewidth, siz->tileheight, siz->tilexoff, siz->tileyoff);
+	fprintf(out, "numcomps = %"PRIuFAST16";\n", siz->numcomps);
+	for (i = 0; i < siz->numcomps; ++i) {
+		fprintf(out, "prec[%d] = %d; sgnd[%d] = %d; hsamp[%d] = %d; "
+		  "vsamp[%d] = %d\n", i, siz->comps[i].prec, i,
+		  siz->comps[i].sgnd, i, siz->comps[i].hsamp, i,
+		  siz->comps[i].vsamp);
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* COD marker segment operations.
+\******************************************************************************/
+
+static void jpc_cod_destroyparms(jpc_ms_t *ms)
+{
+	jpc_cod_t *cod = &ms->parms.cod;
+	jpc_cox_destroycompparms(&cod->compparms);
+}
+
+static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_cod_t *cod = &ms->parms.cod;
+	if (jpc_getuint8(in, &cod->csty)) {
+		return -1;
+	}
+	if (jpc_getuint8(in, &cod->prg) ||
+	  jpc_getuint16(in, &cod->numlyrs) ||
+	  jpc_getuint8(in, &cod->mctrans)) {
+		return -1;
+	}
+	if (cod->numlyrs < 1) {
+		return -1;
+	}
+	if (jpc_cox_getcompparms(ms, cstate, in,
+	  (cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) {
+		return -1;
+	}
+	if (jas_stream_eof(in)) {
+		jpc_cod_destroyparms(ms);
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_cod_t *cod = &ms->parms.cod;
+	assert(cod->numlyrs > 0 && cod->compparms.numdlvls <= 32);
+	assert(cod->compparms.numdlvls == cod->compparms.numrlvls - 1);
+	if (jpc_putuint8(out, cod->compparms.csty) ||
+	  jpc_putuint8(out, cod->prg) ||
+	  jpc_putuint16(out, cod->numlyrs) ||
+	  jpc_putuint8(out, cod->mctrans)) {
+		return -1;
+	}
+	if (jpc_cox_putcompparms(ms, cstate, out,
+	  (cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_cod_t *cod = &ms->parms.cod;
+	int i;
+	fprintf(out, "csty = 0x%02x;\n", cod->compparms.csty);
+	fprintf(out, "numdlvls = %d; qmfbid = %d; mctrans = %d\n",
+	  cod->compparms.numdlvls, cod->compparms.qmfbid, cod->mctrans);
+	fprintf(out, "prg = %d; numlyrs = %"PRIuFAST16";\n",
+	  cod->prg, cod->numlyrs);
+	fprintf(out, "cblkwidthval = %d; cblkheightval = %d; "
+	  "cblksty = 0x%02x;\n", cod->compparms.cblkwidthval, cod->compparms.cblkheightval,
+	  cod->compparms.cblksty);
+	if (cod->csty & JPC_COX_PRT) {
+		for (i = 0; i < cod->compparms.numrlvls; ++i) {
+			jas_eprintf("prcwidth[%d] = %d, prcheight[%d] = %d\n",
+			  i, cod->compparms.rlvls[i].parwidthval,
+			  i, cod->compparms.rlvls[i].parheightval);
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* COC marker segment operations.
+\******************************************************************************/
+
+static void jpc_coc_destroyparms(jpc_ms_t *ms)
+{
+	jpc_coc_t *coc = &ms->parms.coc;
+	jpc_cox_destroycompparms(&coc->compparms);
+}
+
+static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_coc_t *coc = &ms->parms.coc;
+	uint_fast8_t tmp;
+	if (cstate->numcomps <= 256) {
+		if (jpc_getuint8(in, &tmp)) {
+			return -1;
+		}
+		coc->compno = tmp;
+	} else {
+		if (jpc_getuint16(in, &coc->compno)) {
+			return -1;
+		}
+	}
+	if (jpc_getuint8(in, &coc->compparms.csty)) {
+		return -1;
+	}
+	if (jpc_cox_getcompparms(ms, cstate, in,
+	  (coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) {
+		return -1;
+	}
+	if (jas_stream_eof(in)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_coc_t *coc = &ms->parms.coc;
+	assert(coc->compparms.numdlvls <= 32);
+	if (cstate->numcomps <= 256) {
+		if (jpc_putuint8(out, coc->compno)) {
+			return -1;
+		}
+	} else {
+		if (jpc_putuint16(out, coc->compno)) {
+			return -1;
+		}
+	}
+	if (jpc_putuint8(out, coc->compparms.csty)) {
+		return -1;
+	}
+	if (jpc_cox_putcompparms(ms, cstate, out,
+	  (coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_coc_t *coc = &ms->parms.coc;
+	fprintf(out, "compno = %"PRIuFAST16"; csty = 0x%02x; numdlvls = %d;\n",
+	  coc->compno, coc->compparms.csty, coc->compparms.numdlvls);
+	fprintf(out, "cblkwidthval = %d; cblkheightval = %d; "
+	  "cblksty = 0x%02x; qmfbid = %d;\n", coc->compparms.cblkwidthval,
+	  coc->compparms.cblkheightval, coc->compparms.cblksty, coc->compparms.qmfbid);
+	return 0;
+}
+/******************************************************************************\
+* COD/COC marker segment operation helper functions.
+\******************************************************************************/
+
+static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms)
+{
+	/* Eliminate compiler warning about unused variables. */
+	USED(compparms);
+}
+
+static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+  jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms)
+{
+	uint_fast8_t tmp;
+	int i;
+
+	/* Eliminate compiler warning about unused variables. */
+	USED(ms);
+	USED(cstate);
+
+	if (jpc_getuint8(in, &compparms->numdlvls) ||
+	  jpc_getuint8(in, &compparms->cblkwidthval) ||
+	  jpc_getuint8(in, &compparms->cblkheightval) ||
+	  jpc_getuint8(in, &compparms->cblksty) ||
+	  jpc_getuint8(in, &compparms->qmfbid)) {
+		return -1;
+	}
+	if (compparms->numdlvls > 32) {
+		goto error;
+	}
+	if (compparms->qmfbid != JPC_COX_INS &&
+	    compparms->qmfbid != JPC_COX_RFT)
+		goto error;
+	compparms->numrlvls = compparms->numdlvls + 1;
+	if (compparms->numrlvls > JPC_MAXRLVLS) {
+		goto error;
+	}
+	if (prtflag) {
+		for (i = 0; i < compparms->numrlvls; ++i) {
+			if (jpc_getuint8(in, &tmp)) {
+				goto error;
+			}
+			compparms->rlvls[i].parwidthval = tmp & 0xf;
+			compparms->rlvls[i].parheightval = (tmp >> 4) & 0xf;
+		}
+		/* Sigh.
+		This bit should be in the same field in both COC and COD mrk segs. */
+		compparms->csty |= JPC_COX_PRT;
+	}
+	if (jas_stream_eof(in)) {
+		goto error;
+	}
+	return 0;
+error:
+	jpc_cox_destroycompparms(compparms);
+	return -1;
+}
+
+static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+  jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms)
+{
+	int i;
+	assert(compparms->numdlvls <= 32);
+
+	/* Eliminate compiler warning about unused variables. */
+	USED(ms);
+	USED(cstate);
+
+	if (jpc_putuint8(out, compparms->numdlvls) ||
+	  jpc_putuint8(out, compparms->cblkwidthval) ||
+	  jpc_putuint8(out, compparms->cblkheightval) ||
+	  jpc_putuint8(out, compparms->cblksty) ||
+	  jpc_putuint8(out, compparms->qmfbid)) {
+		return -1;
+	}
+	if (prtflag) {
+		for (i = 0; i < compparms->numrlvls; ++i) {
+			if (jpc_putuint8(out,
+			  ((compparms->rlvls[i].parheightval & 0xf) << 4) |
+			  (compparms->rlvls[i].parwidthval & 0xf))) {
+				return -1;
+			}
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* RGN marker segment operations.
+\******************************************************************************/
+
+static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_rgn_t *rgn = &ms->parms.rgn;
+	uint_fast8_t tmp;
+	if (cstate->numcomps <= 256) {
+		if (jpc_getuint8(in, &tmp)) {
+			return -1;
+		}
+		rgn->compno = tmp;
+	} else {
+		if (jpc_getuint16(in, &rgn->compno)) {
+			return -1;
+		}
+	}
+	if (jpc_getuint8(in, &rgn->roisty) ||
+	  jpc_getuint8(in, &rgn->roishift)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_rgn_t *rgn = &ms->parms.rgn;
+	if (cstate->numcomps <= 256) {
+		if (jpc_putuint8(out, rgn->compno)) {
+			return -1;
+		}
+	} else {
+		if (jpc_putuint16(out, rgn->compno)) {
+			return -1;
+		}
+	}
+	if (jpc_putuint8(out, rgn->roisty) ||
+	  jpc_putuint8(out, rgn->roishift)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_rgn_t *rgn = &ms->parms.rgn;
+	fprintf(out, "compno = %"PRIuFAST16"; roisty = %d; roishift = %d\n",
+	  rgn->compno, rgn->roisty, rgn->roishift);
+	return 0;
+}
+
+/******************************************************************************\
+* QCD marker segment operations.
+\******************************************************************************/
+
+static void jpc_qcd_destroyparms(jpc_ms_t *ms)
+{
+	jpc_qcd_t *qcd = &ms->parms.qcd;
+	jpc_qcx_destroycompparms(&qcd->compparms);
+}
+
+static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms;
+	return jpc_qcx_getcompparms(compparms, cstate, in, ms->len);
+}
+
+static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms;
+	return jpc_qcx_putcompparms(compparms, cstate, out);
+}
+
+static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_qcd_t *qcd = &ms->parms.qcd;
+	int i;
+	fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
+	  (int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
+	for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
+		fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
+		  i, JAS_CAST(unsigned, JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i])),
+		  i, JAS_CAST(unsigned, JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])));
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* QCC marker segment operations.
+\******************************************************************************/
+
+static void jpc_qcc_destroyparms(jpc_ms_t *ms)
+{
+	jpc_qcc_t *qcc = &ms->parms.qcc;
+	jpc_qcx_destroycompparms(&qcc->compparms);
+}
+
+static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_qcc_t *qcc = &ms->parms.qcc;
+	uint_fast8_t tmp;
+	int len;
+	len = ms->len;
+	if (cstate->numcomps <= 256) {
+		if (jpc_getuint8(in, &tmp)) {
+			return -1;
+		}
+		qcc->compno = tmp;
+		--len;
+	} else {
+		if (jpc_getuint16(in, &qcc->compno)) {
+			return -1;
+		}
+		len -= 2;
+	}
+	if (jpc_qcx_getcompparms(&qcc->compparms, cstate, in, len)) {
+		return -1;
+	}
+	if (jas_stream_eof(in)) {
+		jpc_qcc_destroyparms(ms);
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_qcc_t *qcc = &ms->parms.qcc;
+	if (cstate->numcomps <= 256) {
+		if (jpc_putuint8(out, qcc->compno)) {
+			return -1;
+		}
+	} else {
+		if (jpc_putuint16(out, qcc->compno)) {
+			return -1;
+		}
+	}
+	if (jpc_qcx_putcompparms(&qcc->compparms, cstate, out)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_qcc_t *qcc = &ms->parms.qcc;
+	int i;
+	fprintf(out, "compno = %"PRIuFAST16"; qntsty = %d; numguard = %d; "
+	  "numstepsizes = %d\n", qcc->compno, qcc->compparms.qntsty, qcc->compparms.numguard,
+	  qcc->compparms.numstepsizes);
+	for (i = 0; i < qcc->compparms.numstepsizes; ++i) {
+		fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
+		  i, (unsigned) JPC_QCX_GETEXPN(qcc->compparms.stepsizes[i]),
+		  i, (unsigned) JPC_QCX_GETMANT(qcc->compparms.stepsizes[i]));
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* QCD/QCC marker segment helper functions.
+\******************************************************************************/
+
+static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms)
+{
+	if (compparms->stepsizes) {
+		jas_free(compparms->stepsizes);
+	}
+}
+
+static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
+  jas_stream_t *in, uint_fast16_t len)
+{
+	uint_fast8_t tmp;
+	int n;
+	int i;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	n = 0;
+	if (jpc_getuint8(in, &tmp)) {
+		return -1;
+	}
+	++n;
+	compparms->qntsty = tmp & 0x1f;
+	compparms->numguard = (tmp >> 5) & 7;
+	switch (compparms->qntsty) {
+	case JPC_QCX_SIQNT:
+		compparms->numstepsizes = 1;
+		break;
+	case JPC_QCX_NOQNT:
+		compparms->numstepsizes = (len - n);
+		break;
+	case JPC_QCX_SEQNT:
+		/* XXX - this is a hack */
+		compparms->numstepsizes = (len - n) / 2;
+		break;
+	}
+	/* Ensure that the step size array is sufficiently large. */
+	if (compparms->numstepsizes > 3 * JPC_MAXRLVLS + 1) {
+		jpc_qcx_destroycompparms(compparms);
+		return -1;
+	}
+	if (compparms->numstepsizes > 0) {
+		if (!(compparms->stepsizes = jas_alloc2(compparms->numstepsizes,
+		  sizeof(uint_fast16_t)))) {
+			jpc_qcx_destroycompparms(compparms);
+			return -1;
+		}
+		for (i = 0; i < compparms->numstepsizes; ++i) {
+			if (compparms->qntsty == JPC_QCX_NOQNT) {
+				if (jpc_getuint8(in, &tmp)) {
+					jpc_qcx_destroycompparms(compparms);
+					return -1;
+				}
+				compparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3);
+			} else {
+				if (jpc_getuint16(in, &compparms->stepsizes[i])) {
+					jpc_qcx_destroycompparms(compparms);
+					return -1;
+				}
+			}
+		}
+	} else {
+		compparms->stepsizes = 0;
+	}
+	if (jas_stream_error(in) || jas_stream_eof(in)) {
+		jpc_qcx_destroycompparms(compparms);
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
+  jas_stream_t *out)
+{
+	int i;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	if (jpc_putuint8(out, ((compparms->numguard & 7) << 5) | compparms->qntsty)) {
+		return -1;
+	}
+	for (i = 0; i < compparms->numstepsizes; ++i) {
+		if (compparms->qntsty == JPC_QCX_NOQNT) {
+			if (jpc_putuint8(out, JPC_QCX_GETEXPN(
+			  compparms->stepsizes[i]) << 3)) {
+				return -1;
+			}
+		} else {
+			if (jpc_putuint16(out, compparms->stepsizes[i])) {
+				return -1;
+			}
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* SOP marker segment operations.
+\******************************************************************************/
+
+static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_sop_t *sop = &ms->parms.sop;
+
+	/* Eliminate compiler warning about unused variable. */
+	(void)cstate;
+
+	if (jpc_getuint16(in, &sop->seqno)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_sop_t *sop = &ms->parms.sop;
+
+	/* Eliminate compiler warning about unused variable. */
+	(void)cstate;
+
+	if (jpc_putuint16(out, sop->seqno)) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_sop_t *sop = &ms->parms.sop;
+	fprintf(out, "seqno = %"PRIuFAST16";\n", sop->seqno);
+	return 0;
+}
+
+/******************************************************************************\
+* PPM marker segment operations.
+\******************************************************************************/
+
+static void jpc_ppm_destroyparms(jpc_ms_t *ms)
+{
+	jpc_ppm_t *ppm = &ms->parms.ppm;
+	if (ppm->data) {
+		jas_free(ppm->data);
+	}
+}
+
+static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_ppm_t *ppm = &ms->parms.ppm;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	ppm->data = 0;
+
+	if (ms->len < 1) {
+		goto error;
+	}
+	if (jpc_getuint8(in, &ppm->ind)) {
+		goto error;
+	}
+
+	ppm->len = ms->len - 1;
+	if (ppm->len > 0) {
+		if (!(ppm->data = jas_malloc(ppm->len))) {
+			goto error;
+		}
+		if (JAS_CAST(jas_uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) {
+			goto error;
+		}
+	} else {
+		ppm->data = 0;
+	}
+	return 0;
+
+error:
+	jpc_ppm_destroyparms(ms);
+	return -1;
+}
+
+static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_ppm_t *ppm = &ms->parms.ppm;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	if (JAS_CAST(jas_uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_ppm_t *ppm = &ms->parms.ppm;
+	fprintf(out, "ind=%d; len = %"PRIuFAST16";\n", ppm->ind, ppm->len);
+	if (ppm->len > 0) {
+		fprintf(out, "data =\n");
+		jas_memdump(out, ppm->data, ppm->len);
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* PPT marker segment operations.
+\******************************************************************************/
+
+static void jpc_ppt_destroyparms(jpc_ms_t *ms)
+{
+	jpc_ppt_t *ppt = &ms->parms.ppt;
+	if (ppt->data) {
+		jas_free(ppt->data);
+	}
+}
+
+static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_ppt_t *ppt = &ms->parms.ppt;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	ppt->data = 0;
+
+	if (ms->len < 1) {
+		goto error;
+	}
+	if (jpc_getuint8(in, &ppt->ind)) {
+		goto error;
+	}
+	ppt->len = ms->len - 1;
+	if (ppt->len > 0) {
+		if (!(ppt->data = jas_malloc(ppt->len))) {
+			goto error;
+		}
+		if (jas_stream_read(in, (char *) ppt->data, ppt->len) != ppt->len) {
+			goto error;
+		}
+	} else {
+		ppt->data = 0;
+	}
+	return 0;
+
+error:
+	jpc_ppt_destroyparms(ms);
+	return -1;
+}
+
+static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_ppt_t *ppt = &ms->parms.ppt;
+
+	/* Eliminate compiler warning about unused variable. */
+	(void)cstate;
+
+	if (jpc_putuint8(out, ppt->ind)) {
+		return -1;
+	}
+	if (jas_stream_write(out, (char *) ppt->data, ppt->len) != ppt->len) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_ppt_t *ppt = &ms->parms.ppt;
+	fprintf(out, "ind=%d; len = %"PRIuFAST32";\n", ppt->ind, ppt->len);
+	if (ppt->len > 0) {
+		fprintf(out, "data =\n");
+		jas_memdump(out, ppt->data, ppt->len);
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* POC marker segment operations.
+\******************************************************************************/
+
+static void jpc_poc_destroyparms(jpc_ms_t *ms)
+{
+	jpc_poc_t *poc = &ms->parms.poc;
+	if (poc->pchgs) {
+		jas_free(poc->pchgs);
+	}
+}
+
+static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_poc_t *poc = &ms->parms.poc;
+	jpc_pocpchg_t *pchg;
+	int pchgno;
+	uint_fast8_t tmp;
+	poc->numpchgs = (cstate->numcomps > 256) ? (ms->len / 9) :
+	  (ms->len / 7);
+	if (!(poc->pchgs = jas_alloc2(poc->numpchgs, sizeof(jpc_pocpchg_t)))) {
+		goto error;
+	}
+	for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno,
+	  ++pchg) {
+		if (jpc_getuint8(in, &pchg->rlvlnostart)) {
+			goto error;
+		}
+		if (cstate->numcomps > 256) {
+			if (jpc_getuint16(in, &pchg->compnostart)) {
+				goto error;
+			}
+		} else {
+			if (jpc_getuint8(in, &tmp)) {
+				goto error;
+			};
+			pchg->compnostart = tmp;
+		}
+		if (jpc_getuint16(in, &pchg->lyrnoend) ||
+		  jpc_getuint8(in, &pchg->rlvlnoend)) {
+			goto error;
+		}
+		if (cstate->numcomps > 256) {
+			if (jpc_getuint16(in, &pchg->compnoend)) {
+				goto error;
+			}
+		} else {
+			if (jpc_getuint8(in, &tmp)) {
+				goto error;
+			}
+			pchg->compnoend = tmp;
+		}
+		if (jpc_getuint8(in, &pchg->prgord)) {
+			goto error;
+		}
+		if (pchg->rlvlnostart > pchg->rlvlnoend ||
+		  pchg->compnostart > pchg->compnoend) {
+			goto error;
+		}
+	}
+	return 0;
+
+error:
+	jpc_poc_destroyparms(ms);
+	return -1;
+}
+
+static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_poc_t *poc = &ms->parms.poc;
+	jpc_pocpchg_t *pchg;
+	int pchgno;
+	for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno,
+	  ++pchg) {
+		if (jpc_putuint8(out, pchg->rlvlnostart) ||
+		  ((cstate->numcomps > 256) ?
+		  jpc_putuint16(out, pchg->compnostart) :
+		  jpc_putuint8(out, pchg->compnostart)) ||
+		  jpc_putuint16(out, pchg->lyrnoend) ||
+		  jpc_putuint8(out, pchg->rlvlnoend) ||
+		  ((cstate->numcomps > 256) ?
+		  jpc_putuint16(out, pchg->compnoend) :
+		  jpc_putuint8(out, pchg->compnoend)) ||
+		  jpc_putuint8(out, pchg->prgord)) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_poc_t *poc = &ms->parms.poc;
+	jpc_pocpchg_t *pchg;
+	int pchgno;
+	for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs;
+	  ++pchgno, ++pchg) {
+		fprintf(out, "po[%d] = %d; ", pchgno, pchg->prgord);
+		fprintf(out, "cs[%d] = %"PRIuFAST16"; ce[%d] = %"PRIuFAST16"; ",
+		  pchgno, pchg->compnostart, pchgno, pchg->compnoend);
+		fprintf(out, "rs[%d] = %d; re[%d] = %d; ",
+		  pchgno, pchg->rlvlnostart, pchgno, pchg->rlvlnoend);
+		fprintf(out, "le[%d] = %"PRIuFAST16"\n", pchgno, pchg->lyrnoend);
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* CRG marker segment operations.
+\******************************************************************************/
+
+static void jpc_crg_destroyparms(jpc_ms_t *ms)
+{
+	jpc_crg_t *crg = &ms->parms.crg;
+	if (crg->comps) {
+		jas_free(crg->comps);
+	}
+}
+
+static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_crg_t *crg = &ms->parms.crg;
+	jpc_crgcomp_t *comp;
+	uint_fast16_t compno;
+	crg->numcomps = cstate->numcomps;
+	if (!(crg->comps = jas_alloc2(cstate->numcomps, sizeof(jpc_crgcomp_t)))) {
+		return -1;
+	}
+	for (compno = 0, comp = crg->comps; compno < cstate->numcomps;
+	  ++compno, ++comp) {
+		if (jpc_getuint16(in, &comp->hoff) ||
+		  jpc_getuint16(in, &comp->voff)) {
+			jpc_crg_destroyparms(ms);
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_crg_t *crg = &ms->parms.crg;
+	int compno;
+	jpc_crgcomp_t *comp;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
+	  ++comp) {
+		if (jpc_putuint16(out, comp->hoff) ||
+		  jpc_putuint16(out, comp->voff)) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_crg_t *crg = &ms->parms.crg;
+	int compno;
+	jpc_crgcomp_t *comp;
+	for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
+	  ++comp) {
+		fprintf(out, "hoff[%d] = %"PRIuFAST16"; voff[%d] = %"PRIuFAST16"\n",
+		  compno, comp->hoff, compno, comp->voff);
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Operations for COM marker segment.
+\******************************************************************************/
+
+static void jpc_com_destroyparms(jpc_ms_t *ms)
+{
+	jpc_com_t *com = &ms->parms.com;
+	if (com->data) {
+		jas_free(com->data);
+	}
+}
+
+static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_com_t *com = &ms->parms.com;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	if (jpc_getuint16(in, &com->regid)) {
+		return -1;
+	}
+	com->len = ms->len - 2;
+	if (com->len > 0) {
+		if (!(com->data = jas_malloc(com->len))) {
+			return -1;
+		}
+		if (jas_stream_read(in, com->data, com->len) != com->len) {
+			return -1;
+		}
+	} else {
+		com->data = 0;
+	}
+	return 0;
+}
+
+static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	jpc_com_t *com = &ms->parms.com;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	if (jpc_putuint16(out, com->regid)) {
+		return -1;
+	}
+	if (jas_stream_write(out, com->data, com->len) != com->len) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	jpc_com_t *com = &ms->parms.com;
+	unsigned int i;
+	int printable;
+	fprintf(out, "regid = %"PRIuFAST16";\n", com->regid);
+	printable = 1;
+	for (i = 0; i < com->len; ++i) {
+		if (!isprint(com->data[i])) {
+			printable = 0;
+			break;
+		}
+	}
+	if (printable) {
+		fprintf(out, "data = ");
+		fwrite(com->data, sizeof(char), com->len, out);
+		fprintf(out, "\n");
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Operations for unknown types of marker segments.
+\******************************************************************************/
+
+static void jpc_unk_destroyparms(jpc_ms_t *ms)
+{
+	jpc_unk_t *unk = &ms->parms.unk;
+	if (unk->data) {
+		jas_free(unk->data);
+	}
+}
+
+static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+	jpc_unk_t *unk = &ms->parms.unk;
+
+	unk->data = 0;
+
+	/* Eliminate compiler warning about unused variables. */
+	(void)cstate;
+
+	if (ms->len > 0) {
+		if (!(unk->data = jas_alloc2(ms->len, sizeof(unsigned char)))) {
+			return -1;
+		}
+		if (jas_stream_read(in, (char *) unk->data, ms->len) != ms->len) {
+			jas_free(unk->data);
+			return -1;
+		}
+		unk->len = ms->len;
+	} else {
+		unk->data = 0;
+		unk->len = 0;
+	}
+	return 0;
+}
+
+static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+	/* Eliminate compiler warning about unused variables. */
+	USED(cstate);
+	USED(ms);
+	USED(out);
+
+	/* If this function is called, we are trying to write an unsupported
+	  type of marker segment.  Return with an error indication.  */
+	return -1;
+}
+
+static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+	unsigned int i;
+	jpc_unk_t *unk = &ms->parms.unk;
+	for (i = 0; i < unk->len; ++i) {
+		fprintf(out, "%02x ", unk->data[i]);
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Primitive I/O operations.
+\******************************************************************************/
+
+int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val)
+{
+	int c;
+	if ((c = jas_stream_getc(in)) == EOF) {
+		return -1;
+	}
+	if (val) {
+		*val = c;
+	}
+	return 0;
+}
+
+int jpc_putuint8(jas_stream_t *out, uint_fast8_t val)
+{
+	if (jas_stream_putc(out, val & 0xff) == EOF) {
+		return -1;
+	}
+	return 0;
+}
+
+int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val)
+{
+	jas_uchar buffer[2];
+	if (jas_stream_read(in, buffer, sizeof(buffer)) != sizeof(buffer))
+		return -1;
+	*val = (uint_fast16_t)buffer[0] << 8 | (uint_fast16_t)buffer[1];
+	return 0;
+}
+
+int jpc_putuint16(jas_stream_t *out, uint_fast16_t val)
+{
+	if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
+	  jas_stream_putc(out, val & 0xff) == EOF) {
+		return -1;
+	}
+	return 0;
+}
+
+int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val)
+{
+	jas_uchar buffer[4];
+	if (jas_stream_read(in, buffer, sizeof(buffer)) != sizeof(buffer))
+		return -1;
+	*val = (uint_fast32_t)buffer[0] << 24 | (uint_fast32_t)buffer[1] << 16
+		| (uint_fast32_t)buffer[2] << 8 | (uint_fast32_t)buffer[3];
+	return 0;
+}
+
+int jpc_putuint32(jas_stream_t *out, uint_fast32_t val)
+{
+	if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF ||
+	  jas_stream_putc(out, (val >> 16) & 0xff) == EOF ||
+	  jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
+	  jas_stream_putc(out, val & 0xff) == EOF) {
+		return -1;
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Miscellany
+\******************************************************************************/
+
+static const jpc_mstabent_t *jpc_mstab_lookup(int id)
+{
+	const jpc_mstabent_t *mstabent;
+	for (mstabent = jpc_mstab;; ++mstabent) {
+		if (mstabent->id == id || mstabent->id < 0) {
+			return mstabent;
+		}
+	}
+}
+
+int jpc_validate(jas_stream_t *in)
+{
+	unsigned char buf[2];
+
+	assert(JAS_STREAM_MAXPUTBACK >= 2);
+
+	if (jas_stream_peek(in, buf, sizeof(buf)) != sizeof(buf))
+		return -1;
+
+	if (buf[0] == (JPC_MS_SOC >> 8) && buf[1] == (JPC_MS_SOC & 0xff)) {
+		return 0;
+	}
+	return -1;
+}
+
+int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long len)
+{
+	return jas_stream_copy(out, in, len);
+}
+
+int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long len)
+{
+	return jas_stream_copy(out, in, len);
+}
--- /dev/null
+++ b/jpc_cs.h
@@ -1,0 +1,798 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JPEG-2000 Code Stream Library
+ *
+ * $Id$
+ */
+
+#ifndef JPC_CS_H
+#define JPC_CS_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_stream.h"
+
+/******************************************************************************\
+* Constants and Types.
+\******************************************************************************/
+
+/* The maximum number of resolution levels. */
+#define	JPC_MAXRLVLS	33
+
+/* The maximum number of bands. */
+#define	JPC_MAXBANDS	(3 * JPC_MAXRLVLS + 1)
+
+/* The maximum number of layers. */
+#define JPC_MAXLYRS	16384
+
+/**************************************\
+* Code stream.
+\**************************************/
+
+/*
+ * Code stream states.
+ */
+
+/* Initial. */
+#define	JPC_CS_INIT	0
+/* Main header. */
+#define	JPC_CS_MHDR	1
+/* Tile-part header. */
+#define	JPC_CS_THDR	2
+/* Main trailer. */
+#define	JPC_CS_MTLR	3
+/* Tile-part data. */
+#define	JPC_CS_TDATA	4
+
+/*
+ * Unfortunately, the code stream syntax was not designed in such a way that
+ * any given marker segment can be correctly decoded without additional state
+ * derived from previously decoded marker segments.
+ * For example, a RGN/COC/QCC marker segment cannot be decoded unless the
+ * number of components is known.
+ */
+
+/*
+ * Code stream state information.
+ */
+
+typedef struct {
+
+	/* The number of components. */
+	uint_fast16_t numcomps;
+
+} jpc_cstate_t;
+
+/**************************************\
+* SOT marker segment parameters.
+\**************************************/
+
+typedef struct {
+
+	/* The tile number. */
+	uint_fast16_t tileno;
+
+	/* The combined length of the marker segment and its auxilary data
+	  (i.e., packet data). */
+	uint_fast32_t len;
+
+	/* The tile-part instance. */
+	uint_fast8_t partno;
+
+	/* The number of tile-parts. */
+	uint_fast8_t numparts;
+
+} jpc_sot_t;
+
+/**************************************\
+* SIZ marker segment parameters.
+\**************************************/
+
+/* Per component information. */
+
+typedef struct {
+
+	/* The precision of the samples. */
+	uint_fast8_t prec;
+
+	/* The signedness of the samples. */
+	uint_fast8_t sgnd;
+
+	/* The horizontal separation of samples with respect to the reference
+	  grid. */
+	uint_fast8_t hsamp;
+
+	/* The vertical separation of samples with respect to the reference
+	  grid. */
+	uint_fast8_t vsamp;
+
+} jpc_sizcomp_t;
+
+/* SIZ marker segment parameters. */
+
+typedef struct {
+
+	/* The code stream capabilities. */
+	uint_fast16_t caps;
+
+	/* The width of the image in units of the reference grid. */
+	uint_fast32_t width;
+
+	/* The height of the image in units of the reference grid. */
+	uint_fast32_t height;
+
+	/* The horizontal offset from the origin of the reference grid to the
+	  left side of the image area. */
+	uint_fast32_t xoff;
+
+	/* The vertical offset from the origin of the reference grid to the
+	  top side of the image area. */
+	uint_fast32_t yoff;
+
+	/* The nominal width of a tile in units of the reference grid. */
+	uint_fast32_t tilewidth;
+
+	/* The nominal height of a tile in units of the reference grid. */
+	uint_fast32_t tileheight;
+
+	/* The horizontal offset from the origin of the reference grid to the
+	  left side of the first tile. */
+	uint_fast32_t tilexoff;
+
+	/* The vertical offset from the origin of the reference grid to the
+	  top side of the first tile. */
+	uint_fast32_t tileyoff;
+
+	/* The number of components. */
+	uint_fast16_t numcomps;
+
+	/* The per-component information. */
+	jpc_sizcomp_t *comps;
+
+} jpc_siz_t;
+
+/**************************************\
+* COD marker segment parameters.
+\**************************************/
+
+/*
+ * Coding style constants.
+ */
+
+/* Precincts may be used. */
+#define	JPC_COX_PRT	0x01
+/* SOP marker segments may be used. */
+#define	JPC_COD_SOP	0x02
+/* EPH marker segments may be used. */
+#define	JPC_COD_EPH	0x04
+
+/*
+ * Progression order constants.
+ */
+
+/* Layer-resolution-component-precinct progressive
+  (i.e., progressive by fidelity). */
+#define	JPC_COD_LRCPPRG	0
+/* Resolution-layer-component-precinct progressive
+  (i.e., progressive by resolution). */
+#define	JPC_COD_RLCPPRG	1
+/* Resolution-precinct-component-layer progressive. */
+#define	JPC_COD_RPCLPRG	2
+/* Precinct-component-resolution-layer progressive. */
+#define	JPC_COD_PCRLPRG	3
+/* Component-position-resolution-layer progressive. */
+#define	JPC_COD_CPRLPRG	4
+
+/*
+ * Code block style constants.
+ */
+
+#define	JPC_COX_LAZY	0x01 /* Selective arithmetic coding bypass. */
+#define	JPC_COX_RESET	0x02 /* Reset context probabilities. */
+#define	JPC_COX_TERMALL	0x04 /* Terminate all coding passes. */
+#define	JPC_COX_VSC		0x08 /* Vertical stripe causal context formation. */
+#define	JPC_COX_PTERM	0x10 /* Predictable termination. */
+#define	JPC_COX_SEGSYM	0x20 /* Use segmentation symbols. */
+
+/* Transform constants. */
+#define	JPC_COX_INS	0x00 /* Irreversible 9/7. */
+#define	JPC_COX_RFT	0x01 /* Reversible 5/3. */
+
+/* Multicomponent transform constants. */
+#define	JPC_COD_NOMCT	0x00 /* No multicomponent transform. */
+#define	JPC_COD_MCT		0x01 /* Multicomponent transform. */
+
+/* Get the code block size value from the code block size exponent. */
+JAS_ATTRIBUTE_CONST
+static inline unsigned JPC_COX_CBLKSIZEEXPN(unsigned x)
+{
+	return x - 2;
+}
+
+/* Get the code block size exponent from the code block size value. */
+JAS_ATTRIBUTE_CONST
+static inline unsigned JPC_COX_GETCBLKSIZEEXPN(unsigned x)
+{
+	return x + 2;
+}
+
+/* Per resolution-level information. */
+
+typedef struct {
+
+	/* The packet partition width. */
+	uint_fast8_t parwidthval;
+
+	/* The packet partition height. */
+	uint_fast8_t parheightval;
+
+} jpc_coxrlvl_t;
+
+/* Per component information. */
+
+typedef struct {
+
+	/* The coding style. */
+	uint_fast8_t csty;
+
+	/* The number of decomposition levels. */
+	uint_fast8_t numdlvls;
+
+	/* The nominal code block width specifier. */
+	uint_fast8_t cblkwidthval;
+
+	/* The nominal code block height specifier. */
+	uint_fast8_t cblkheightval;
+
+	/* The style of coding passes. */
+	uint_fast8_t cblksty;
+
+	/* The QMFB employed. */
+	uint_fast8_t qmfbid;
+
+	/* The number of resolution levels. */
+	int numrlvls;
+
+	/* The per-resolution-level information. */
+	jpc_coxrlvl_t rlvls[JPC_MAXRLVLS];
+
+} jpc_coxcp_t;
+
+/* COD marker segment parameters. */
+
+typedef struct {
+
+	/* The general coding style. */
+	uint_fast8_t csty;
+
+	/* The progression order. */
+	uint_fast8_t prg;
+
+	/* The number of layers. */
+	uint_fast16_t numlyrs;
+
+	/* The multicomponent transform. */
+	uint_fast8_t mctrans;
+
+	/* Component-related parameters. */
+	jpc_coxcp_t compparms;
+
+} jpc_cod_t;
+
+/* COC marker segment parameters. */
+
+typedef struct {
+
+	/* The component number. */
+	uint_fast16_t compno;
+
+	/* Component-related parameters. */
+	jpc_coxcp_t compparms;
+
+} jpc_coc_t;
+
+/**************************************\
+* RGN marker segment parameters.
+\**************************************/
+
+/* The maxshift ROI style. */
+#define	JPC_RGN_MAXSHIFT	0x00
+
+typedef struct {
+
+	/* The component to which the marker applies. */
+	uint_fast16_t compno;
+
+	/* The ROI style. */
+	uint_fast8_t roisty;
+
+	/* The ROI shift value. */
+	uint_fast8_t roishift;
+
+} jpc_rgn_t;
+
+/**************************************\
+* QCD/QCC marker segment parameters.
+\**************************************/
+
+/*
+ * Quantization style constants.
+ */
+
+#define	JPC_QCX_NOQNT	0 /* No quantization. */
+#define	JPC_QCX_SIQNT	1 /* Scalar quantization, implicit. */
+#define	JPC_QCX_SEQNT	2 /* Scalar quantization, explicit. */
+
+/*
+ * Stepsize manipulation macros.
+ */
+
+JAS_ATTRIBUTE_CONST
+static inline unsigned JPC_QCX_GETEXPN(unsigned x)
+{
+	return x >> 11;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline unsigned JPC_QCX_GETMANT(unsigned x)
+{
+	return x & 0x7ff;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline uint_fast16_t JPC_QCX_EXPN(unsigned x)
+{
+	assert(!(x & (~0x1f)));
+
+	return (x & 0x1f) << 11;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline uint_fast16_t JPC_QCX_MANT(unsigned x)
+{
+	assert(!(x & (~0x7ff)));
+
+	return x & 0x7ff;
+}
+
+/* Per component information. */
+
+typedef struct {
+
+	/* The quantization style. */
+	uint_fast8_t qntsty;
+
+	/* The number of step sizes. */
+	int numstepsizes;
+
+	/* The step sizes. */
+	uint_fast16_t *stepsizes;
+
+	/* The number of guard bits. */
+	uint_fast8_t numguard;
+
+} jpc_qcxcp_t;
+
+/* QCC marker segment parameters. */
+
+typedef struct {
+
+	/* The component associated with this marker segment. */
+	uint_fast16_t compno;
+
+	/* The parameters. */
+	jpc_qcxcp_t compparms;
+
+} jpc_qcc_t;
+
+/* QCD marker segment parameters. */
+
+typedef struct {
+
+	/* The parameters. */
+	jpc_qcxcp_t compparms;
+
+} jpc_qcd_t;
+
+/**************************************\
+* POD marker segment parameters.
+\**************************************/
+
+typedef struct {
+
+	/* The progression order. */
+	uint_fast8_t prgord;
+
+	/* The lower bound (inclusive) on the resolution level for the
+	  progression order volume. */
+	uint_fast8_t rlvlnostart;
+
+	/* The upper bound (exclusive) on the resolution level for the
+	  progression order volume. */
+	uint_fast8_t rlvlnoend;
+
+	/* The lower bound (inclusive) on the component for the progression
+	  order volume. */
+	uint_fast16_t compnostart;
+
+	/* The upper bound (exclusive) on the component for the progression
+	  order volume. */
+	uint_fast16_t compnoend;
+
+	/* The upper bound (exclusive) on the layer for the progression
+	  order volume. */
+	uint_fast16_t lyrnoend;
+
+} jpc_pocpchg_t;
+
+/* An alias for the above type. */
+typedef jpc_pocpchg_t jpc_pchg_t;
+
+/* POC marker segment parameters. */
+
+typedef struct {
+
+	/* The number of progression order changes. */
+	int numpchgs;
+
+	/* The per-progression-order-change information. */
+	jpc_pocpchg_t *pchgs;
+
+} jpc_poc_t;
+
+/**************************************\
+* PPM/PPT marker segment parameters.
+\**************************************/
+
+/* PPM marker segment parameters. */
+
+typedef struct {
+
+	/* The index. */
+	uint_fast8_t ind;
+
+	/* The length. */
+	uint_fast16_t len;
+
+	/* The data. */
+	jas_uchar *data;
+
+} jpc_ppm_t;
+
+/* PPT marker segment parameters. */
+
+typedef struct {
+
+	/* The index. */
+	uint_fast8_t ind;
+
+	/* The length. */
+	uint_fast32_t len;
+
+	/* The data. */
+	unsigned char *data;
+
+} jpc_ppt_t;
+
+/**************************************\
+* COM marker segment parameters.
+\**************************************/
+
+/*
+ * Registration IDs.
+ */
+
+#define	JPC_COM_BIN		0x00
+#define	JPC_COM_LATIN	0x01
+
+typedef struct {
+
+	/* The registration ID. */
+	uint_fast16_t regid;
+
+	/* The length of the data in bytes. */
+	uint_fast16_t len;
+
+	/* The data. */
+	jas_uchar *data;
+
+} jpc_com_t;
+
+/**************************************\
+* SOP marker segment parameters.
+\**************************************/
+
+typedef struct {
+
+	/* The sequence number. */
+	uint_fast16_t seqno;
+
+} jpc_sop_t;
+
+/**************************************\
+* CRG marker segment parameters.
+\**************************************/
+
+/* Per component information. */
+
+typedef struct {
+
+	/* The horizontal offset. */
+	uint_fast16_t hoff;
+
+	/* The vertical offset. */
+	uint_fast16_t voff;
+
+} jpc_crgcomp_t;
+
+typedef struct {
+
+	/* The number of components. */
+	int numcomps;
+
+	/* Per component information. */
+	jpc_crgcomp_t *comps;
+
+} jpc_crg_t;
+
+/**************************************\
+* Marker segment parameters for unknown marker type.
+\**************************************/
+
+typedef struct {
+
+	/* The data. */
+	jas_uchar *data;
+
+	/* The length. */
+	uint_fast16_t len;
+
+} jpc_unk_t;
+
+/**************************************\
+* Generic marker segment parameters.
+\**************************************/
+
+typedef union {
+	int soc;	/* unused */
+	jpc_sot_t sot;
+	int sod;	/* unused */
+	int eoc;	/* unused */
+	jpc_siz_t siz;
+	jpc_cod_t cod;
+	jpc_coc_t coc;
+	jpc_rgn_t rgn;
+	jpc_qcd_t qcd;
+	jpc_qcc_t qcc;
+	jpc_poc_t poc;
+	/* jpc_plm_t plm; */
+	/* jpc_plt_t plt; */
+	jpc_ppm_t ppm;
+	jpc_ppt_t ppt;
+	jpc_sop_t sop;
+	int eph;	/* unused */
+	jpc_com_t com;
+	jpc_crg_t crg;
+	jpc_unk_t unk;
+} jpc_msparms_t;
+
+/**************************************\
+* Marker segment.
+\**************************************/
+
+/* Marker segment IDs. */
+
+/* The smallest valid marker value. */
+#define	JPC_MS_MIN	0xff00
+
+/* The largest valid marker value. */
+#define	JPC_MS_MAX	0xffff
+
+/* The minimum marker value that cannot occur within packet data. */
+#define	JPC_MS_INMIN	0xff80
+/* The maximum marker value that cannot occur within packet data. */
+#define	JPC_MS_INMAX	0xffff
+
+/* Delimiting marker segments. */
+#define	JPC_MS_SOC	0xff4f /* Start of code stream (SOC). */
+#define	JPC_MS_SOT	0xff90 /* Start of tile-part (SOT). */
+#define	JPC_MS_SOD	0xff93 /* Start of data (SOD). */
+#define	JPC_MS_EOC	0xffd9 /* End of code stream (EOC). */
+
+/* Fixed information marker segments. */
+#define	JPC_MS_SIZ	0xff51 /* Image and tile size (SIZ). */
+
+/* Functional marker segments. */
+#define	JPC_MS_COD	0xff52 /* Coding style default (COD). */
+#define JPC_MS_COC	0xff53 /* Coding style component (COC). */
+#define	JPC_MS_RGN	0xff5e /* Region of interest (RGN). */
+#define JPC_MS_QCD	0xff5c /* Quantization default (QCD). */
+#define JPC_MS_QCC	0xff5d /* Quantization component (QCC). */
+#define JPC_MS_POC	0xff5f /* Progression order default (POC). */
+
+/* Pointer marker segments. */
+#define	JPC_MS_TLM	0xff55 /* Tile-part lengths, main header (TLM). */
+#define	JPC_MS_PLM	0xff57 /* Packet length, main header (PLM). */
+#define	JPC_MS_PLT	0xff58 /* Packet length, tile-part header (PLT). */
+#define	JPC_MS_PPM	0xff60 /* Packed packet headers, main header (PPM). */
+#define	JPC_MS_PPT	0xff61 /* Packet packet headers, tile-part header (PPT). */
+
+/* In bit stream marker segments. */
+#define	JPC_MS_SOP	0xff91	/* Start of packet (SOP). */
+#define	JPC_MS_EPH	0xff92	/* End of packet header (EPH). */
+
+/* Informational marker segments. */
+#define	JPC_MS_CRG	0xff63 /* Component registration (CRG). */
+#define JPC_MS_COM	0xff64 /* Comment (COM). */
+
+/* Forward declaration. */
+struct jpc_msops_s;
+
+/* Generic marker segment class. */
+
+typedef struct {
+
+	/* The type of marker segment. */
+	uint_fast16_t id;
+
+	/* The length of the marker segment. */
+	uint_fast16_t len;
+
+	/* The starting offset within the stream. */
+	uint_fast32_t off;
+
+	/* The parameters of the marker segment. */
+	jpc_msparms_t parms;
+
+	/* The marker segment operations. */
+	const struct jpc_msops_s *ops;
+
+} jpc_ms_t;
+
+/* Marker segment operations (which depend on the marker segment type). */
+
+typedef struct jpc_msops_s {
+
+	/* Destroy the marker segment parameters. */
+	void (*destroyparms)(jpc_ms_t *ms);
+
+	/* Get the marker segment parameters from a stream. */
+	int (*getparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+
+	/* Put the marker segment parameters to a stream. */
+	int (*putparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+
+	/* Dump the marker segment parameters (for debugging). */
+	int (*dumpparms)(jpc_ms_t *ms, FILE *out);
+
+} jpc_msops_t;
+
+/******************************************************************************\
+* Macros/Functions.
+\******************************************************************************/
+
+/* Create a code-stream state object. */
+jpc_cstate_t *jpc_cstate_create(void);
+
+/* Destroy a code-stream state object. */
+void jpc_cstate_destroy(jpc_cstate_t *cstate);
+
+/* Create a marker segment. */
+jpc_ms_t *jpc_ms_create(int type);
+
+/* Destroy a marker segment. */
+void jpc_ms_destroy(jpc_ms_t *ms);
+
+/* Does a marker segment have parameters? */
+JAS_ATTRIBUTE_CONST
+static inline bool JPC_MS_HASPARMS(unsigned x)
+{
+	return !(x == JPC_MS_SOC || x == JPC_MS_SOD || x == JPC_MS_EOC ||
+		 x == JPC_MS_EPH || (x >= 0xff30 && x <= 0xff3f));
+}
+
+/* Get the marker segment type. */
+JAS_ATTRIBUTE_PURE
+static inline unsigned jpc_ms_gettype(const jpc_ms_t *ms)
+{
+	return ms->id;
+}
+
+/* Read a marker segment from a stream. */
+jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate);
+
+/* Write a marker segment to a stream. */
+int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms);
+
+/* Copy code stream data from one stream to another. */
+int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long n);
+
+/* Copy code stream data from one stream to another. */
+int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long n);
+
+/* Dump a marker segment (for debugging). */
+void jpc_ms_dump(jpc_ms_t *ms, FILE *out);
+
+/* Read a 8-bit unsigned integer from a stream. */
+int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val);
+
+/* Read a 16-bit unsigned integer from a stream. */
+int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val);
+
+/* Read a 32-bit unsigned integer from a stream. */
+int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val);
+
+/* Write a 8-bit unsigned integer to a stream. */
+int jpc_putuint8(jas_stream_t *out, uint_fast8_t val);
+
+/* Write a 16-bit unsigned integer to a stream. */
+int jpc_putuint16(jas_stream_t *out, uint_fast16_t val);
+
+/* Write a 32-bit unsigned integer to a stream. */
+int jpc_putuint32(jas_stream_t *out, uint_fast32_t val);
+
+#endif
--- /dev/null
+++ b/jpc_dec.c
@@ -1,0 +1,2451 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_dec.h"
+#include "jpc_fix.h"
+#include "jpc_cs.h"
+#include "jpc_mct.h"
+#include "jpc_t2dec.h"
+#include "jpc_t1cod.h"
+#include "jpc_t1dec.h"
+#include "jpc_math.h"
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define	JPC_MHSOC	0x0001
+  /* In the main header, expecting a SOC marker segment. */
+#define	JPC_MHSIZ	0x0002
+  /* In the main header, expecting a SIZ marker segment. */
+#define	JPC_MH		0x0004
+  /* In the main header, expecting "other" marker segments. */
+#define	JPC_TPHSOT	0x0008
+  /* In a tile-part header, expecting a SOT marker segment. */
+#define	JPC_TPH		0x0010
+  /* In a tile-part header, expecting "other" marker segments. */
+#define	JPC_MT		0x0020
+  /* In the main trailer. */
+
+typedef struct {
+
+	uint_least16_t id;
+	/* The marker segment type. */
+
+	uint_least16_t validstates;
+	/* The states in which this type of marker segment can be
+	  validly encountered. */
+
+	int (*action)(jpc_dec_t *dec, jpc_ms_t *ms);
+	/* The action to take upon encountering this type of marker segment. */
+
+} jpc_dec_mstabent_t;
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+/* COD/COC parameters have been specified. */
+#define	JPC_CSET	0x0001
+/* QCD/QCC parameters have been specified. */
+#define	JPC_QSET	0x0002
+/* COD/COC parameters set from a COC marker segment. */
+#define	JPC_COC	0x0004
+/* QCD/QCC parameters set from a QCC marker segment. */
+#define	JPC_QCC	0x0008
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static int jpc_dec_dump(const jpc_dec_t *dec, FILE *out);
+
+static jpc_ppxstab_t *jpc_ppxstab_create(void);
+static void jpc_ppxstab_destroy(jpc_ppxstab_t *tab);
+static int jpc_ppxstab_grow(jpc_ppxstab_t *tab, unsigned maxents);
+static int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent);
+static jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab);
+static int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab);
+static jpc_ppxstabent_t *jpc_ppxstabent_create(void);
+static void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent);
+
+static int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist);
+static jpc_streamlist_t *jpc_streamlist_create(void);
+
+static int jpc_streamlist_insert(jpc_streamlist_t *streamlist, unsigned streamno,
+  jas_stream_t *stream);
+static jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, unsigned streamno);
+static void jpc_streamlist_destroy(jpc_streamlist_t *streamlist);
+
+static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp);
+static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps);
+static int jpc_dec_cp_isvalid(const jpc_dec_cp_t *cp);
+static jpc_dec_cp_t *jpc_dec_cp_copy(const jpc_dec_cp_t *cp);
+static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, const jpc_cod_t *cod);
+static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, const jpc_coc_t *coc);
+static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
+  const jpc_coxcp_t *compparms, unsigned flags);
+static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, const jpc_qcd_t *qcd);
+static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, const jpc_qcc_t *qcc);
+static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
+  const jpc_qcxcp_t *compparms, unsigned flags);
+static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, const jpc_rgn_t *rgn);
+static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp);
+static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp);
+static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, const jpc_poc_t *poc, int reset);
+static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, const jpc_poc_t *poc);
+
+static int jpc_dec_decode(jpc_dec_t *dec);
+static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts,
+  jas_stream_t *in);
+static void jpc_dec_destroy(jpc_dec_t *dec);
+static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize);
+static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, unsigned numbps);
+static jpc_fix_t jpc_calcabsstepsize(unsigned stepsize, unsigned numbits);
+static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms);
+static jpc_dec_importopts_t *jpc_dec_opts_create(const char *optstr);
+static void jpc_dec_opts_destroy(jpc_dec_importopts_t *opts);
+
+static const jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+static const jpc_dec_mstabent_t jpc_dec_mstab[] = {
+	{JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc},
+	{JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot},
+	{JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod},
+	{JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc},
+	{JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz},
+	{JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod},
+	{JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc},
+	{JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn},
+	{JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd},
+	{JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc},
+	{JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc},
+	{JPC_MS_TLM, JPC_MH, 0},
+	{JPC_MS_PLM, JPC_MH, 0},
+	{JPC_MS_PLT, JPC_TPH, 0},
+	{JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm},
+	{JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt},
+	{JPC_MS_SOP, 0, 0},
+	{JPC_MS_CRG, JPC_MH, jpc_dec_process_crg},
+	{JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com},
+	{0, JPC_MH | JPC_TPH, jpc_dec_process_unk}
+};
+
+/******************************************************************************\
+* The main entry point for the JPEG-2000 decoder.
+\******************************************************************************/
+
+jas_image_t *jpc_decode(jas_stream_t *in, const char *optstr)
+{
+	jpc_dec_importopts_t *opts;
+	jpc_dec_t *dec;
+	jas_image_t *image;
+
+	dec = 0;
+
+	JAS_DBGLOG(100, ("jpc_decode(%p, \"%s\")\n", in, optstr));
+
+	if (!(opts = jpc_dec_opts_create(optstr))) {
+		goto error;
+	}
+
+	jpc_initluts();
+
+	if (!(dec = jpc_dec_create(opts, in))) {
+		goto error;
+	}
+	jpc_dec_opts_destroy(opts);
+	opts = 0;
+
+	/* Do most of the work. */
+	if (jpc_dec_decode(dec)) {
+		goto error;
+	}
+
+	if (jas_image_numcmpts(dec->image) >= 3) {
+		jas_image_setclrspc(dec->image, JAS_CLRSPC_SRGB);
+		jas_image_setcmpttype(dec->image, 0,
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
+		jas_image_setcmpttype(dec->image, 1,
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
+		jas_image_setcmpttype(dec->image, 2,
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
+	} else {
+		jas_image_setclrspc(dec->image, JAS_CLRSPC_SGRAY);
+		jas_image_setcmpttype(dec->image, 0,
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
+	}
+
+	/* Save the return value. */
+	image = dec->image;
+
+	/* Stop the image from being discarded. */
+	dec->image = 0;
+
+	/* Destroy decoder. */
+	jpc_dec_destroy(dec);
+
+	return image;
+
+error:
+	if (opts) {
+		jpc_dec_opts_destroy(opts);
+	}
+	if (dec) {
+		jpc_dec_destroy(dec);
+	}
+	return 0;
+}
+
+static jpc_dec_importopts_t *jpc_dec_opts_create(const char *optstr)
+{
+	jpc_dec_importopts_t *opts;
+
+	USED(optstr);
+	if (!(opts = jas_malloc(sizeof(jpc_dec_importopts_t)))) {
+		goto error;
+	}
+
+	opts->debug = 0;
+	opts->maxlyrs = JPC_MAXLYRS;
+	opts->maxpkts = -1;
+	opts->max_samples = JAS_DEC_DEFAULT_MAX_SAMPLES;
+
+	return opts;
+
+error:
+	if (opts) {
+		jpc_dec_opts_destroy(opts);
+	}
+	return 0;
+}
+
+static void jpc_dec_opts_destroy(jpc_dec_importopts_t *opts)
+{
+	jas_free(opts);
+}
+
+/******************************************************************************\
+* Code for table-driven code stream decoder.
+\******************************************************************************/
+
+JAS_ATTRIBUTE_CONST
+static const jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id)
+{
+	const jpc_dec_mstabent_t *mstabent;
+	for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) {
+		if (mstabent->id == id) {
+			break;
+		}
+	}
+	return mstabent;
+}
+
+static int jpc_dec_decode(jpc_dec_t *dec)
+{
+	jpc_ms_t *ms;
+	const jpc_dec_mstabent_t *mstabent;
+	int ret;
+	jpc_cstate_t *cstate;
+
+	if (!(cstate = jpc_cstate_create())) {
+		return -1;
+	}
+	dec->cstate = cstate;
+
+	/* Initially, we should expect to encounter a SOC marker segment. */
+	dec->state = JPC_MHSOC;
+
+	for (;;) {
+
+		/* Get the next marker segment in the code stream. */
+		if (!(ms = jpc_getms(dec->in, cstate))) {
+			jas_eprintf("cannot get marker segment\n");
+			return -1;
+		}
+
+		mstabent = jpc_dec_mstab_lookup(ms->id);
+		assert(mstabent);
+
+		/* Ensure that this type of marker segment is permitted
+		  at this point in the code stream. */
+		if (!(dec->state & mstabent->validstates)) {
+			jas_eprintf("unexpected marker segment type\n");
+			jpc_ms_destroy(ms);
+			return -1;
+		}
+
+		/* Process the marker segment. */
+		if (mstabent->action) {
+			ret = (*mstabent->action)(dec, ms);
+		} else {
+			/* No explicit action is required. */
+			ret = 0;
+		}
+
+		/* Destroy the marker segment. */
+		jpc_ms_destroy(ms);
+
+		if (ret < 0) {
+			return -1;
+		} else if (ret > 0) {
+			break;
+		}
+
+	}
+
+	return 0;
+}
+
+static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	jpc_dec_cmpt_t *cmpt;
+	jpc_crg_t *crg;
+
+	crg = &ms->parms.crg;
+	unsigned cmptno;
+	for (cmptno = 0, cmpt = dec->cmpts; cmptno < dec->numcomps; ++cmptno,
+	  ++cmpt) {
+		/* Ignore the information in the CRG marker segment for now.
+		  This information serves no useful purpose for decoding anyhow.
+		  Some other parts of the code need to be changed if these lines
+		  are uncommented.
+		cmpt->hsubstep = crg->comps[cmptno].hoff;
+		cmpt->vsubstep = crg->comps[cmptno].voff;
+		*/
+		/* suppress -Wunused-but-set-variable */
+		USED(crg);
+	}
+	return 0;
+}
+
+static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	/* Eliminate warnings about unused variables. */
+	(void)ms;
+
+	/* We should expect to encounter a SIZ marker segment next. */
+	dec->state = JPC_MHSIZ;
+
+	return 0;
+}
+
+static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	jpc_dec_tile_t *tile;
+	jpc_sot_t *sot = &ms->parms.sot;
+	jas_image_cmptparm_t *compinfos;
+	jas_image_cmptparm_t *compinfo;
+	jpc_dec_cmpt_t *cmpt;
+
+	if (dec->state == JPC_MH) {
+
+		if (!(compinfos = jas_alloc2(dec->numcomps,
+		  sizeof(jas_image_cmptparm_t)))) {
+			return -1;
+		}
+		unsigned cmptno;
+		for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos;
+		  cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) {
+			compinfo->tlx = 0;
+			compinfo->tly = 0;
+			compinfo->prec = cmpt->prec;
+			compinfo->sgnd = cmpt->sgnd;
+			compinfo->width = cmpt->width;
+			compinfo->height = cmpt->height;
+			compinfo->hstep = cmpt->hstep;
+			compinfo->vstep = cmpt->vstep;
+		}
+
+		if (!(dec->image = jas_image_create(dec->numcomps, compinfos,
+		  JAS_CLRSPC_UNKNOWN))) {
+			jas_free(compinfos);
+			return -1;
+		}
+		jas_free(compinfos);
+
+		/* Is the packet header information stored in PPM marker segments in
+		  the main header? */
+		if (dec->ppmstab) {
+			/* Convert the PPM marker segment data into a collection of streams
+			  (one stream per tile-part). */
+			if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) {
+				return -1;
+			}
+			jpc_ppxstab_destroy(dec->ppmstab);
+			dec->ppmstab = 0;
+		}
+	}
+
+	if (sot->len > 0) {
+		dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len -
+		  4 + sot->len;
+	} else {
+		dec->curtileendoff = 0;
+	}
+
+	if (sot->tileno >= dec->numtiles) {
+		jas_eprintf("invalid tile number in SOT marker segment\n");
+		return -1;
+	}
+	/* Set the current tile. */
+	dec->curtile = &dec->tiles[sot->tileno];
+	tile = dec->curtile;
+	/* Ensure that this is the expected part number. */
+	if (sot->partno != tile->partno) {
+		return -1;
+	}
+	if (tile->numparts > 0 && sot->partno >= tile->numparts) {
+		return -1;
+	}
+	if (!tile->numparts && sot->numparts > 0) {
+		tile->numparts = sot->numparts;
+	}
+
+	tile->pptstab = 0;
+
+	switch (tile->state) {
+	case JPC_TILE_INIT:
+		/* This is the first tile-part for this tile. */
+		tile->state = JPC_TILE_ACTIVE;
+		assert(!tile->cp);
+		if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) {
+			return -1;
+		}
+		jpc_dec_cp_resetflags(dec->cp);
+		break;
+	default:
+		if (sot->numparts == sot->partno - 1) {
+			tile->state = JPC_TILE_ACTIVELAST;
+		}
+		break;
+	}
+
+	/* Note: We do not increment the expected tile-part number until
+	  all processing for this tile-part is complete. */
+
+	/* We should expect to encounter other tile-part header marker
+	  segments next. */
+	dec->state = JPC_TPH;
+
+	return 0;
+}
+
+static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	jpc_dec_tile_t *tile;
+	int pos;
+
+	/* Eliminate compiler warnings about unused variables. */
+	(void)ms;
+
+	if (!(tile = dec->curtile)) {
+		return -1;
+	}
+
+	if (!tile->partno) {
+		if (!jpc_dec_cp_isvalid(tile->cp)) {
+			return -1;
+		}
+		if (jpc_dec_cp_prepare(tile->cp)) {
+			return -1;
+		}
+		if (jpc_dec_tileinit(dec, tile)) {
+			return -1;
+		}
+	}
+
+	/* Are packet headers stored in the main header or tile-part header? */
+	if (dec->pkthdrstreams) {
+		/* Get the stream containing the packet header data for this
+		  tile-part. */
+		if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) {
+			return -1;
+		}
+	}
+
+	if (tile->pptstab) {
+		if (!tile->pkthdrstream) {
+			if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) {
+				return -1;
+			}
+		}
+		pos = jas_stream_tell(tile->pkthdrstream);
+		jas_stream_seek(tile->pkthdrstream, 0, SEEK_END);
+		if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) {
+			return -1;
+		}
+		jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET);
+		jpc_ppxstab_destroy(tile->pptstab);
+		tile->pptstab = 0;
+	}
+
+	if (jas_getdbglevel() >= 10) {
+		jpc_dec_dump(dec, stderr);
+	}
+
+	if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream :
+	  dec->in, dec->in)) {
+		jas_eprintf("jpc_dec_decodepkts failed\n");
+		return -1;
+	}
+
+	/* Gobble any unconsumed tile data. */
+	if (dec->curtileendoff > 0) {
+		long curoff;
+		uint_fast32_t n;
+		curoff = jas_stream_getrwcount(dec->in);
+		if (curoff < dec->curtileendoff) {
+			n = dec->curtileendoff - curoff;
+			jas_eprintf("warning: ignoring trailing garbage (%lu bytes)\n",
+			  (unsigned long) n);
+
+			while (n-- > 0) {
+				if (jas_stream_getc(dec->in) == EOF) {
+					jas_eprintf("read error\n");
+					return -1;
+				}
+			}
+		} else if (curoff > dec->curtileendoff) {
+			jas_eprintf("warning: not enough tile data (%lu bytes)\n",
+			  (unsigned long) curoff - dec->curtileendoff);
+		}
+
+	}
+
+	if (tile->numparts > 0 && tile->partno == tile->numparts - 1) {
+		if (jpc_dec_tiledecode(dec, tile)) {
+			return -1;
+		}
+		jpc_dec_tilefini(dec, tile);
+	}
+
+	dec->curtile = 0;
+
+	/* Increment the expected tile-part number. */
+	++tile->partno;
+
+	/* We should expect to encounter a SOT marker segment next. */
+	dec->state = JPC_TPHSOT;
+
+	return 0;
+}
+
+static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+	jpc_dec_tcomp_t *tcomp;
+	unsigned rlvlno;
+	jpc_dec_rlvl_t *rlvl;
+	jpc_dec_band_t *band;
+	jpc_dec_prc_t *prc;
+	jpc_dec_cblk_t *cblk;
+	uint_fast32_t tlprcxstart;
+	uint_fast32_t tlprcystart;
+	uint_fast32_t brprcxend;
+	uint_fast32_t brprcyend;
+	uint_fast32_t tlcbgxstart;
+	uint_fast32_t tlcbgystart;
+	uint_fast32_t brcbgxend;
+	uint_fast32_t cbgxstart;
+	uint_fast32_t cbgystart;
+	uint_fast32_t cbgxend;
+	uint_fast32_t cbgyend;
+	uint_fast32_t tlcblkxstart;
+	uint_fast32_t tlcblkystart;
+	uint_fast32_t brcblkxend;
+	uint_fast32_t brcblkyend;
+	uint_fast32_t cblkxstart;
+	uint_fast32_t cblkystart;
+	uint_fast32_t cblkxend;
+	uint_fast32_t cblkyend;
+	uint_fast32_t tmpxstart;
+	uint_fast32_t tmpystart;
+	uint_fast32_t tmpxend;
+	uint_fast32_t tmpyend;
+	jpc_tsfb_band_t bnds[JPC_MAXBANDS];
+	jpc_pchg_t *pchg;
+
+	const jpc_dec_cp_t *cp = tile->cp;
+	tile->realmode = 0;
+	if (cp->mctid == JPC_MCT_ICT) {
+		tile->realmode = 1;
+	}
+
+	unsigned compno;
+	const jpc_dec_cmpt_t *cmpt;
+	for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+	  dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+		const jpc_dec_ccp_t *ccp = &tile->cp->ccps[compno];
+		if (ccp->qmfbid == JPC_COX_INS) {
+			tile->realmode = 1;
+		}
+		tcomp->numrlvls = ccp->numrlvls;
+		if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls,
+		  sizeof(jpc_dec_rlvl_t)))) {
+			return -1;
+		}
+		for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
+		  ++rlvlno, ++rlvl) {
+			rlvl->bands = NULL;
+		}
+		if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart,
+		  cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep),
+		  JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend,
+		  cmpt->vstep)))) {
+			return -1;
+		}
+		if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid,
+		  tcomp->numrlvls - 1))) {
+			return -1;
+		}
+		{
+			jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data),
+			  jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data),
+			  jas_seq2d_yend(tcomp->data), bnds);
+		}
+		for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
+		  ++rlvlno, ++rlvl) {
+			rlvl->bands = 0;
+			rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart,
+			  tcomp->numrlvls - 1 - rlvlno);
+			rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart,
+			  tcomp->numrlvls - 1 - rlvlno);
+			rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend,
+			  tcomp->numrlvls - 1 - rlvlno);
+			rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend,
+			  tcomp->numrlvls - 1 - rlvlno);
+			rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno];
+			rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno];
+			tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart,
+			  rlvl->prcwidthexpn) << rlvl->prcwidthexpn;
+			tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart,
+			  rlvl->prcheightexpn) << rlvl->prcheightexpn;
+			brprcxend = JPC_CEILDIVPOW2(rlvl->xend,
+			  rlvl->prcwidthexpn) << rlvl->prcwidthexpn;
+			brprcyend = JPC_CEILDIVPOW2(rlvl->yend,
+			  rlvl->prcheightexpn) << rlvl->prcheightexpn;
+			rlvl->numhprcs = (brprcxend - tlprcxstart) >>
+			  rlvl->prcwidthexpn;
+			rlvl->numvprcs = (brprcyend - tlprcystart) >>
+			  rlvl->prcheightexpn;
+			rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
+
+			if (rlvl->numprcs >= 64 * 1024) {
+				/* avoid out-of-memory due to
+				   malicious file; this limit is
+				   rather arbitrary; "good" files I
+				   have seen have values 1..12 */
+				return -1;
+			}
+
+			if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) {
+				rlvl->bands = 0;
+				rlvl->numprcs = 0;
+				rlvl->numhprcs = 0;
+				rlvl->numvprcs = 0;
+				continue;
+			}	
+			if (!rlvlno) {
+				tlcbgxstart = tlprcxstart;
+				tlcbgystart = tlprcystart;
+				brcbgxend = brprcxend;
+				rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
+				rlvl->cbgheightexpn = rlvl->prcheightexpn;
+			} else {
+				tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1);
+				tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1);
+				brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1);
+				if (rlvl->prcwidthexpn < 1 || rlvl->prcheightexpn < 1) {
+					/* the control block width/height offset
+					   exponent must not be negative */
+					return -1;
+				}
+				rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
+				rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
+			}
+			rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn,
+			  rlvl->cbgwidthexpn);
+			rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn,
+			  rlvl->cbgheightexpn);
+
+			rlvl->numbands = (!rlvlno) ? 1 : 3;
+			if (!(rlvl->bands = jas_alloc2(rlvl->numbands,
+			  sizeof(jpc_dec_band_t)))) {
+				return -1;
+			}
+			unsigned bandno;
+			for (bandno = 0, band = rlvl->bands;
+			  bandno < rlvl->numbands; ++bandno, ++band) {
+				unsigned bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) +
+				  bandno + 1);
+				const jpc_tsfb_band_t *bnd = &bnds[bndno];
+
+				band->orient = bnd->orient;
+				band->stepsize = ccp->stepsizes[bndno];
+				band->analgain = JPC_NOMINALGAIN(ccp->qmfbid,
+				  tcomp->numrlvls - 1, rlvlno, band->orient);
+				band->absstepsize = jpc_calcabsstepsize(band->stepsize,
+				  cmpt->prec + band->analgain);
+				band->numbps = ccp->numguardbits +
+				  JPC_QCX_GETEXPN(band->stepsize) - 1;
+				band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ?
+				  (JPC_PREC - 1 - band->numbps) : ccp->roishift;
+				band->data = 0;
+				band->prcs = 0;
+				if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) {
+					continue;
+				}
+				if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
+					return -1;
+				}
+				if (jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart,
+						      bnd->locystart, bnd->locxend, bnd->locyend)) {
+					return -1;
+				}
+				jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart);
+
+				assert(rlvl->numprcs);
+
+				if (!(band->prcs = jas_alloc2(rlvl->numprcs,
+				  sizeof(jpc_dec_prc_t)))) {
+					return -1;
+				}
+
+/************************************************/
+				cbgxstart = tlcbgxstart;
+				cbgystart = tlcbgystart;
+				unsigned prccnt;				for (prccnt = rlvl->numprcs, prc = band->prcs;
+				  prccnt > 0; --prccnt, ++prc) {
+					cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn);
+					cbgyend = cbgystart + (1 << rlvl->cbgheightexpn);
+					prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t,
+					  jas_seq2d_xstart(band->data)));
+					prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t,
+					  jas_seq2d_ystart(band->data)));
+					prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t,
+					  jas_seq2d_xend(band->data)));
+					prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t,
+					  jas_seq2d_yend(band->data)));
+					if (prc->xend > prc->xstart && prc->yend > prc->ystart) {
+						tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart,
+						  rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;
+						tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart,
+						  rlvl->cblkheightexpn) << rlvl->cblkheightexpn;
+						brcblkxend = JPC_CEILDIVPOW2(prc->xend,
+						  rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;
+						brcblkyend = JPC_CEILDIVPOW2(prc->yend,
+						  rlvl->cblkheightexpn) << rlvl->cblkheightexpn;
+						prc->numhcblks = (brcblkxend - tlcblkxstart) >>
+						  rlvl->cblkwidthexpn;
+						prc->numvcblks = (brcblkyend - tlcblkystart) >>
+						  rlvl->cblkheightexpn;
+						prc->numcblks = prc->numhcblks * prc->numvcblks;
+						assert(prc->numcblks > 0);
+
+						if (!(prc->incltagtree = jpc_tagtree_create(
+						  prc->numhcblks, prc->numvcblks))) {
+							return -1;
+						}
+						if (!(prc->numimsbstagtree = jpc_tagtree_create(
+						  prc->numhcblks, prc->numvcblks))) {
+							return -1;
+						}
+						if (!(prc->cblks = jas_alloc2(prc->numcblks,
+						  sizeof(jpc_dec_cblk_t)))) {
+							return -1;
+						}
+
+						cblkxstart = cbgxstart;
+						cblkystart = cbgystart;
+						unsigned cblkcnt;
+						for (cblkcnt = prc->numcblks, cblk = prc->cblks;
+						  cblkcnt > 0;) {
+							cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn);
+							cblkyend = cblkystart + (1 << rlvl->cblkheightexpn);
+							tmpxstart = JAS_MAX(cblkxstart, prc->xstart);
+							tmpystart = JAS_MAX(cblkystart, prc->ystart);
+							tmpxend = JAS_MIN(cblkxend, prc->xend);
+							tmpyend = JAS_MIN(cblkyend, prc->yend);
+							if (tmpxend > tmpxstart && tmpyend > tmpystart) {
+								cblk->firstpassno = -1;
+								cblk->numpasses = 0;
+								cblk->segs.head = 0;
+								cblk->segs.tail = 0;
+								cblk->curseg = 0;
+								cblk->numimsbs = 0;
+								cblk->numlenbits = 3;
+								if (!(cblk->data = jas_seq2d_create(0, 0, 0,
+								  0))) {
+									return -1;
+								}
+								if (jas_seq2d_bindsub(cblk->data, band->data,
+										      tmpxstart, tmpystart, tmpxend, tmpyend)) {
+									return -1;
+								}
+								++cblk;
+								--cblkcnt;
+							}
+							cblkxstart += 1 << rlvl->cblkwidthexpn;
+							if (cblkxstart >= cbgxend) {
+								cblkxstart = cbgxstart;
+								cblkystart += 1 << rlvl->cblkheightexpn;
+							}
+						}
+
+					} else {
+						prc->cblks = 0;
+						prc->incltagtree = 0;
+						prc->numimsbstagtree = 0;
+					}
+					cbgxstart += 1 << rlvl->cbgwidthexpn;
+					if (cbgxstart >= brcbgxend) {
+						cbgxstart = tlcbgxstart;
+						cbgystart += 1 << rlvl->cbgheightexpn;
+					}
+
+				}
+/********************************************/
+			}
+		}
+	}
+
+	if (!(tile->pi = jpc_dec_pi_create(dec, tile))) {
+		return -1;
+	}
+
+	for (unsigned pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist);
+	  ++pchgno) {
+		pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno));
+		assert(pchg);
+		jpc_pi_addpchg(tile->pi, pchg);
+	}
+	jpc_pi_init(tile->pi);
+
+	return 0;
+}
+
+static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+	jpc_dec_tcomp_t *tcomp;
+	unsigned rlvlno;
+	jpc_dec_seg_t *seg;
+	jpc_dec_cblk_t *cblk;
+
+	if (tile->tcomps) {
+
+		unsigned compno;
+		for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+		  ++compno, ++tcomp) {
+			const jpc_dec_rlvl_t *rlvl;
+			for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
+			  ++rlvlno, ++rlvl) {
+				if (!rlvl->bands) {
+					continue;
+				}
+				unsigned bandno;
+				const jpc_dec_band_t *band;
+				for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+				  ++bandno, ++band) {
+					if (band->prcs) {
+						unsigned prcno;
+						const jpc_dec_prc_t *prc;
+						for (prcno = 0, prc = band->prcs; prcno <
+						  rlvl->numprcs; ++prcno, ++prc) {
+							if (!prc->cblks) {
+								continue;
+							}
+							unsigned cblkno;
+							for (cblkno = 0, cblk = prc->cblks; cblkno <
+							  prc->numcblks; ++cblkno, ++cblk) {
+
+								while (cblk->segs.head) {
+									seg = cblk->segs.head;
+									jpc_seglist_remove(&cblk->segs, seg);
+									jpc_seg_destroy(seg);
+								}
+								jas_matrix_destroy(cblk->data);
+							}
+							if (prc->incltagtree) {
+								jpc_tagtree_destroy(prc->incltagtree);
+							}
+							if (prc->numimsbstagtree) {
+								jpc_tagtree_destroy(prc->numimsbstagtree);
+							}
+							if (prc->cblks) {
+								jas_free(prc->cblks);
+							}
+						}
+					}
+					if (band->data) {
+						jas_matrix_destroy(band->data);
+					}
+					if (band->prcs) {
+						jas_free(band->prcs);
+					}
+				}
+				if (rlvl->bands) {
+					jas_free(rlvl->bands);
+				}
+			}
+			if (tcomp->rlvls) {
+				jas_free(tcomp->rlvls);
+			}
+			if (tcomp->data) {
+				jas_matrix_destroy(tcomp->data);
+			}
+			if (tcomp->tsfb) {
+				jpc_tsfb_destroy(tcomp->tsfb);
+			}
+		}
+	}
+
+	if (tile->cp) {
+		jpc_dec_cp_destroy(tile->cp);
+		//tile->cp = 0;
+	}
+	if (tile->tcomps) {
+		jas_free(tile->tcomps);
+		//tile->tcomps = 0;
+	}
+	if (tile->pi) {
+		jpc_pi_destroy(tile->pi);
+		//tile->pi = 0;
+	}
+	if (tile->pkthdrstream) {
+		jas_stream_close(tile->pkthdrstream);
+		//tile->pkthdrstream = 0;
+	}
+	if (tile->pptstab) {
+		jpc_ppxstab_destroy(tile->pptstab);
+		//tile->pptstab = 0;
+	}
+
+	tile->state = JPC_TILE_DONE;
+
+	return 0;
+}
+
+static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+	unsigned rlvlno;
+	int v;
+
+	if (jpc_dec_decodecblks(dec, tile)) {
+		jas_eprintf("jpc_dec_decodecblks failed\n");
+		return -1;
+	}
+
+	/* Perform dequantization. */
+	unsigned compno;
+	const jpc_dec_tcomp_t *tcomp;
+	for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+	  ++compno, ++tcomp) {
+		const jpc_dec_ccp_t *ccp = &tile->cp->ccps[compno];
+		const jpc_dec_rlvl_t *rlvl;
+		for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
+		  ++rlvlno, ++rlvl) {
+			if (!rlvl->bands) {
+				continue;
+			}
+			unsigned bandno;
+			const jpc_dec_band_t *band;
+			for (bandno = 0, band = rlvl->bands;
+			  bandno < rlvl->numbands; ++bandno, ++band) {
+				if (!band->data) {
+					continue;
+				}
+				jpc_undo_roi(band->data, band->roishift, ccp->roishift -
+				  band->roishift, band->numbps);
+				if (ccp->qmfbid == JPC_COX_INS) {
+					jas_matrix_asl(band->data, JPC_FIX_FRACBITS);
+					jpc_dequantize(band->data, band->absstepsize);
+				}
+
+			}
+		}
+	}
+
+	/* Apply an inverse wavelet transform if necessary. */
+	for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+	  ++compno, ++tcomp) {
+		jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data);
+	}
+
+
+	/* Apply an inverse intercomponent transform if necessary. */
+	switch (tile->cp->mctid) {
+	case JPC_MCT_RCT:
+		if (dec->numcomps < 3) {
+			jas_eprintf("RCT requires at least three components\n");
+			return -1;
+		}
+		if (!jas_image_cmpt_domains_same(dec->image)) {
+			jas_eprintf("RCT requires all components have the same domain\n");
+			return -1;
+		}
+		jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data,
+		  tile->tcomps[2].data);
+		break;
+	case JPC_MCT_ICT:
+		if (dec->numcomps < 3) {
+			jas_eprintf("ICT requires at least three components\n");
+			return -1;
+		}
+		if (!jas_image_cmpt_domains_same(dec->image)) {
+			jas_eprintf("RCT requires all components have the same domain\n");
+			return -1;
+		}
+		jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data,
+		  tile->tcomps[2].data);
+		break;
+	}
+
+	/* Perform rounding and convert to integer values. */
+	for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+		  ++compno, ++tcomp) {
+		const jpc_dec_ccp_t *ccp = &tile->cp->ccps[compno];
+		if (ccp->qmfbid == JPC_COX_INS) {
+			jas_matrix_t *const data = tcomp->data;
+			const jas_matind_t height = jas_matrix_numrows(data);
+			const jas_matind_t numcols = jas_matrix_numcols(data);
+			for (jas_matind_t i = 0; i < height; ++i) {
+				jpc_fix_t *p = jas_matrix_getref(data, i, 0);
+				for (jas_matind_t j = 0; j < numcols; ++j) {
+					v = p[j];
+					v = jpc_fix_round(v);
+					p[j] = jpc_fixtoint(v);
+				}
+			}
+		}
+	}
+
+	/* Perform level shift. */
+	const jpc_dec_cmpt_t *cmpt;
+	for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+	  dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+		if (cmpt->sgnd)
+			continue;
+
+		jas_matrix_t *const data = tcomp->data;
+		const jas_matind_t width = jas_matrix_numcols(data);
+		const jas_matind_t height = jas_matrix_numrows(data);
+		const jas_seqent_t adjust = (jas_seqent_t)1 << (cmpt->prec - 1);
+		for (jas_matind_t i = 0; i < height; ++i) {
+			jpc_fix_t *p = jas_matrix_getref(data, i, 0);
+			for (jas_matind_t j = 0; j < width; ++j) {
+				p[j] += adjust;
+			}
+		}
+	}
+
+	/* Perform clipping. */
+	for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+	  dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+		if (cmpt->prec >= sizeof(jpc_fix_t) * 8 - 2 + cmpt->sgnd)
+			/* no need to clip, because the calculated
+			   minimum/maximum values would overflow our
+			   integer type anyway */
+			continue;
+
+		const jas_seqent_t mn = cmpt->sgnd
+			? (-((jpc_fix_t)1 << (cmpt->prec - 1)))
+			: (0);
+		const jas_seqent_t mx = cmpt->sgnd
+			? (((jpc_fix_t)1 << (cmpt->prec - 1)) - 1)
+			: (((jpc_fix_t)1 << cmpt->prec) - 1);
+		jas_matrix_clip(tcomp->data, mn, mx);
+	}
+
+	/* XXX need to free tsfb struct */
+
+	/* Write the data for each component of the image. */
+	for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+	  dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+		if (jas_image_writecmpt(dec->image, compno, tcomp->xstart -
+		  JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart -
+		  JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols(
+		  tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) {
+			jas_eprintf("write component failed\n");
+			return -1;
+		}
+	}
+
+	return 0;
+}
+
+static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	jpc_dec_tile_t *tile;
+
+	/* Eliminate compiler warnings about unused variables. */
+	(void)ms;
+
+	unsigned tileno;
+	for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
+	  ++tile) {
+		if (tile->state == JPC_TILE_ACTIVE ||
+			tile->state == JPC_TILE_ACTIVELAST) {
+			if (jpc_dec_tiledecode(dec, tile)) {
+				return -1;
+			}
+		}
+		/* If the tile has not yet been finalized, finalize it. */
+		// OLD CODE: jpc_dec_tilefini(dec, tile);
+		if (tile->state != JPC_TILE_DONE) {
+			jpc_dec_tilefini(dec, tile);
+		}
+	}
+
+	/* We are done processing the code stream. */
+	dec->state = JPC_MT;
+
+	return 1;
+}
+
+static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	jpc_siz_t *siz = &ms->parms.siz;
+	jpc_dec_tile_t *tile;
+	jpc_dec_tcomp_t *tcomp;
+	jpc_dec_cmpt_t *cmpt;
+	size_t size;
+	size_t num_samples;
+	size_t num_samples_delta;
+
+	size_t total_samples;
+	if (!jas_safe_size_mul(siz->width, siz->height, &total_samples) ||
+	    (dec->max_samples > 0 && total_samples > dec->max_samples)) {
+		jas_eprintf("image too large\n");
+		return -1;
+	}
+
+	size_t tile_samples;
+	if (!jas_safe_size_mul(siz->tilewidth, siz->tileheight, &tile_samples) ||
+	    (dec->max_samples > 0 && tile_samples > dec->max_samples)) {
+		jas_eprintf("tile too large\n");
+		return -1;
+	}
+
+	dec->xstart = siz->xoff;
+	dec->ystart = siz->yoff;
+	dec->xend = siz->width;
+	dec->yend = siz->height;
+	dec->tilewidth = siz->tilewidth;
+	dec->tileheight = siz->tileheight;
+	dec->tilexoff = siz->tilexoff;
+	dec->tileyoff = siz->tileyoff;
+	dec->numcomps = siz->numcomps;
+
+	if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
+		return -1;
+	}
+
+	if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
+		return -1;
+	}
+
+	num_samples = 0;
+	unsigned compno;
+	for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
+	  ++cmpt) {
+		cmpt->prec = siz->comps[compno].prec;
+		cmpt->sgnd = siz->comps[compno].sgnd;
+		cmpt->hstep = siz->comps[compno].hsamp;
+		cmpt->vstep = siz->comps[compno].vsamp;
+		cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
+		  JPC_CEILDIV(dec->xstart, cmpt->hstep);
+		cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
+		  JPC_CEILDIV(dec->ystart, cmpt->vstep);
+		cmpt->hsubstep = 0;
+		cmpt->vsubstep = 0;
+
+		if (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) {
+			jas_eprintf("image too large\n");
+			return -1;
+		}
+		if (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) {
+			jas_eprintf("image too large\n");
+			return -1;
+		}
+	}
+
+	if (dec->max_samples > 0 && num_samples > dec->max_samples) {
+		jas_eprintf("maximum number of samples exceeded (%zu > %zu)\n",
+		  num_samples, dec->max_samples);
+		return -1;
+	}
+
+	dec->image = 0;
+
+	dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
+	dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
+	if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size) ||
+	  size > INT_MAX) {
+		return -1;
+	}
+	if (dec->max_samples > 0 && size > dec->max_samples / 16 / 16) {
+		/* avoid Denial of Service by a malicious input file
+		   with millions of tiny tiles; if max_samples is
+		   configured, then assume the tiles are at least
+		   16x16, and don't allow more than this number of
+		   tiles */
+		return -1;
+	}
+	if (dec->max_samples > 0 && size > dec->max_samples / dec->numcomps / 16) {
+		/* another DoS check: since each tile allocates an
+		   array of components, this check attempts to catch
+		   excessive tile*component numbers */
+		return -1;
+	}
+	dec->numtiles = size;
+	JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
+	  dec->numtiles, dec->numhtiles, dec->numvtiles));
+	if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
+		return -1;
+	}
+
+	unsigned tileno;
+	for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
+	  ++tile) {
+		/* initialize all tiles with JPC_TILE_DONE so
+		   jpc_dec_destroy() knows which ones need a
+		   jpc_dec_tilefini() call; they are not actually
+		   "done", of course */
+		tile->state = JPC_TILE_DONE;
+	}
+
+	for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
+	  ++tile) {
+		const unsigned htileno = tileno % dec->numhtiles;
+		const unsigned vtileno = tileno / dec->numhtiles;
+		tile->realmode = 0;
+		tile->state = JPC_TILE_INIT;
+		tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
+		  dec->xstart);
+		tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
+		  dec->ystart);
+		tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
+		  dec->tilewidth, dec->xend);
+		tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
+		  dec->tileheight, dec->yend);
+		tile->numparts = 0;
+		tile->partno = 0;
+		tile->pkthdrstream = 0;
+		tile->pptstab = 0;
+		tile->cp = 0;
+		tile->pi = 0;
+		if (!(tile->tcomps = jas_alloc2(dec->numcomps,
+		  sizeof(jpc_dec_tcomp_t)))) {
+			return -1;
+		}
+		for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
+		  compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
+			tcomp->rlvls = 0;
+			tcomp->numrlvls = 0;
+			tcomp->data = 0;
+			tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
+			tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
+			tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
+			tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
+			tcomp->tsfb = 0;
+		}
+	}
+
+	dec->pkthdrstreams = 0;
+
+	/* We should expect to encounter other main header marker segments
+	  or an SOT marker segment next. */
+	dec->state = JPC_MH;
+
+	return 0;
+}
+
+static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	const jpc_cod_t *cod = &ms->parms.cod;
+	jpc_dec_tile_t *tile;
+
+	switch (dec->state) {
+	case JPC_MH:
+		jpc_dec_cp_setfromcod(dec->cp, cod);
+		break;
+	case JPC_TPH:
+		if (!(tile = dec->curtile)) {
+			return -1;
+		}
+		if (tile->partno != 0) {
+			return -1;
+		}
+		jpc_dec_cp_setfromcod(tile->cp, cod);
+		break;
+	}
+	return 0;
+}
+
+static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	const jpc_coc_t *coc = &ms->parms.coc;
+	jpc_dec_tile_t *tile;
+
+	if (coc->compno >= dec->numcomps) {
+		jas_eprintf("invalid component number in COC marker segment\n");
+		return -1;
+	}
+	switch (dec->state) {
+	case JPC_MH:
+		jpc_dec_cp_setfromcoc(dec->cp, coc);
+		break;
+	case JPC_TPH:
+		if (!(tile = dec->curtile)) {
+			return -1;
+		}
+		if (tile->partno > 0) {
+			return -1;
+		}
+		jpc_dec_cp_setfromcoc(tile->cp, coc);
+		break;
+	}
+	return 0;
+}
+
+static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	const jpc_rgn_t *rgn = &ms->parms.rgn;
+	jpc_dec_tile_t *tile;
+
+	if (rgn->compno >= dec->numcomps) {
+		jas_eprintf("invalid component number in RGN marker segment\n");
+		return -1;
+	}
+	switch (dec->state) {
+	case JPC_MH:
+		jpc_dec_cp_setfromrgn(dec->cp, rgn);
+		break;
+	case JPC_TPH:
+		if (!(tile = dec->curtile)) {
+			return -1;
+		}
+		if (tile->partno > 0) {
+			return -1;
+		}
+		jpc_dec_cp_setfromrgn(tile->cp, rgn);
+		break;
+	}
+
+	return 0;
+}
+
+static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	const jpc_qcd_t *qcd = &ms->parms.qcd;
+	jpc_dec_tile_t *tile;
+
+	switch (dec->state) {
+	case JPC_MH:
+		jpc_dec_cp_setfromqcd(dec->cp, qcd);
+		break;
+	case JPC_TPH:
+		if (!(tile = dec->curtile)) {
+			return -1;
+		}
+		if (tile->partno > 0) {
+			return -1;
+		}
+		jpc_dec_cp_setfromqcd(tile->cp, qcd);
+		break;
+	}
+	return 0;
+}
+
+static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	const jpc_qcc_t *qcc = &ms->parms.qcc;
+	jpc_dec_tile_t *tile;
+
+	if (qcc->compno >= dec->numcomps) {
+		jas_eprintf("invalid component number in QCC marker segment\n");
+		return -1;
+	}
+	switch (dec->state) {
+	case JPC_MH:
+		jpc_dec_cp_setfromqcc(dec->cp, qcc);
+		break;
+	case JPC_TPH:
+		if (!(tile = dec->curtile)) {
+			return -1;
+		}
+		if (tile->partno > 0) {
+			return -1;
+		}
+		jpc_dec_cp_setfromqcc(tile->cp, qcc);
+		break;
+	}
+	return 0;
+}
+
+static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	const jpc_poc_t *poc = &ms->parms.poc;
+	jpc_dec_tile_t *tile;
+	switch (dec->state) {
+	case JPC_MH:
+		if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) {
+			return -1;
+		}
+		break;
+	case JPC_TPH:
+		if (!(tile = dec->curtile)) {
+			return -1;
+		}
+		if (!tile->partno) {
+			if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) {
+				return -1;
+			}
+		} else {
+			jpc_pi_addpchgfrompoc(tile->pi, poc);
+		}
+		break;
+	}
+	return 0;
+}
+
+static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	jpc_ppm_t *ppm = &ms->parms.ppm;
+	jpc_ppxstabent_t *ppmstabent;
+
+	if (!dec->ppmstab) {
+		if (!(dec->ppmstab = jpc_ppxstab_create())) {
+			return -1;
+		}
+	}
+
+	if (!(ppmstabent = jpc_ppxstabent_create())) {
+		return -1;
+	}
+	ppmstabent->ind = ppm->ind;
+	ppmstabent->data = ppm->data;
+	ppm->data = 0;
+	ppmstabent->len = ppm->len;
+	if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) {
+		jpc_ppxstabent_destroy(ppmstabent);
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	jpc_ppt_t *ppt = &ms->parms.ppt;
+	jpc_dec_tile_t *tile;
+	jpc_ppxstabent_t *pptstabent;
+
+	tile = dec->curtile;
+	if (!tile->pptstab) {
+		if (!(tile->pptstab = jpc_ppxstab_create())) {
+			return -1;
+		}
+	}
+	if (!(pptstabent = jpc_ppxstabent_create())) {
+		return -1;
+	}
+	pptstabent->ind = ppt->ind;
+	pptstabent->data = ppt->data;
+	ppt->data = 0;
+	pptstabent->len = ppt->len;
+	if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) {
+		jpc_ppxstabent_destroy(pptstabent);
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	/* Eliminate compiler warnings about unused variables. */
+	USED(dec);
+	USED(ms);
+
+	return 0;
+}
+
+static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+	/* Eliminate compiler warnings about unused variables. */
+	USED(dec);
+
+	jas_eprintf("warning: ignoring unknown marker segment (0x%x)\n",
+	  ms->id);
+	return 0;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps)
+{
+	jpc_dec_cp_t *cp;
+	jpc_dec_ccp_t *ccp;
+
+	if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) {
+		return 0;
+	}
+	cp->flags = 0;
+	cp->numcomps = numcomps;
+	cp->prgord = 0;
+	cp->numlyrs = 0;
+	cp->mctid = 0;
+	cp->csty = 0;
+	if (!(cp->ccps = jas_alloc2(cp->numcomps, sizeof(jpc_dec_ccp_t)))) {
+		goto error;
+	}
+	if (!(cp->pchglist = jpc_pchglist_create())) {
+		goto error;
+	}
+	unsigned compno;
+	for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+	  ++compno, ++ccp) {
+		ccp->flags = 0;
+		ccp->numrlvls = 0;
+		ccp->cblkwidthexpn = 0;
+		ccp->cblkheightexpn = 0;
+		ccp->qmfbid = 0;
+		ccp->numstepsizes = 0;
+		ccp->numguardbits = 0;
+		ccp->roishift = 0;
+		ccp->cblkctx = 0;
+	}
+	return cp;
+error:
+	if (cp) {
+		jpc_dec_cp_destroy(cp);
+	}
+	return 0;
+}
+
+static jpc_dec_cp_t *jpc_dec_cp_copy(const jpc_dec_cp_t *cp)
+{
+	jpc_dec_cp_t *newcp;
+	jpc_dec_ccp_t *newccp;
+	const jpc_dec_ccp_t *ccp;
+
+	if (!(newcp = jpc_dec_cp_create(cp->numcomps))) {
+		return 0;
+	}
+	newcp->flags = cp->flags;
+	newcp->prgord = cp->prgord;
+	newcp->numlyrs = cp->numlyrs;
+	newcp->mctid = cp->mctid;
+	newcp->csty = cp->csty;
+	jpc_pchglist_destroy(newcp->pchglist);
+	newcp->pchglist = 0;
+	if (!(newcp->pchglist = jpc_pchglist_copy(cp->pchglist))) {
+		jas_free(newcp);
+		return 0;
+	}
+	unsigned compno;
+	for (compno = 0, newccp = newcp->ccps, ccp = cp->ccps;
+	  compno < cp->numcomps;
+	  ++compno, ++newccp, ++ccp) {
+		*newccp = *ccp;
+	}
+	return newcp;
+}
+
+static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp)
+{
+	jpc_dec_ccp_t *ccp;
+	cp->flags &= (JPC_CSET | JPC_QSET);
+
+	unsigned compno;
+	for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+	  ++compno, ++ccp) {
+		ccp->flags = 0;
+	}
+}
+
+static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp)
+{
+	if (cp->ccps) {
+		jas_free(cp->ccps);
+	}
+	if (cp->pchglist) {
+		jpc_pchglist_destroy(cp->pchglist);
+	}
+	jas_free(cp);
+}
+
+static int jpc_dec_cp_isvalid(const jpc_dec_cp_t *cp)
+{
+	uint_fast16_t compcnt;
+	const jpc_dec_ccp_t *ccp;
+
+	if (!(cp->flags & JPC_CSET) || !(cp->flags & JPC_QSET)) {
+		return 0;
+	}
+	for (compcnt = cp->numcomps, ccp = cp->ccps; compcnt > 0; --compcnt,
+	  ++ccp) {
+		/* Is there enough step sizes for the number of bands? */
+		if ((ccp->qsty != JPC_QCX_SIQNT && JAS_CAST(int, ccp->numstepsizes) < 3 *
+		  ccp->numrlvls - 2) || (ccp->qsty == JPC_QCX_SIQNT &&
+		  ccp->numstepsizes != 1)) {
+			return 0;
+		}
+	}
+	return 1;
+}
+
+static int calcstepsizes(uint_fast16_t refstepsize, unsigned numrlvls,
+  uint_fast16_t *stepsizes)
+{
+	uint_fast16_t expn;
+	uint_fast16_t mant;
+	expn = JPC_QCX_GETEXPN(refstepsize);
+	mant = JPC_QCX_GETMANT(refstepsize);
+	const unsigned numbands = 3 * numrlvls - 2;
+	for (unsigned bandno = 0; bandno < numbands; ++bandno) {
+//jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))));
+		const unsigned r = (bandno + 2) / 3;
+		const unsigned nb = (r == 0) ? (numrlvls - 1) - r : (numrlvls - 1) - r + 1;
+		uint_fast16_t e = expn - (numrlvls - 1) + nb;
+		if (e >= 0x20)
+			return -1;
+		stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(e);
+	}
+	return 0;
+}
+
+static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp)
+{
+	jpc_dec_ccp_t *ccp;
+	unsigned compno;
+	for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+	  ++compno, ++ccp) {
+		if (!(ccp->csty & JPC_COX_PRT)) {
+			for (unsigned i = 0; i < JPC_MAXRLVLS; ++i) {
+				ccp->prcwidthexpns[i] = 15;
+				ccp->prcheightexpns[i] = 15;
+			}
+		}
+		if (ccp->qsty == JPC_QCX_SIQNT) {
+			if (calcstepsizes(ccp->stepsizes[0], ccp->numrlvls, ccp->stepsizes)) {
+				return -1;
+			}
+		}
+	}
+	return 0;
+}
+
+static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, const jpc_cod_t *cod)
+{
+	jpc_dec_ccp_t *ccp;
+	cp->flags |= JPC_CSET;
+	cp->prgord = cod->prg;
+	if (cod->mctrans) {
+		cp->mctid = (cod->compparms.qmfbid == JPC_COX_INS) ? (JPC_MCT_ICT) : (JPC_MCT_RCT);
+	} else {
+		cp->mctid = JPC_MCT_NONE;
+	}
+	cp->numlyrs = cod->numlyrs;
+	cp->csty = cod->csty & (JPC_COD_SOP | JPC_COD_EPH);
+	unsigned compno;
+	for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+	  ++compno, ++ccp) {
+		jpc_dec_cp_setfromcox(cp, ccp, &cod->compparms, 0);
+	}
+	cp->flags |= JPC_CSET;
+	return 0;
+}
+
+static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, const jpc_coc_t *coc)
+{
+	jpc_dec_cp_setfromcox(cp, &cp->ccps[coc->compno], &coc->compparms, JPC_COC);
+	return 0;
+}
+
+static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
+  const jpc_coxcp_t *compparms, unsigned flags)
+{
+	int rlvlno;
+
+	/* Eliminate compiler warnings about unused variables. */
+	USED(cp);
+
+	if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) {
+		ccp->numrlvls = compparms->numdlvls + 1;
+		ccp->cblkwidthexpn = JPC_COX_GETCBLKSIZEEXPN(
+		  compparms->cblkwidthval);
+		ccp->cblkheightexpn = JPC_COX_GETCBLKSIZEEXPN(
+		  compparms->cblkheightval);
+		ccp->qmfbid = compparms->qmfbid;
+		ccp->cblkctx = compparms->cblksty;
+		ccp->csty = compparms->csty & JPC_COX_PRT;
+		for (rlvlno = 0; rlvlno < compparms->numrlvls; ++rlvlno) {
+			ccp->prcwidthexpns[rlvlno] =
+			  compparms->rlvls[rlvlno].parwidthval;
+			ccp->prcheightexpns[rlvlno] =
+			  compparms->rlvls[rlvlno].parheightval;
+		}
+		ccp->flags |= flags | JPC_CSET;
+	}
+	return 0;
+}
+
+static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, const jpc_qcd_t *qcd)
+{
+	unsigned compno;
+	jpc_dec_ccp_t *ccp;
+	for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+	  ++compno, ++ccp) {
+		jpc_dec_cp_setfromqcx(cp, ccp, &qcd->compparms, 0);
+	}
+	cp->flags |= JPC_QSET;
+	return 0;
+}
+
+static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, const jpc_qcc_t *qcc)
+{
+	return jpc_dec_cp_setfromqcx(cp, &cp->ccps[qcc->compno], &qcc->compparms, JPC_QCC);
+}
+
+static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
+  const jpc_qcxcp_t *compparms, unsigned flags)
+{
+	int bandno;
+
+	/* Eliminate compiler warnings about unused variables. */
+	USED(cp);
+
+	/* Sanity check to prevent buffer overflow */
+	if (compparms->numstepsizes > (3 * JPC_MAXRLVLS + 1)) {
+		return -1;
+	}
+
+	if ((flags & JPC_QCC) || !(ccp->flags & JPC_QCC)) {
+		ccp->flags |= flags | JPC_QSET;
+		for (bandno = 0; bandno < compparms->numstepsizes; ++bandno) {
+			ccp->stepsizes[bandno] = compparms->stepsizes[bandno];
+		}
+		ccp->numstepsizes = compparms->numstepsizes;
+		ccp->numguardbits = compparms->numguard;
+		ccp->qsty = compparms->qntsty;
+	}
+	return 0;
+}
+
+static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, const jpc_rgn_t *rgn)
+{
+	jpc_dec_ccp_t *ccp;
+	ccp = &cp->ccps[rgn->compno];
+	ccp->roishift = rgn->roishift;
+	return 0;
+}
+
+static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, const jpc_poc_t *poc)
+{
+	int pchgno;
+	jpc_pchg_t *pchg;
+	for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) {
+		if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) {
+			return -1;
+		}
+		if (jpc_pchglist_insert(pi->pchglist, -1, pchg)) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, const jpc_poc_t *poc, int reset)
+{
+	int pchgno;
+	jpc_pchg_t *pchg;
+	if (reset) {
+		while (jpc_pchglist_numpchgs(cp->pchglist) > 0) {
+			pchg = jpc_pchglist_remove(cp->pchglist, 0);
+			jpc_pchg_destroy(pchg);
+		}
+	}
+	for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) {
+		if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) {
+			return -1;
+		}
+		if (jpc_pchglist_insert(cp->pchglist, -1, pchg)) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static jpc_fix_t jpc_calcabsstepsize(unsigned stepsize, unsigned numbits)
+{
+	jpc_fix_t absstepsize;
+	int n;
+
+	absstepsize = jpc_inttofix(1);
+	n = JPC_FIX_FRACBITS - 11;
+	absstepsize |= (n >= 0) ? (JPC_QCX_GETMANT(stepsize) << n) :
+	  (JPC_QCX_GETMANT(stepsize) >> (-n));
+	n = numbits - JPC_QCX_GETEXPN(stepsize);
+	absstepsize = (n >= 0) ? (absstepsize << n) : (absstepsize >> (-n));
+	return absstepsize;
+}
+
+static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize)
+{
+	// a reconstruction parameter defined in E 1.1.2 of the ISO/IEC 15444-1
+	jpc_fix_t recparam = JPC_FIX_HALF;
+
+	assert(absstepsize >= 0);
+	if (absstepsize == jpc_inttofix(1)) {
+		return;
+	}
+
+	const jas_matind_t height = jas_matrix_numrows(x);
+	const size_t width = jas_matrix_numcols(x);
+
+	for (jas_matind_t i = 0; i < height; ++i) {
+		jpc_fix_t *p = jas_matrix_getref(x, i, 0);
+		for (size_t j = 0; j < width; ++j) {
+			jas_seqent_t t = p[j];
+			if (t) {
+				// mid-point reconstruction
+				t = (t > 0) ? jpc_fix_add(t, recparam) : jpc_fix_sub(t, recparam);
+				t = jpc_fix_mul(t, absstepsize);
+				p[j] = t;
+			}
+		}
+	}
+
+}
+
+static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, unsigned numbps)
+{
+	int thresh;
+	jpc_fix_t val;
+	jpc_fix_t mag;
+	bool warn;
+	uint_fast32_t mask;
+
+	if (roishift < 0) {
+		/* We could instead return an error here. */
+		/* I do not think it matters much. */
+		jas_eprintf("warning: forcing negative ROI shift to zero "
+		  "(bitstream is probably corrupt)\n");
+		roishift = 0;
+	}
+	if (roishift == 0 && bgshift == 0) {
+		return;
+	}
+	thresh = 1 << roishift;
+
+	warn = false;
+
+	const jas_matind_t width = jas_matrix_numcols(x);
+	const jas_matind_t height = jas_matrix_numrows(x);
+	for (jas_matind_t i = 0; i < height; ++i) {
+		jpc_fix_t *p = jas_matrix_getref(x, i, 0);
+		for (jas_matind_t j = 0; j < width; ++j, ++p) {
+			val = *p;
+			mag = JAS_ABS(val);
+			if (mag >= thresh) {
+				/* We are dealing with ROI data. */
+				mag >>= roishift;
+				val = (val < 0) ? (-mag) : mag;
+				*p = val;
+			} else {
+				/* We are dealing with non-ROI (i.e., background) data. */
+				mag <<= bgshift;
+				mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1;
+				/* Perform a basic sanity check on the sample value. */
+				/* Some implementations write garbage in the unused
+				  most-significant bit planes introduced by ROI shifting.
+				  Here we ensure that any such bits are masked off. */
+				if (mag & (~mask)) {
+					if (!warn) {
+						jas_eprintf("warning: possibly corrupt code stream\n");
+						warn = true;
+					}
+					mag &= mask;
+				}
+				val = (val < 0) ? (-mag) : mag;
+				*p = val;
+			}
+		}
+	}
+}
+
+static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in)
+{
+	jpc_dec_t *dec;
+
+	if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) {
+		return 0;
+	}
+
+	dec->image = 0;
+	dec->xstart = 0;
+	dec->ystart = 0;
+	dec->xend = 0;
+	dec->yend = 0;
+	dec->tilewidth = 0;
+	dec->tileheight = 0;
+	dec->tilexoff = 0;
+	dec->tileyoff = 0;
+	dec->numhtiles = 0;
+	dec->numvtiles = 0;
+	dec->numtiles = 0;
+	dec->tiles = 0;
+	dec->curtile = 0;
+	dec->numcomps = 0;
+	dec->in = in;
+	dec->cp = 0;
+	dec->maxlyrs = impopts->maxlyrs;
+	dec->maxpkts = impopts->maxpkts;
+dec->numpkts = 0;
+	dec->ppmseqno = 0;
+	dec->state = 0;
+	dec->cmpts = 0;
+	dec->pkthdrstreams = 0;
+	dec->ppmstab = 0;
+	dec->curtileendoff = 0;
+	dec->max_samples = impopts->max_samples;
+
+	return dec;
+}
+
+static void jpc_dec_destroy(jpc_dec_t *dec)
+{
+	if (dec->cstate) {
+		jpc_cstate_destroy(dec->cstate);
+	}
+	if (dec->pkthdrstreams) {
+		jpc_streamlist_destroy(dec->pkthdrstreams);
+	}
+	if (dec->ppmstab) {
+		jpc_ppxstab_destroy(dec->ppmstab);
+	}
+	if (dec->image) {
+		jas_image_destroy(dec->image);
+	}
+
+	if (dec->cp) {
+		jpc_dec_cp_destroy(dec->cp);
+	}
+
+	if (dec->cmpts) {
+		jas_free(dec->cmpts);
+	}
+
+	if (dec->tiles) {
+		unsigned tileno;
+		jpc_dec_tile_t *tile;
+
+		for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
+		  ++tile) {
+			if (tile->state != JPC_TILE_DONE) {
+				jpc_dec_tilefini(dec, tile);
+			}
+		}
+
+		jas_free(dec->tiles);
+	}
+
+	jas_free(dec);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, jpc_dec_seg_t *node)
+{
+	jpc_dec_seg_t *prev;
+	jpc_dec_seg_t *next;
+
+	prev = ins;
+	node->prev = prev;
+	next = prev ? (prev->next) : 0;
+	node->prev = prev;
+	node->next = next;
+	if (prev) {
+		prev->next = node;
+	} else {
+		list->head = node;
+	}
+	if (next) {
+		next->prev = node;
+	} else {
+		list->tail = node;
+	}
+}
+
+void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *seg)
+{
+	jpc_dec_seg_t *prev;
+	jpc_dec_seg_t *next;
+
+	prev = seg->prev;
+	next = seg->next;
+	if (prev) {
+		prev->next = next;
+	} else {
+		list->head = next;
+	}
+	if (next) {
+		next->prev = prev;
+	} else {
+		list->tail = prev;
+	}
+	seg->prev = 0;
+	seg->next = 0;
+}
+
+jpc_dec_seg_t *jpc_seg_alloc()
+{
+	jpc_dec_seg_t *seg;
+
+	if (!(seg = jas_malloc(sizeof(jpc_dec_seg_t)))) {
+		return 0;
+	}
+	seg->prev = 0;
+	seg->next = 0;
+	seg->passno = -1;
+	seg->numpasses = 0;
+	seg->maxpasses = 0;
+	seg->type = JPC_SEG_INVALID;
+	seg->stream = 0;
+	seg->cnt = 0;
+	seg->complete = 0;
+	seg->lyrno = -1;
+	return seg;
+}
+
+void jpc_seg_destroy(jpc_dec_seg_t *seg)
+{
+	if (seg->stream) {
+		jas_stream_close(seg->stream);
+	}
+	jas_free(seg);
+}
+
+static int jpc_dec_dump(const jpc_dec_t *dec, FILE *out)
+{
+	assert(!dec->numtiles || dec->tiles);
+	unsigned tileno;
+	const jpc_dec_tile_t *tile;
+	for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles;
+	  ++tileno, ++tile) {
+		assert(!dec->numcomps || tile->tcomps);
+		unsigned compno;
+		const jpc_dec_tcomp_t *tcomp;
+		for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+		     ++compno, ++tcomp) {
+			unsigned rlvlno;
+			const jpc_dec_rlvl_t *rlvl;
+			for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno <
+			  tcomp->numrlvls; ++rlvlno, ++rlvl) {
+				fprintf(out, "RESOLUTION LEVEL %d\n", rlvlno);
+				fprintf(out, "xs = %"PRIuFAST32", ys = %"PRIuFAST32", xe = %"PRIuFAST32", ye = %"PRIuFAST32", w = %"PRIuFAST32", h = %"PRIuFAST32"\n",
+				  rlvl->xstart, rlvl->ystart, rlvl->xend, rlvl->yend,
+				  rlvl->xend - rlvl->xstart, rlvl->yend - rlvl->ystart);
+				assert(!rlvl->numbands || rlvl->bands);
+				unsigned bandno;
+				const jpc_dec_band_t *band;
+				for (bandno = 0, band = rlvl->bands;
+				  bandno < rlvl->numbands; ++bandno, ++band) {
+					fprintf(out, "BAND %d\n", bandno);
+					if (!band->data) {
+						fprintf(out, "band has no data (null pointer)\n");
+						assert(!band->prcs);
+						continue;
+					}
+					fprintf(out, "xs = %"PRIjas_seqent", ys = %"PRIjas_seqent", xe = %"PRIjas_seqent", ye = %"PRIjas_seqent", w = %"PRIjas_seqent", h = %"PRIjas_seqent"\n",
+					  jas_seq2d_xstart(band->data),
+					  jas_seq2d_ystart(band->data),
+					  jas_seq2d_xend(band->data),
+					  jas_seq2d_yend(band->data),
+					  jas_seq2d_xend(band->data) -
+					  jas_seq2d_xstart(band->data),
+					  jas_seq2d_yend(band->data) -
+					  jas_seq2d_ystart(band->data));
+					assert(!rlvl->numprcs || band->prcs);
+					unsigned prcno;
+					const jpc_dec_prc_t *prc;
+					for (prcno = 0, prc = band->prcs;
+					  prcno < rlvl->numprcs; ++prcno,
+					  ++prc) {
+						fprintf(out, "CODE BLOCK GROUP %d\n", prcno);
+						fprintf(out, "xs = %"PRIuFAST32", ys = %"PRIuFAST32", xe = %"PRIuFAST32", ye = %"PRIuFAST32", w = %"PRIuFAST32", h = %"PRIuFAST32"\n",
+						  prc->xstart, prc->ystart, prc->xend, prc->yend,
+						  prc->xend - prc->xstart, prc->yend - prc->ystart);
+						assert(!prc->numcblks || prc->cblks);
+						unsigned cblkno;
+						const jpc_dec_cblk_t *cblk;
+						for (cblkno = 0, cblk =
+						  prc->cblks; cblkno <
+						  prc->numcblks; ++cblkno,
+						  ++cblk) {
+							fprintf(out, "CODE BLOCK %d\n", cblkno);
+							fprintf(out, "xs = %"PRIjas_seqent", ys = %"PRIjas_seqent", xe = %"PRIjas_seqent", ye = %"PRIjas_seqent", w = %"PRIjas_seqent", h = %"PRIjas_seqent"\n",
+							  jas_seq2d_xstart(cblk->data),
+							  jas_seq2d_ystart(cblk->data),
+							  jas_seq2d_xend(cblk->data),
+							  jas_seq2d_yend(cblk->data),
+							  jas_seq2d_xend(cblk->data) -
+							  jas_seq2d_xstart(cblk->data),
+							  jas_seq2d_yend(cblk->data) -
+							  jas_seq2d_ystart(cblk->data));
+						}
+					}
+				}
+			}
+		}
+	}
+
+	return 0;
+}
+
+static jpc_streamlist_t *jpc_streamlist_create()
+{
+	jpc_streamlist_t *streamlist;
+
+	if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) {
+		return 0;
+	}
+	streamlist->numstreams = 0;
+	streamlist->maxstreams = 100;
+	if (!(streamlist->streams = jas_alloc2(streamlist->maxstreams,
+	  sizeof(jas_stream_t *)))) {
+		jas_free(streamlist);
+		return 0;
+	}
+	for (unsigned i = 0; i < streamlist->maxstreams; ++i) {
+		streamlist->streams[i] = 0;
+	}
+	return streamlist;
+}
+
+static int jpc_streamlist_insert(jpc_streamlist_t *streamlist, unsigned streamno,
+  jas_stream_t *stream)
+{
+	jas_stream_t **newstreams;
+	/* Grow the array of streams if necessary. */
+	if (streamlist->numstreams >= streamlist->maxstreams) {
+		const unsigned newmaxstreams = streamlist->maxstreams + 1024;
+		if (!(newstreams = jas_realloc2(streamlist->streams,
+		  (newmaxstreams + 1024), sizeof(jas_stream_t *)))) {
+			return -1;
+		}
+		for (unsigned i = streamlist->numstreams; i < streamlist->maxstreams; ++i) {
+			streamlist->streams[i] = 0;
+		}
+		streamlist->maxstreams = newmaxstreams;
+		streamlist->streams = newstreams;
+	}
+	if (streamno != streamlist->numstreams) {
+		/* Can only handle insertion at start of list. */
+		return -1;
+	}
+	streamlist->streams[streamno] = stream;
+	++streamlist->numstreams;
+	return 0;
+}
+
+static jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, unsigned streamno)
+{
+	assert(streamno < streamlist->numstreams);
+
+	jas_stream_t *stream;
+	stream = streamlist->streams[streamno];
+	for (unsigned i = streamno + 1; i < streamlist->numstreams; ++i) {
+		streamlist->streams[i - 1] = streamlist->streams[i];
+	}
+	--streamlist->numstreams;
+	return stream;
+}
+
+static void jpc_streamlist_destroy(jpc_streamlist_t *streamlist)
+{
+	if (streamlist->streams) {
+		for (unsigned streamno = 0; streamno < streamlist->numstreams;
+		  ++streamno) {
+			jas_stream_close(streamlist->streams[streamno]);
+		}
+		jas_free(streamlist->streams);
+	}
+	jas_free(streamlist);
+}
+
+static int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist)
+{
+	return streamlist->numstreams;
+}
+
+static jpc_ppxstab_t *jpc_ppxstab_create()
+{
+	jpc_ppxstab_t *tab;
+
+	if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) {
+		return 0;
+	}
+	tab->numents = 0;
+	tab->maxents = 0;
+	tab->ents = 0;
+	return tab;
+}
+
+static void jpc_ppxstab_destroy(jpc_ppxstab_t *tab)
+{
+	for (unsigned i = 0; i < tab->numents; ++i) {
+		jpc_ppxstabent_destroy(tab->ents[i]);
+	}
+	if (tab->ents) {
+		jas_free(tab->ents);
+	}
+	jas_free(tab);
+}
+
+static int jpc_ppxstab_grow(jpc_ppxstab_t *tab, unsigned maxents)
+{
+	jpc_ppxstabent_t **newents;
+	if (tab->maxents < maxents) {
+		newents = (tab->ents) ? jas_realloc2(tab->ents, maxents,
+		  sizeof(jpc_ppxstabent_t *)) : jas_alloc2(maxents, sizeof(jpc_ppxstabent_t *));
+		if (!newents) {
+			return -1;
+		}
+		tab->ents = newents;
+		tab->maxents = maxents;
+	}
+	return 0;
+}
+
+static int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent)
+{
+	unsigned i;
+
+	for (i = 0; i < tab->numents; ++i) {
+		if (tab->ents[i]->ind > ent->ind) {
+			break;
+		}
+	}
+	const unsigned inspt = i;
+
+	if (tab->numents >= tab->maxents) {
+		if (jpc_ppxstab_grow(tab, tab->maxents + 128)) {
+			return -1;
+		}
+	}
+
+	for (i = tab->numents; i > inspt; --i) {
+		tab->ents[i] = tab->ents[i - 1];
+	}
+	tab->ents[i] = ent;
+	++tab->numents;
+
+	return 0;
+}
+
+static jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)
+{
+	jpc_streamlist_t *streams;
+	uint_fast32_t datacnt;
+	uint_fast32_t tpcnt;
+	jas_stream_t *stream;
+
+	if (!(streams = jpc_streamlist_create())) {
+		goto error;
+	}
+
+	if (!tab->numents) {
+		return streams;
+	}
+
+	unsigned entno = 0;
+	const jpc_ppxstabent_t *ent = tab->ents[entno];
+	const jas_uchar *dataptr = ent->data;
+	datacnt = ent->len;
+	for (;;) {
+
+		/* Get the length of the packet header data for the current
+		  tile-part. */
+		if (datacnt < 4) {
+			goto error;
+		}
+		if (!(stream = jas_stream_memopen(0, 0))) {
+			goto error;
+		}
+		if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),
+		  stream)) {
+			goto error;
+		}
+		tpcnt = ((uint_least32_t)dataptr[0] << 24) | ((uint_least32_t)dataptr[1] << 16) | ((uint_least32_t)dataptr[2] << 8)
+		  | (uint_least32_t)dataptr[3];
+		datacnt -= 4;
+		dataptr += 4;
+
+		/* Get the packet header data for the current tile-part. */
+		while (tpcnt) {
+			if (!datacnt) {
+				if (++entno >= tab->numents) {
+					goto error;
+				}
+				ent = tab->ents[entno];
+				dataptr = ent->data;
+				datacnt = ent->len;
+			}
+			const size_t n = JAS_MIN(tpcnt, datacnt);
+			if (jas_stream_write(stream, dataptr, n) != n) {
+				goto error;
+			}
+			tpcnt -= n;
+			dataptr += n;
+			datacnt -= n;
+		}
+		jas_stream_rewind(stream);
+		if (!datacnt) {
+			if (++entno >= tab->numents) {
+				break;
+			}
+			ent = tab->ents[entno];
+			dataptr = ent->data;
+			datacnt = ent->len;
+		}
+	}
+
+	return streams;
+
+error:
+	if (streams) {
+		jpc_streamlist_destroy(streams);
+	}
+	return 0;
+}
+
+static int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab)
+{
+	for (unsigned i = 0; i < tab->numents; ++i) {
+		const jpc_ppxstabent_t *ent = tab->ents[i];
+		if (jas_stream_write(out, ent->data, ent->len) != ent->len) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static jpc_ppxstabent_t *jpc_ppxstabent_create()
+{
+	jpc_ppxstabent_t *ent;
+	if (!(ent = jas_malloc(sizeof(jpc_ppxstabent_t)))) {
+		return 0;
+	}
+	ent->data = 0;
+	ent->len = 0;
+	ent->ind = 0;
+	return ent;
+}
+
+static void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent)
+{
+	if (ent->data) {
+		jas_free(ent->data);
+	}
+	jas_free(ent);
+}
--- /dev/null
+++ b/jpc_dec.h
@@ -1,0 +1,687 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JPEG-2000 Decoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_DEC_H
+#define JPC_DEC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+
+#include "jpc_tsfb.h"
+#include "jpc_tagtree.h"
+#include "jpc_cs.h"
+#include "jpc_t1cod.h"
+#include "jpc_t2cod.h"
+
+/******************************************************************************\
+* Below are some ugly warts necessary to support packed packet headers.
+\******************************************************************************/
+
+/* PPM/PPT marker segment table entry. */
+
+typedef struct {
+
+	/* The index for this entry. */
+	uint_fast16_t ind;
+
+	/* The data length. */
+	uint_fast32_t len;
+
+	/* The data. */
+	jas_uchar *data;
+
+} jpc_ppxstabent_t;
+
+/* PPM/PPT marker segment table. */
+
+typedef struct {
+
+	/* The number of entries. */
+	unsigned numents;
+
+	/* The maximum number of entries (i.e., the allocated size of the array
+	  below). */
+	unsigned maxents;
+
+	/* The table entries. */
+	jpc_ppxstabent_t **ents;
+
+} jpc_ppxstab_t;
+
+/* Stream list class. */
+
+typedef struct {
+
+	/* The number of streams in this list. */
+	unsigned numstreams;
+
+	/* The maximum number of streams that can be accomodated without
+	  growing the streams array. */
+	unsigned maxstreams;
+
+	/* The streams. */
+	jas_stream_t **streams;
+
+} jpc_streamlist_t;
+
+/******************************************************************************\
+* Coding parameters class.
+\******************************************************************************/
+
+/* Per-component coding parameters. */
+
+typedef struct {
+
+	/* How were various coding parameters set? */
+	unsigned flags;
+
+	/* Per-component coding style parameters (e.g., explicit precinct sizes) */
+	uint_fast8_t csty;
+
+	/* The number of resolution levels. */
+	uint_fast8_t numrlvls;
+
+	/* The code block width exponent. */
+	uint_fast8_t cblkwidthexpn;
+
+	/* The code block height exponent. */
+	uint_fast8_t cblkheightexpn;
+
+	/* The QMFB ID. */
+	uint_fast8_t qmfbid;
+
+	/* The quantization style. */
+	uint_fast8_t qsty;
+
+	/* The number of quantizer step sizes. */
+	uint_fast16_t numstepsizes;
+
+	/* The step sizes. */
+	uint_fast16_t stepsizes[3 * JPC_MAXRLVLS + 1];
+
+	/* The number of guard bits. */
+	uint_fast8_t numguardbits;
+
+	/* The ROI shift value. */
+	uint_fast8_t roishift;
+
+	/* The code block parameters. */
+	uint_fast8_t cblkctx;
+
+	/* The precinct width exponents. */
+	uint_fast8_t prcwidthexpns[JPC_MAXRLVLS];
+
+	/* The precinct height exponents. */
+	uint_fast8_t prcheightexpns[JPC_MAXRLVLS];
+
+} jpc_dec_ccp_t;
+
+/* Coding paramters. */
+
+typedef struct {
+
+	/* How were these coding parameters set? */
+	unsigned flags;
+
+	/* Progression change list. */
+	jpc_pchglist_t *pchglist;
+
+	/* Progression order. */
+	uint_fast8_t prgord;
+
+	/* The number of layers. */
+	uint_fast16_t numlyrs;
+
+	/* The MCT ID. */
+	uint_fast8_t mctid;
+
+	/* The coding style parameters (e.g., SOP, EPH). */
+	uint_fast8_t csty;
+
+	/* The number of components. */
+	unsigned numcomps;
+
+	/* The per-component coding parameters. */
+	jpc_dec_ccp_t *ccps;
+
+} jpc_dec_cp_t;
+
+/******************************************************************************\
+* Decoder class.
+\******************************************************************************/
+
+/* Decoder per-segment state information. */
+
+typedef struct jpc_dec_seg_s {
+
+	/* The next segment in the list. */
+	struct jpc_dec_seg_s *next;
+
+	/* The previous segment in the list. */
+	struct jpc_dec_seg_s *prev;
+
+	/* The starting pass number for this segment. */
+	unsigned passno;
+
+	/* The number of passes in this segment. */
+	unsigned numpasses;
+
+	/* The maximum number of passes in this segment. */
+	unsigned maxpasses;
+
+	/* The type of data in this segment (i.e., MQ or raw). */
+	enum jpc_segtype type;
+
+	/* A stream containing the data for this segment. */
+	jas_stream_t *stream;
+
+	/* The number of bytes destined for this segment from the packet
+	  currently being decoded. */
+	unsigned cnt;
+
+	/* A flag indicating if this segment has been terminated. */
+	int complete;
+
+	/* The layer number to which this segment belongs. */
+	/* If the segment spans multiple layers, then the largest layer number
+	  spanned by the segment is used. */
+	unsigned lyrno;
+
+} jpc_dec_seg_t;
+
+/* Decoder segment list. */
+
+typedef struct {
+
+	/* The first entry in the list. */
+	jpc_dec_seg_t *head;
+
+	/* The last entry in the list. */
+	jpc_dec_seg_t *tail;
+
+} jpc_dec_seglist_t;
+
+/* Decoder per-code-block state information. */
+
+typedef struct {
+
+	/* The number of passes. */
+	unsigned numpasses;
+
+	/* A list of segments that still need to be decoded. */
+	jpc_dec_seglist_t segs;
+
+	/* The first incomplete/partial segment. */
+	jpc_dec_seg_t *curseg;
+
+	/* The number of leading insignificant bit planes for this code block. */
+	unsigned numimsbs;
+
+	/* The number of bits used to encode pass data lengths. */
+	unsigned numlenbits;
+
+	/* The first pass number containing data for this code block. */
+	unsigned firstpassno;
+
+	/* The sample data associated with this code block. */
+	jas_matrix_t *data;
+
+} jpc_dec_cblk_t;
+
+/* Decoder per-code-block-group state information. */
+
+typedef struct {
+
+	/* The x-coordinate of the top-left corner of the precinct. */
+	uint_fast32_t xstart;
+
+	/* The y-coordinate of the top-left corner of the precinct. */
+	uint_fast32_t ystart;
+
+	/* The x-coordinate of the bottom-right corner of the precinct
+	  (plus one). */
+	uint_fast32_t xend;
+
+	/* The y-coordinate of the bottom-right corner of the precinct
+	  (plus one). */
+	uint_fast32_t yend;
+
+	/* The number of code blocks spanning this precinct in the horizontal
+	  direction. */
+	unsigned numhcblks;
+
+	/* The number of code blocks spanning this precinct in the vertical
+	  direction. */
+	unsigned numvcblks;
+
+	/* The total number of code blocks in this precinct. */
+	unsigned numcblks;
+
+	/* The per code block information. */
+	jpc_dec_cblk_t *cblks;
+
+	/* The inclusion tag tree. */
+	jpc_tagtree_t *incltagtree;
+
+	/* The insignificant MSBs tag tree. */
+	jpc_tagtree_t *numimsbstagtree;
+
+} jpc_dec_prc_t;
+
+/* Decoder per-band state information. */
+
+typedef struct {
+
+	/* The per-code-block-group state information. */
+	jpc_dec_prc_t *prcs;
+
+	/* The sample data associated with this band. */
+	jas_matrix_t *data;
+
+	/* The orientation of this band (i.e., LL, LH, HL, or HH). */
+	enum jpc_tsfb_orient orient;
+
+	/* The encoded quantizer step size. */
+	unsigned stepsize;
+
+	/* The absolute quantizer step size. */
+	jpc_fix_t absstepsize;
+
+	/* The number of bit planes for this band. */
+	unsigned numbps;
+
+	/* The analysis gain associated with this band. */
+	int analgain;
+
+	/* The ROI shift value for this band. */
+	int roishift;
+
+} jpc_dec_band_t;
+
+/* Decoder per-resolution-level state information. */
+
+typedef struct {
+
+	/* The number of bands associated with this resolution level. */
+	unsigned numbands;
+
+	/* The per-band information. */
+	jpc_dec_band_t *bands;
+
+	/* The x-coordinate of the top-left corner of the tile-component
+	  at this resolution. */
+	uint_fast32_t xstart;
+
+	/* The y-coordinate of the top-left corner of the tile-component
+	  at this resolution. */
+	uint_fast32_t ystart;
+
+	/* The x-coordinate of the bottom-right corner of the tile-component
+	  at this resolution (plus one). */
+	uint_fast32_t xend;
+
+	/* The y-coordinate of the bottom-right corner of the tile-component
+	  at this resolution (plus one). */
+	uint_fast32_t yend;
+
+	/* The exponent value for the nominal precinct width measured
+	  relative to the associated LL band. */
+	unsigned prcwidthexpn;
+
+	/* The exponent value for the nominal precinct height measured
+	  relative to the associated LL band. */
+	unsigned prcheightexpn;
+
+	/* The number of precincts in the horizontal direction. */
+	unsigned numhprcs;
+
+	/* The number of precincts in the vertical direction. */
+	unsigned numvprcs;
+
+	/* The total number of precincts. */
+	unsigned numprcs;
+
+	/* The exponent value for the nominal code block group width.
+	  This quantity is associated with the next lower resolution level
+	  (assuming that there is one). */
+	unsigned cbgwidthexpn;
+
+	/* The exponent value for the nominal code block group height
+	  This quantity is associated with the next lower resolution level
+	  (assuming that there is one). */
+	unsigned cbgheightexpn;
+
+	/* The exponent value for the code block width. */
+	uint_fast16_t cblkwidthexpn;
+
+	/* The exponent value for the code block height. */
+	uint_fast16_t cblkheightexpn;
+
+} jpc_dec_rlvl_t;
+
+/* Decoder per-tile-component state information. */
+
+typedef struct {
+
+	/* The x-coordinate of the top-left corner of the tile-component
+	  in the coordinate system of the tile-component. */
+	uint_fast32_t xstart;
+
+	/* The y-coordinate of the top-left corner of the tile-component
+	  in the coordinate system of the tile-component. */
+	uint_fast32_t ystart;
+
+	/* The x-coordinate of the bottom-right corner of the tile-component
+	  in the coordinate system of the tile-component (plus one). */
+	uint_fast32_t xend;
+
+	/* The y-coordinate of the bottom-right corner of the tile-component
+	  in the coordinate system of the tile-component (plus one). */
+	uint_fast32_t yend;
+
+	/* The component data for the current tile. */
+	jas_matrix_t *data;
+
+	/* The number of resolution levels. */
+	unsigned numrlvls;
+
+	/* The per resolution level information. */
+	jpc_dec_rlvl_t *rlvls;
+
+	/* The TSFB. */
+	jpc_tsfb_t *tsfb;
+
+} jpc_dec_tcomp_t;
+
+/*
+ * Tile states.
+ */
+
+#define	JPC_TILE_INIT	0
+#define	JPC_TILE_ACTIVE	1
+#define	JPC_TILE_ACTIVELAST	2
+#define	JPC_TILE_DONE	3
+
+/* Decoder per-tile state information. */
+
+typedef struct {
+
+	/* The processing state for this tile. */
+	int state;
+
+	/* The x-coordinate of the top-left corner of the tile on the reference
+	  grid. */
+	uint_fast32_t xstart;
+
+	/* The y-coordinate of the top-left corner of the tile on the reference
+	  grid. */
+	uint_fast32_t ystart;
+
+	/* The x-coordinate of the bottom-right corner of the tile on the
+	  reference grid (plus one). */
+	uint_fast32_t xend;
+
+	/* The y-coordinate of the bottom-right corner of the tile on the
+	  reference grid (plus one). */
+	uint_fast32_t yend;
+
+	/* The packed packet header data for this tile. */
+	jpc_ppxstab_t *pptstab;
+
+	/* A stream containing the packed packet header data for this tile. */
+	jas_stream_t *pkthdrstream;
+
+	/* The coding parameters for this tile. */
+	jpc_dec_cp_t *cp;
+
+	/* The per tile-component information. */
+	jpc_dec_tcomp_t *tcomps;
+
+	/* The next expected tile-part number. */
+	unsigned partno;
+
+	/* The number of tile-parts. */
+	unsigned numparts;
+
+	/* The coding mode. */
+	int realmode;
+
+	/* The packet iterator for this tile. */
+	jpc_pi_t *pi;
+
+} jpc_dec_tile_t;
+
+/* Decoder per-component state information. */
+
+typedef struct {
+
+	/* The horizontal sampling period. */
+	uint_fast32_t hstep;
+
+	/* The vertical sampling period. */
+	uint_fast32_t vstep;
+
+	/* The number of samples in the horizontal direction. */
+	uint_fast32_t width;
+
+	/* The number of samples in the vertical direction. */
+	uint_fast32_t height;
+
+	/* The precision of the sample data. */
+	uint_fast16_t prec;
+
+	/* The signedness of the sample data. */
+	bool sgnd;
+
+	/* The sample alignment horizontal offset. */
+	uint_fast32_t hsubstep;
+	
+	/* The sample alignment vertical offset. */
+	uint_fast32_t vsubstep;
+
+} jpc_dec_cmpt_t;
+
+/* Decoder state information. */
+
+typedef struct {
+
+	/* The decoded image. */
+	jas_image_t *image;
+
+	/* The x-coordinate of the top-left corner of the image area on
+	  the reference grid. */
+	uint_fast32_t xstart;
+
+	/* The y-coordinate of the top-left corner of the image area on
+	  the reference grid. */
+	uint_fast32_t ystart;
+
+	/* The x-coordinate of the bottom-right corner of the image area on
+	  the reference grid (plus one). */
+	uint_fast32_t xend;
+
+	/* The y-coordinate of the bottom-right corner of the image area on
+	  the reference grid (plus one). */
+	uint_fast32_t yend;
+
+	/* The nominal tile width in units of the image reference grid. */
+	uint_fast32_t tilewidth;
+
+	/* The nominal tile height in units of the image reference grid. */
+	uint_fast32_t tileheight;
+
+	/* The horizontal offset from the origin of the reference grid to the
+	  left side of the first tile. */
+	uint_fast32_t tilexoff;
+
+	/* The vertical offset from the origin of the reference grid to the
+	  top side of the first tile. */
+	uint_fast32_t tileyoff;
+
+	/* The number of tiles spanning the image area in the vertical
+	  direction. */
+	unsigned numhtiles;
+
+	/* The number of tiles spanning the image area in the horizontal
+	  direction. */
+	unsigned numvtiles;
+
+	/* The total number of tiles. */
+	unsigned numtiles;
+
+	/* The per-tile information. */
+	jpc_dec_tile_t *tiles;
+
+	/* The tile currently being processed. */
+	jpc_dec_tile_t *curtile;
+
+	/* The number of components. */
+	unsigned numcomps;
+
+	/* The stream containing the input JPEG-2000 code stream data. */
+	jas_stream_t *in;
+
+	/* The default coding parameters for all tiles. */
+	jpc_dec_cp_t *cp;
+
+	/* The maximum number of layers that may be decoded. */
+	unsigned maxlyrs;
+
+	/* The maximum number of packets that may be decoded. */
+	int maxpkts;
+
+	/* The number of packets decoded so far in the processing of the entire
+	  code stream. */
+	unsigned numpkts;
+
+	/* The next expected PPM marker segment sequence number. */
+	unsigned ppmseqno;
+
+	/* The current state for code stream processing. */
+	int state;
+
+	/* The per-component information. */
+	jpc_dec_cmpt_t *cmpts;
+
+	/* The information from PPM marker segments. */
+	jpc_ppxstab_t *ppmstab;
+
+	/* A list of streams containing packet header data from PPM marker
+	  segments. */
+	jpc_streamlist_t *pkthdrstreams;
+
+	/* The expected ending offset for a tile-part. */
+	long curtileendoff;
+
+	/* This is required by the tier-2 decoder. */
+	jpc_cstate_t *cstate;
+
+	size_t max_samples;
+
+} jpc_dec_t;
+
+/* Decoder options. */
+
+typedef struct {
+
+	/* The debug level for the decoder. */
+	int debug;
+
+	/* The maximum number of layers to decode. */
+	unsigned maxlyrs;
+
+	/* The maximum number of packets to decode. */
+	int maxpkts;
+
+	size_t max_samples;
+
+} jpc_dec_importopts_t;
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Create a decoder segment object. */
+jpc_dec_seg_t *jpc_seg_alloc(void);
+
+/* Destroy a decoder segment object. */
+void jpc_seg_destroy(jpc_dec_seg_t *seg);
+
+/* Remove a segment from a segment list. */
+void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *node);
+
+/* Insert a segment into a segment list. */
+void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins,
+  jpc_dec_seg_t *node);
+
+#endif
--- /dev/null
+++ b/jpc_fix.h
@@ -1,0 +1,231 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Fixed-Point Number Class
+ *
+ * $Id$
+ */
+
+#ifndef JPC_FIX_H
+#define JPC_FIX_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_config.h"
+#include "jasper/jas_types.h"
+#include "jasper/jas_fix.h"
+#include "jasper/jas_math.h"
+
+/******************************************************************************\
+* Basic parameters of the fixed-point type.
+\******************************************************************************/
+
+/* The integral type used to represent a fixed-point number.  This
+  type must be capable of representing values from -(2^31) to 2^31-1
+  (inclusive). */
+#ifdef JAS_ENABLE_32BIT
+typedef int_least32_t jpc_fix_t;
+#else
+typedef int_fast32_t jpc_fix_t;
+#endif
+
+/* The integral type used to respresent higher-precision intermediate results.
+  This type should be capable of representing values from -(2^63) to 2^63-1
+  (inclusive). */
+typedef int_fast64_t jpc_fix_big_t;
+
+/* The number of bits used for the fractional part of a fixed-point number. */
+#define JPC_FIX_FRACBITS	13
+
+/******************************************************************************\
+* Instantiations of the generic fixed-point number macros for the
+* parameters given above.  (Too bad C does not support templates, eh?)
+* The purpose of these macros is self-evident if one examines the
+* corresponding macros in the jasper/jas_fix.h header file.
+\******************************************************************************/
+
+#define	JPC_FIX_ZERO	JAS_FIX_ZERO(jpc_fix_t, JPC_FIX_FRACBITS)
+#define	JPC_FIX_ONE		JAS_FIX_ONE(jpc_fix_t, JPC_FIX_FRACBITS)
+#define	JPC_FIX_HALF	JAS_FIX_HALF(jpc_fix_t, JPC_FIX_FRACBITS)
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_inttofix(int x)
+{
+	return JAS_INTTOFIX(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline int jpc_fixtoint(jpc_fix_t x)
+{
+	return JAS_FIXTOINT(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline double jpc_fixtodbl(jpc_fix_t x)
+{
+	return JAS_FIXTODBL(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_dbltofix(double x)
+{
+	return JAS_DBLTOFIX(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_add(jpc_fix_t x, jpc_fix_t y)
+{
+	return JAS_FIX_ADD(jpc_fix_t, JPC_FIX_FRACBITS, x, y);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_sub(jpc_fix_t x, jpc_fix_t y)
+{
+	return JAS_FIX_SUB(jpc_fix_t, JPC_FIX_FRACBITS, x, y);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_mul(jpc_fix_big_t x, jpc_fix_big_t y)
+{
+	return JAS_FIX_MUL(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_big_t jpc_fix_mulbyint(jpc_fix_big_t x, int y)
+{
+	return JAS_FIX_MUL(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_div(jpc_fix_big_t x, jpc_fix_t y)
+{
+	return JAS_FIX_DIV(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_neg(jpc_fix_t x)
+{
+	return JAS_FIX_NEG(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+//#define	jpc_fix_asl(x, n)	JAS_FIX_ASL(jpc_fix_t, JPC_FIX_FRACBITS, x, n)
+//#define	jpc_fix_asr(x, n)	JAS_FIX_ASR(jpc_fix_t, JPC_FIX_FRACBITS, x, n)
+
+#ifdef JAS_ENABLE_32BIT
+#define jpc_fix_asl jas_least32_asl
+#define jpc_fix_asr jas_least32_asr
+#else
+#define jpc_fix_asl jas_fast32_asl
+#define jpc_fix_asr jas_fast32_asr
+#endif
+
+#define jpc_fix_pluseq(x, y)	JAS_FIX_PLUSEQ(jpc_fix_t, JPC_FIX_FRACBITS, x, y)
+#define jpc_fix_minuseq(x, y)	JAS_FIX_MINUSEQ(jpc_fix_t, JPC_FIX_FRACBITS, x, y)
+#define	jpc_fix_muleq(x, y)	\
+	JAS_FIX_MULEQ(jpc_fix_t, JPC_FIX_FRACBITS, jpc_fix_big_t, x, y)
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_abs(jpc_fix_t x)
+{
+	return JAS_FIX_ABS(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline bool jpc_fix_isint(jpc_fix_t x)
+{
+	return JAS_FIX_ISINT(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline int jpc_fix_sgn(jpc_fix_t x)
+{
+	return JAS_FIX_SGN(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_round(jpc_fix_t x)
+{
+	return JAS_FIX_ROUND(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_floor(jpc_fix_t x)
+{
+	return JAS_FIX_FLOOR(jpc_fix_t, JPC_FIX_FRACBITS, x);
+}
+
+/******************************************************************************\
+* Extra macros for convenience.
+\******************************************************************************/
+
+/* Compute the sum of three fixed-point numbers. */
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t jpc_fix_add3(jpc_fix_t x, jpc_fix_t y, jpc_fix_t z)
+{
+	return jpc_fix_add(jpc_fix_add(x, y), z);
+}
+
+#endif
--- /dev/null
+++ b/jpc_flt.h
@@ -1,0 +1,78 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Floating-Point Class
+ *
+ * $Id$
+ */
+
+#ifndef JPC_FLT_H
+#define JPC_FLT_H
+
+/* The code ought to be modified so this type is not used at all. */
+/* Very few places in the code rely on floating-point arithmetic, aside
+  from conversions in printf's. */
+typedef double jpc_flt_t;
+
+#endif
--- /dev/null
+++ b/jpc_math.c
@@ -1,0 +1,129 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Math Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include "jpc_math.h"
+
+/******************************************************************************\
+* Miscellaneous Functions
+\******************************************************************************/
+
+/* Calculate the integer quantity floor(log2(x)), where x is a positive
+  integer. */
+unsigned jpc_floorlog2(uint_fast32_t x)
+{
+	int y;
+
+	/* The argument must be positive. */
+	assert(x > 0);
+
+	y = 0;
+	while (x > 1) {
+		x >>= 1;
+		++y;
+	}
+	return y;
+}
+
+/* Calculate the bit position of the first leading one in a nonnegative
+  integer. */
+/* This function is the basically the same as ceillog2(x), except that the
+  allowable range for x is slightly different. */
+int jpc_int_firstone(int x)
+{
+	int n;
+
+	/* The argument must be nonnegative. */
+	assert(x >= 0);
+
+	n = -1;
+	while (x > 0) {
+		x >>= 1;
+		++n;
+	}
+	return n;
+}
+
+int jpc_fix_firstone(jpc_fix_t x)
+{
+	int n;
+
+	/* The argument must be nonnegative. */
+	assert(x >= 0);
+
+	n = -1;
+	while (x > 0) {
+		x >>= 1;
+		++n;
+	}
+	return n;
+}
--- /dev/null
+++ b/jpc_math.h
@@ -1,0 +1,106 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef	JPC_MATH_H
+#define	JPC_MATH_H
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include "jasper/jas_config.h"
+
+#include "jpc_fix.h"
+
+/******************************************************************************\
+* Macros
+\******************************************************************************/
+
+/* Compute the floor of the quotient of two integers. */
+#define	JPC_FLOORDIV(x, y)	((x) / (y))
+
+/* Compute the ceiling of the quotient of two integers. */
+#define	JPC_CEILDIV(x, y)	(((x) + (y) - 1) / (y))
+
+/* Compute the floor of (x / 2^y). */
+#define	JPC_FLOORDIVPOW2(x, y)	((x) >> (y))
+
+/* Compute the ceiling of (x / 2^y). */
+#define	JPC_CEILDIVPOW2(x, y)	(((x) + (1 << (y)) - 1) >> (y))
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Calculate the bit position of the first leading one in a nonnegative
+  integer. */
+JAS_ATTRIBUTE_CONST
+int jpc_int_firstone(int x);
+
+JAS_ATTRIBUTE_CONST
+int jpc_fix_firstone(jpc_fix_t x);
+
+/* Calculate the integer quantity floor(log2(x)), where x is a positive
+  integer. */
+JAS_ATTRIBUTE_CONST
+unsigned jpc_floorlog2(uint_fast32_t x);
+
+#endif
--- /dev/null
+++ b/jpc_mct.c
@@ -1,0 +1,249 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Multicomponent Transform Code
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_mct.h"
+#include "jpc_fix.h"
+
+#include "jasper/jas_seq.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/* Compute the forward RCT. */
+
+void jpc_rct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
+{
+	int numrows;
+	int numcols;
+	int i;
+	int j;
+	jpc_fix_t *c0p;
+	jpc_fix_t *c1p;
+	jpc_fix_t *c2p;
+
+	numrows = jas_matrix_numrows(c0);
+	numcols = jas_matrix_numcols(c0);
+
+	/* All three matrices must have the same dimensions. */
+	assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols
+	  && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols);
+
+	for (i = 0; i < numrows; i++) {
+		c0p = jas_matrix_getref(c0, i, 0);
+		c1p = jas_matrix_getref(c1, i, 0);
+		c2p = jas_matrix_getref(c2, i, 0);
+		for (j = numcols; j > 0; --j) {
+			int r;
+			int g;
+			int b;
+			int y;
+			int u;
+			int v;
+			r = *c0p;
+			g = *c1p;
+			b = *c2p;
+			//y = (r + (g << 1) + b) >> 2;
+			y = jpc_fix_asr(r + jpc_fix_asl(g, 1) + b, 2);
+			u = b - g;
+			v = r - g;
+			*c0p++ = y;
+			*c1p++ = u;
+			*c2p++ = v;
+		}
+	}
+}
+
+/* Compute the inverse RCT. */
+
+void jpc_irct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
+{
+	int numrows;
+	int numcols;
+	int i;
+	int j;
+	jpc_fix_t *c0p;
+	jpc_fix_t *c1p;
+	jpc_fix_t *c2p;
+
+	numrows = jas_matrix_numrows(c0);
+	numcols = jas_matrix_numcols(c0);
+
+	/* All three matrices must have the same dimensions. */
+	assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols
+	  && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols);
+
+	for (i = 0; i < numrows; i++) {
+		c0p = jas_matrix_getref(c0, i, 0);
+		c1p = jas_matrix_getref(c1, i, 0);
+		c2p = jas_matrix_getref(c2, i, 0);
+		for (j = numcols; j > 0; --j) {
+			int r;
+			int g;
+			int b;
+			int y;
+			int u;
+			int v;
+			y = *c0p;
+			u = *c1p;
+			v = *c2p;
+			//g = y - ((u + v) >> 2);
+			g = y - jpc_fix_asr(u + v, 2);
+			r = v + g;
+			b = u + g;
+			*c0p++ = r;
+			*c1p++ = g;
+			*c2p++ = b;
+		}
+	}
+}
+
+void jpc_ict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
+{
+	int numrows;
+	int numcols;
+	int i;
+	int j;
+	jpc_fix_t r;
+	jpc_fix_t g;
+	jpc_fix_t b;
+	jpc_fix_t y;
+	jpc_fix_t u;
+	jpc_fix_t v;
+	jpc_fix_t *c0p;
+	jpc_fix_t *c1p;
+	jpc_fix_t *c2p;
+
+	numrows = jas_matrix_numrows(c0);
+	assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows);
+	numcols = jas_matrix_numcols(c0);
+	assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols);
+	for (i = 0; i < numrows; ++i) {
+		c0p = jas_matrix_getref(c0, i, 0);
+		c1p = jas_matrix_getref(c1, i, 0);
+		c2p = jas_matrix_getref(c2, i, 0);
+		for (j = numcols; j > 0; --j) {
+			r = *c0p;
+			g = *c1p;
+			b = *c2p;
+			y = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.299), r), jpc_fix_mul(jpc_dbltofix(0.587), g),
+			  jpc_fix_mul(jpc_dbltofix(0.114), b));
+			u = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(-0.16875), r), jpc_fix_mul(jpc_dbltofix(-0.33126), g),
+			  jpc_fix_mul(jpc_dbltofix(0.5), b));
+			v = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.5), r), jpc_fix_mul(jpc_dbltofix(-0.41869), g),
+			  jpc_fix_mul(jpc_dbltofix(-0.08131), b));
+			*c0p++ = y;
+			*c1p++ = u;
+			*c2p++ = v;
+		}
+	}
+}
+
+void jpc_iict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
+{
+	int numrows;
+	int numcols;
+	int i;
+	int j;
+	jpc_fix_t r;
+	jpc_fix_t g;
+	jpc_fix_t b;
+	jpc_fix_t y;
+	jpc_fix_t u;
+	jpc_fix_t v;
+	jpc_fix_t *c0p;
+	jpc_fix_t *c1p;
+	jpc_fix_t *c2p;
+
+	numrows = jas_matrix_numrows(c0);
+	assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows);
+	numcols = jas_matrix_numcols(c0);
+	assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols);
+	for (i = 0; i < numrows; ++i) {
+		c0p = jas_matrix_getref(c0, i, 0);
+		c1p = jas_matrix_getref(c1, i, 0);
+		c2p = jas_matrix_getref(c2, i, 0);
+		for (j = numcols; j > 0; --j) {
+			y = *c0p;
+			u = *c1p;
+			v = *c2p;
+			r = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.402), v));
+			g = jpc_fix_add3(y, jpc_fix_mul(jpc_dbltofix(-0.34413), u),
+			  jpc_fix_mul(jpc_dbltofix(-0.71414), v));
+			b = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.772), u));
+			*c0p++ = r;
+			*c1p++ = g;
+			*c2p++ = b;
+		}
+	}
+}
--- /dev/null
+++ b/jpc_mct.h
@@ -1,0 +1,109 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Multicomponent Transform Code
+ *
+ * $Id$
+ */
+
+#ifndef JPC_MCT_H
+#define JPC_MCT_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_fix.h"
+
+#include "jasper/jas_seq.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/*
+ * Multicomponent transform IDs.
+ */
+
+#define JPC_MCT_NONE	0
+#define JPC_MCT_ICT		1
+#define JPC_MCT_RCT		2
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Calculate the forward RCT. */
+void jpc_rct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2);
+
+/* Calculate the inverse RCT. */
+void jpc_irct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2);
+
+/* Calculate the forward ICT. */
+void jpc_ict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2);
+
+/* Calculate the inverse ICT. */
+void jpc_iict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2);
+
+#endif
--- /dev/null
+++ b/jpc_mqcod.c
@@ -1,0 +1,177 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Coder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_mqcod.h"
+
+/******************************************************************************\
+* Data.
+\******************************************************************************/
+
+/* MQ coder per-state information. */
+
+const jpc_mqstate_t jpc_mqstates[47 * 2] = {
+	{0x5601, 0, &jpc_mqstates[ 2], &jpc_mqstates[ 3]},
+	{0x5601, 1, &jpc_mqstates[ 3], &jpc_mqstates[ 2]},
+	{0x3401, 0, &jpc_mqstates[ 4], &jpc_mqstates[12]},
+	{0x3401, 1, &jpc_mqstates[ 5], &jpc_mqstates[13]},
+	{0x1801, 0, &jpc_mqstates[ 6], &jpc_mqstates[18]},
+	{0x1801, 1, &jpc_mqstates[ 7], &jpc_mqstates[19]},
+	{0x0ac1, 0, &jpc_mqstates[ 8], &jpc_mqstates[24]},
+	{0x0ac1, 1, &jpc_mqstates[ 9], &jpc_mqstates[25]},
+	{0x0521, 0, &jpc_mqstates[10], &jpc_mqstates[58]},
+	{0x0521, 1, &jpc_mqstates[11], &jpc_mqstates[59]},
+	{0x0221, 0, &jpc_mqstates[76], &jpc_mqstates[66]},
+	{0x0221, 1, &jpc_mqstates[77], &jpc_mqstates[67]},
+	{0x5601, 0, &jpc_mqstates[14], &jpc_mqstates[13]},
+	{0x5601, 1, &jpc_mqstates[15], &jpc_mqstates[12]},
+	{0x5401, 0, &jpc_mqstates[16], &jpc_mqstates[28]},
+	{0x5401, 1, &jpc_mqstates[17], &jpc_mqstates[29]},
+	{0x4801, 0, &jpc_mqstates[18], &jpc_mqstates[28]},
+	{0x4801, 1, &jpc_mqstates[19], &jpc_mqstates[29]},
+	{0x3801, 0, &jpc_mqstates[20], &jpc_mqstates[28]},
+	{0x3801, 1, &jpc_mqstates[21], &jpc_mqstates[29]},
+	{0x3001, 0, &jpc_mqstates[22], &jpc_mqstates[34]},
+	{0x3001, 1, &jpc_mqstates[23], &jpc_mqstates[35]},
+	{0x2401, 0, &jpc_mqstates[24], &jpc_mqstates[36]},
+	{0x2401, 1, &jpc_mqstates[25], &jpc_mqstates[37]},
+	{0x1c01, 0, &jpc_mqstates[26], &jpc_mqstates[40]},
+	{0x1c01, 1, &jpc_mqstates[27], &jpc_mqstates[41]},
+	{0x1601, 0, &jpc_mqstates[58], &jpc_mqstates[42]},
+	{0x1601, 1, &jpc_mqstates[59], &jpc_mqstates[43]},
+	{0x5601, 0, &jpc_mqstates[30], &jpc_mqstates[29]},
+	{0x5601, 1, &jpc_mqstates[31], &jpc_mqstates[28]},
+	{0x5401, 0, &jpc_mqstates[32], &jpc_mqstates[28]},
+	{0x5401, 1, &jpc_mqstates[33], &jpc_mqstates[29]},
+	{0x5101, 0, &jpc_mqstates[34], &jpc_mqstates[30]},
+	{0x5101, 1, &jpc_mqstates[35], &jpc_mqstates[31]},
+	{0x4801, 0, &jpc_mqstates[36], &jpc_mqstates[32]},
+	{0x4801, 1, &jpc_mqstates[37], &jpc_mqstates[33]},
+	{0x3801, 0, &jpc_mqstates[38], &jpc_mqstates[34]},
+	{0x3801, 1, &jpc_mqstates[39], &jpc_mqstates[35]},
+	{0x3401, 0, &jpc_mqstates[40], &jpc_mqstates[36]},
+	{0x3401, 1, &jpc_mqstates[41], &jpc_mqstates[37]},
+	{0x3001, 0, &jpc_mqstates[42], &jpc_mqstates[38]},
+	{0x3001, 1, &jpc_mqstates[43], &jpc_mqstates[39]},
+	{0x2801, 0, &jpc_mqstates[44], &jpc_mqstates[38]},
+	{0x2801, 1, &jpc_mqstates[45], &jpc_mqstates[39]},
+	{0x2401, 0, &jpc_mqstates[46], &jpc_mqstates[40]},
+	{0x2401, 1, &jpc_mqstates[47], &jpc_mqstates[41]},
+	{0x2201, 0, &jpc_mqstates[48], &jpc_mqstates[42]},
+	{0x2201, 1, &jpc_mqstates[49], &jpc_mqstates[43]},
+	{0x1c01, 0, &jpc_mqstates[50], &jpc_mqstates[44]},
+	{0x1c01, 1, &jpc_mqstates[51], &jpc_mqstates[45]},
+	{0x1801, 0, &jpc_mqstates[52], &jpc_mqstates[46]},
+	{0x1801, 1, &jpc_mqstates[53], &jpc_mqstates[47]},
+	{0x1601, 0, &jpc_mqstates[54], &jpc_mqstates[48]},
+	{0x1601, 1, &jpc_mqstates[55], &jpc_mqstates[49]},
+	{0x1401, 0, &jpc_mqstates[56], &jpc_mqstates[50]},
+	{0x1401, 1, &jpc_mqstates[57], &jpc_mqstates[51]},
+	{0x1201, 0, &jpc_mqstates[58], &jpc_mqstates[52]},
+	{0x1201, 1, &jpc_mqstates[59], &jpc_mqstates[53]},
+	{0x1101, 0, &jpc_mqstates[60], &jpc_mqstates[54]},
+	{0x1101, 1, &jpc_mqstates[61], &jpc_mqstates[55]},
+	{0x0ac1, 0, &jpc_mqstates[62], &jpc_mqstates[56]},
+	{0x0ac1, 1, &jpc_mqstates[63], &jpc_mqstates[57]},
+	{0x09c1, 0, &jpc_mqstates[64], &jpc_mqstates[58]},
+	{0x09c1, 1, &jpc_mqstates[65], &jpc_mqstates[59]},
+	{0x08a1, 0, &jpc_mqstates[66], &jpc_mqstates[60]},
+	{0x08a1, 1, &jpc_mqstates[67], &jpc_mqstates[61]},
+	{0x0521, 0, &jpc_mqstates[68], &jpc_mqstates[62]},
+	{0x0521, 1, &jpc_mqstates[69], &jpc_mqstates[63]},
+	{0x0441, 0, &jpc_mqstates[70], &jpc_mqstates[64]},
+	{0x0441, 1, &jpc_mqstates[71], &jpc_mqstates[65]},
+	{0x02a1, 0, &jpc_mqstates[72], &jpc_mqstates[66]},
+	{0x02a1, 1, &jpc_mqstates[73], &jpc_mqstates[67]},
+	{0x0221, 0, &jpc_mqstates[74], &jpc_mqstates[68]},
+	{0x0221, 1, &jpc_mqstates[75], &jpc_mqstates[69]},
+	{0x0141, 0, &jpc_mqstates[76], &jpc_mqstates[70]},
+	{0x0141, 1, &jpc_mqstates[77], &jpc_mqstates[71]},
+	{0x0111, 0, &jpc_mqstates[78], &jpc_mqstates[72]},
+	{0x0111, 1, &jpc_mqstates[79], &jpc_mqstates[73]},
+	{0x0085, 0, &jpc_mqstates[80], &jpc_mqstates[74]},
+	{0x0085, 1, &jpc_mqstates[81], &jpc_mqstates[75]},
+	{0x0049, 0, &jpc_mqstates[82], &jpc_mqstates[76]},
+	{0x0049, 1, &jpc_mqstates[83], &jpc_mqstates[77]},
+	{0x0025, 0, &jpc_mqstates[84], &jpc_mqstates[78]},
+	{0x0025, 1, &jpc_mqstates[85], &jpc_mqstates[79]},
+	{0x0015, 0, &jpc_mqstates[86], &jpc_mqstates[80]},
+	{0x0015, 1, &jpc_mqstates[87], &jpc_mqstates[81]},
+	{0x0009, 0, &jpc_mqstates[88], &jpc_mqstates[82]},
+	{0x0009, 1, &jpc_mqstates[89], &jpc_mqstates[83]},
+	{0x0005, 0, &jpc_mqstates[90], &jpc_mqstates[84]},
+	{0x0005, 1, &jpc_mqstates[91], &jpc_mqstates[85]},
+	{0x0001, 0, &jpc_mqstates[90], &jpc_mqstates[86]},
+	{0x0001, 1, &jpc_mqstates[91], &jpc_mqstates[87]},
+	{0x5601, 0, &jpc_mqstates[92], &jpc_mqstates[92]},
+	{0x5601, 1, &jpc_mqstates[93], &jpc_mqstates[93]},
+};
--- /dev/null
+++ b/jpc_mqcod.h
@@ -1,0 +1,124 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Coder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_MQCOD_H
+#define JPC_MQCOD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/*
+ * MQ coder context information.
+ */
+
+typedef struct {
+
+	/* The most probable symbol (MPS). */
+	bool mps;
+
+	/* The state index. */
+	int_least8_t ind;
+
+} jpc_mqctx_t;
+
+/*
+ * MQ coder state table entry.
+ */
+
+typedef struct jpc_mqstate_s {
+
+	/* The Qe value. */
+	uint_least16_t qeval;
+
+	/* The MPS. */
+	bool mps;
+
+	/* The NMPS state. */
+	const struct jpc_mqstate_s *nmps;
+
+	/* The NLPS state. */
+	const struct jpc_mqstate_s *nlps;
+
+} jpc_mqstate_t;
+
+/******************************************************************************\
+* Data.
+\******************************************************************************/
+
+/* The state table for the MQ coder. */
+extern const jpc_mqstate_t jpc_mqstates[];
+
+#endif
--- /dev/null
+++ b/jpc_mqdec.c
@@ -1,0 +1,298 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Decoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_mqdec.h"
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Local macros.
+\******************************************************************************/
+
+#ifndef NDEBUG
+#define	MQDEC_CALL(n, x) \
+	((jas_getdbglevel() >= (n)) ? ((void)(x)) : ((void)0))
+#else
+#define	MQDEC_CALL(n, x)
+#endif
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static void jpc_mqdec_bytein(jpc_mqdec_t *mqdec);
+
+/******************************************************************************\
+* Code for creation and destruction of a MQ decoder.
+\******************************************************************************/
+
+/* Create a MQ decoder. */
+jpc_mqdec_t *jpc_mqdec_create(unsigned maxctxs, jas_stream_t *in)
+{
+	jpc_mqdec_t *mqdec;
+
+	/* There must be at least one context. */
+	assert(maxctxs > 0);
+
+	/* Allocate memory for the MQ decoder. */
+	if (!(mqdec = jas_malloc(sizeof(jpc_mqdec_t)))) {
+		goto error;
+	}
+	mqdec->in = in;
+	mqdec->maxctxs = maxctxs;
+	/* Allocate memory for the per-context state information. */
+	if (!(mqdec->ctxs = jas_alloc2(mqdec->maxctxs, sizeof(jpc_mqstate_t *)))) {
+		goto error;
+	}
+	/* Set the current context to the first context. */
+	mqdec->curctx = mqdec->ctxs;
+
+	/* If an input stream has been associated with the MQ decoder,
+	  initialize the decoder state from the stream. */
+	if (mqdec->in) {
+		jpc_mqdec_init(mqdec);
+	}
+	/* Initialize the per-context state information. */
+	jpc_mqdec_setctxs(mqdec, 0, 0);
+
+	return mqdec;
+
+error:
+	/* Oops...  Something has gone wrong. */
+	if (mqdec) {
+		jpc_mqdec_destroy(mqdec);
+	}
+	return 0;
+}
+
+/* Destroy a MQ decoder. */
+void jpc_mqdec_destroy(jpc_mqdec_t *mqdec)
+{
+	jas_free(mqdec->ctxs);
+	jas_free(mqdec);
+}
+
+/******************************************************************************\
+* Code for initialization of a MQ decoder.
+\******************************************************************************/
+
+/* Initialize the state of a MQ decoder. */
+
+void jpc_mqdec_init(jpc_mqdec_t *mqdec)
+{
+	int c;
+
+	mqdec->eof = false;
+	mqdec->creg = 0;
+	/* Get the next byte from the input stream. */
+	if ((c = jas_stream_getc(mqdec->in)) == EOF) {
+		/* We have encountered an I/O error or EOF. */
+		c = 0xff;
+		mqdec->eof = true;
+	}
+	mqdec->inbuffer = c;
+	mqdec->creg += mqdec->inbuffer << 16;
+	jpc_mqdec_bytein(mqdec);
+	mqdec->creg <<= 7;
+	mqdec->ctreg -= 7;
+	mqdec->areg = 0x8000;
+}
+
+/* Set the input stream for a MQ decoder. */
+
+void jpc_mqdec_setinput(jpc_mqdec_t *mqdec, jas_stream_t *in)
+{
+	mqdec->in = in;
+}
+
+/* Initialize one or more contexts. */
+
+void jpc_mqdec_setctxs(const jpc_mqdec_t *mqdec, unsigned numctxs, const jpc_mqctx_t *ctxs)
+{
+	const jpc_mqstate_t **ctx;
+
+	ctx = mqdec->ctxs;
+	unsigned n = JAS_MIN(mqdec->maxctxs, numctxs);
+	while (n-- > 0) {
+		*ctx = &jpc_mqstates[2 * ctxs->ind + ctxs->mps];
+		++ctx;
+		++ctxs;
+	}
+	n = mqdec->maxctxs - numctxs;
+	while (n-- > 0) {
+		*ctx = &jpc_mqstates[0];
+		++ctx;
+	}
+}
+
+/******************************************************************************\
+* Code for decoding a bit.
+\******************************************************************************/
+
+/* Decode a bit. */
+
+bool jpc_mqdec_getbit_func(register jpc_mqdec_t *mqdec)
+{
+	bool bit;
+	JAS_DBGLOG(100, ("jpc_mqdec_getbit_func(%p)\n", mqdec));
+	MQDEC_CALL(100, jpc_mqdec_dump(mqdec, stderr));
+	bit = jpc_mqdec_getbit_macro(mqdec);
+	MQDEC_CALL(100, jpc_mqdec_dump(mqdec, stderr));
+	JAS_DBGLOG(100, ("ctx = %d, decoded %d\n", mqdec->curctx -
+	  mqdec->ctxs, bit));
+	return bit;
+}
+
+static void jpc_mqdec_renormd(jpc_mqdec_t *mqdec)
+{
+	do {
+		if (!mqdec->ctreg)
+			jpc_mqdec_bytein(mqdec);
+
+		mqdec->areg <<= 1;
+		mqdec->creg <<= 1;
+		--mqdec->ctreg;
+	} while (!(mqdec->areg & 0x8000));
+}
+
+/* Apply MPS_EXCHANGE algorithm (with RENORMD). */
+bool jpc_mqdec_mpsexchrenormd(register jpc_mqdec_t *mqdec)
+{
+	register const jpc_mqstate_t *state = *mqdec->curctx;
+	bool ret = jpc_mqdec_mpsexchange(mqdec->areg, state->qeval, mqdec->curctx);
+	jpc_mqdec_renormd(mqdec);
+	return ret;
+}
+
+/* Apply LPS_EXCHANGE algorithm (with RENORMD). */
+bool jpc_mqdec_lpsexchrenormd(register jpc_mqdec_t *mqdec)
+{
+	register const jpc_mqstate_t *state = *mqdec->curctx;
+	bool ret = jpc_mqdec_lpsexchange(&mqdec->areg, state->qeval, mqdec->curctx);
+	jpc_mqdec_renormd(mqdec);
+	return ret;
+}
+
+/******************************************************************************\
+* Support code.
+\******************************************************************************/
+
+/* Apply the BYTEIN algorithm. */
+static void jpc_mqdec_bytein(jpc_mqdec_t *mqdec)
+{
+	int c;
+	unsigned char prevbuf;
+
+	if (!mqdec->eof) {
+		if ((c = jas_stream_getc(mqdec->in)) == EOF) {
+			mqdec->eof = true;
+			c = 0xff;
+		}
+		prevbuf = mqdec->inbuffer;
+		mqdec->inbuffer = c;
+		if (prevbuf == 0xff) {
+			if (c > 0x8f) {
+				mqdec->creg += 0xff00;
+				mqdec->ctreg = 8;
+			} else {
+				mqdec->creg += c << 9;
+				mqdec->ctreg = 7;
+			}
+		} else {
+			mqdec->creg += c << 8;
+			mqdec->ctreg = 8;
+		}
+	} else {
+		mqdec->creg += 0xff00;
+		mqdec->ctreg = 8;
+	}
+}
+
+/******************************************************************************\
+* Code for debugging.
+\******************************************************************************/
+
+/* Dump a MQ decoder to a stream for debugging. */
+
+void jpc_mqdec_dump(const jpc_mqdec_t *mqdec, FILE *out)
+{
+	fprintf(out, "MQDEC A = %08lx, C = %08lx, CT=%08lx, ",
+	  (unsigned long) mqdec->areg, (unsigned long) mqdec->creg,
+	  (unsigned long) mqdec->ctreg);
+	fprintf(out, "CTX = %" PRIdPTR ", ", mqdec->curctx - mqdec->ctxs);
+	fprintf(out, "IND %" PRIdPTR ", MPS %d, QEVAL %"PRIxLEAST16"\n", *mqdec->curctx -
+	  jpc_mqstates, (*mqdec->curctx)->mps, (*mqdec->curctx)->qeval);
+}
--- /dev/null
+++ b/jpc_mqdec.h
@@ -1,0 +1,241 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Decoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_MQDEC_H
+#define JPC_MQDEC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+
+#include "jpc_mqcod.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* MQ arithmetic decoder. */
+
+typedef struct {
+
+	/* The C register. */
+	uint_least32_t creg;
+
+	/* The A register. */
+	uint_least32_t areg;
+
+	/* The CT register. */
+	uint_least32_t ctreg;
+
+	/* The current context. */
+	const jpc_mqstate_t **curctx;
+
+	/* The per-context information. */
+	const jpc_mqstate_t **ctxs;
+
+	/* The maximum number of contexts. */
+	unsigned maxctxs;
+
+	/* The stream from which to read data. */
+	jas_stream_t *in;
+
+	/* The last character read. */
+	jas_uchar inbuffer;
+
+	/* The EOF indicator. */
+	bool eof;
+
+} jpc_mqdec_t;
+
+/******************************************************************************\
+* Functions/macros for construction and destruction.
+\******************************************************************************/
+
+/* Create a MQ decoder. */
+jpc_mqdec_t *jpc_mqdec_create(unsigned maxctxs, jas_stream_t *in);
+
+/* Destroy a MQ decoder. */
+void jpc_mqdec_destroy(jpc_mqdec_t *dec);
+
+/******************************************************************************\
+* Functions/macros for initialization.
+\******************************************************************************/
+
+/* Set the input stream associated with a MQ decoder. */
+void jpc_mqdec_setinput(jpc_mqdec_t *dec, jas_stream_t *in);
+
+/* Initialize a MQ decoder. */
+void jpc_mqdec_init(jpc_mqdec_t *dec);
+
+/******************************************************************************\
+* Functions/macros for manipulating contexts.
+\******************************************************************************/
+
+/* Set the current context for a MQ decoder. */
+static inline void jpc_mqdec_setcurctx(jpc_mqdec_t *dec, unsigned ctxno)
+{
+	dec->curctx = &dec->ctxs[ctxno];
+}
+
+/* Set the state information for all contexts of a MQ decoder. */
+void jpc_mqdec_setctxs(const jpc_mqdec_t *dec, unsigned numctxs, const jpc_mqctx_t *ctxs);
+
+/******************************************************************************\
+* Functions/macros for decoding bits.
+\******************************************************************************/
+
+/* Decode a symbol. */
+#ifdef NDEBUG
+#define	jpc_mqdec_getbit(dec) \
+	jpc_mqdec_getbit_macro(dec)
+#else
+#define	jpc_mqdec_getbit(dec) \
+	jpc_mqdec_getbit_func(dec)
+#endif
+
+/* Decode a symbol (assuming an unskewed probability distribution). */
+#ifdef NDEBUG
+#define	jpc_mqdec_getbitnoskew(dec) \
+	jpc_mqdec_getbit_macro(dec)
+#else
+#define	jpc_mqdec_getbitnoskew(dec) \
+	jpc_mqdec_getbit_func(dec)
+#endif
+
+/******************************************************************************\
+* Functions/macros for debugging.
+\******************************************************************************/
+
+/* Dump the MQ decoder state for debugging. */
+void jpc_mqdec_dump(const jpc_mqdec_t *dec, FILE *out);
+
+/******************************************************************************\
+* EVERYTHING BELOW THIS POINT IS IMPLEMENTATION SPECIFIC AND NOT PART OF THE
+* APPLICATION INTERFACE.  DO NOT RELY ON ANY OF THE INTERNAL FUNCTIONS/MACROS
+* GIVEN BELOW.
+\******************************************************************************/
+
+bool jpc_mqdec_mpsexchrenormd(jpc_mqdec_t *dec);
+bool jpc_mqdec_lpsexchrenormd(jpc_mqdec_t *dec);
+
+JAS_FORCE_INLINE
+static bool jpc_mqdec_getbit_macro(jpc_mqdec_t *dec)
+{
+	const jpc_mqstate_t *const state = *dec->curctx;
+
+	dec->areg -= state->qeval;
+
+	if (dec->creg >= (uint_least32_t)state->qeval << 16) {
+		dec->creg -= (uint_least32_t)state->qeval << 16;
+		return dec->areg & 0x8000
+			? state->mps
+			: jpc_mqdec_mpsexchrenormd(dec);
+	} else {
+		return jpc_mqdec_lpsexchrenormd(dec);
+	}
+}
+
+JAS_FORCE_INLINE
+static bool jpc_mqdec_mpsexchange(uint_least32_t areg, uint_least32_t delta, const jpc_mqstate_t **curctx)
+{
+	if (areg < delta) {
+		const jpc_mqstate_t *state = *curctx;
+		/* LPS decoded. */
+		*curctx = state->nlps;
+		return !state->mps;
+	} else {
+		const jpc_mqstate_t *state = *curctx;
+		/* MPS decoded. */
+		*curctx = state->nmps;
+		return state->mps;
+	}
+}
+
+JAS_FORCE_INLINE
+static bool jpc_mqdec_lpsexchange(uint_least32_t *areg_p, uint_least32_t delta, const jpc_mqstate_t **curctx)
+{
+	if (*areg_p >= delta) {
+		const jpc_mqstate_t *state = *curctx;
+		*areg_p = delta;
+		*curctx = state->nlps;
+		return !state->mps;
+	} else {
+		const jpc_mqstate_t *state = *curctx;
+		*areg_p = delta;
+		*curctx = state->nmps;
+		return state->mps;
+	}
+}
+
+bool jpc_mqdec_getbit_func(jpc_mqdec_t *dec);
+
+#endif
--- /dev/null
+++ b/jpc_qmfb.c
@@ -1,0 +1,2207 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Quadrature Mirror-Image Filter Bank (QMFB) Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#undef WT_LENONE /* This is not needed due to normalization. */
+#define WT_DOSCALE
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_qmfb.h"
+#include "jpc_math.h"
+
+#include "jasper/jas_malloc.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define QMFB_SPLITBUFSIZE	4096
+#define	QMFB_JOINBUFSIZE	4096
+
+static int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+  int stride);
+static int jpc_ft_synthesize(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+  int stride);
+
+static int jpc_ns_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+  int stride);
+static int jpc_ns_synthesize(jpc_fix_t *a, int xstart, int ystart, int width,
+  int height, int stride);
+
+static void jpc_ft_fwdlift_row(jpc_fix_t *a, unsigned numcols, bool parity);
+static void jpc_ft_fwdlift_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride,
+  bool parity);
+static void jpc_ft_fwdlift_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols,
+  unsigned stride, bool parity);
+
+static void jpc_ft_invlift_row(jpc_fix_t *a, unsigned numcols, bool parity);
+static void jpc_ft_invlift_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride,
+  bool parity);
+static void jpc_ft_invlift_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols,
+  unsigned stride, bool parity);
+
+static void jpc_ns_fwdlift_row(jpc_fix_t *a, unsigned numcols, bool parity);
+static void jpc_ns_fwdlift_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride, bool parity);
+static void jpc_ns_fwdlift_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols, unsigned stride,
+  bool parity);
+static void jpc_ns_invlift_row(jpc_fix_t *a, unsigned numcols, bool parity);
+static void jpc_ns_invlift_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride, bool parity);
+static void jpc_ns_invlift_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols, unsigned stride,
+  bool parity);
+
+static void jpc_qmfb_split_row(jpc_fix_t *a, unsigned numrows, bool parity);
+static void jpc_qmfb_split_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride, bool parity);
+static void jpc_qmfb_split_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols, unsigned stride,
+  bool parity);
+
+static void jpc_qmfb_join_row(jpc_fix_t *a, unsigned numcols, bool parity);
+static void jpc_qmfb_join_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride, bool parity);
+static void jpc_qmfb_join_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols, unsigned stride,
+  bool parity);
+
+static const double jpc_ft_lpenergywts[32] = {
+	1.2247448713915889,
+	1.6583123951776999,
+	2.3184046238739260,
+	3.2691742076555053,
+	4.6199296531440819,
+	6.5323713152269596,
+	9.2377452606141937,
+	13.0639951297449581,
+	18.4752262333915667,
+	26.1278968190610392,
+	36.9504194305524791,
+	52.2557819580462777,
+	73.9008347315741645,
+	104.5115624560829133,
+	147.8016689469569656,
+	209.0231247296646018,
+	295.6033378293900000,
+	418.0462494347059419,
+	591.2066756503630813,
+	836.0924988714708661,
+	/* approximations */
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661,
+	836.0924988714708661
+};
+
+static const double jpc_ft_hpenergywts[32] = {
+	0.8477912478906585,
+	0.9601432184835760,
+	1.2593401049756179,
+	1.7444107171191079,
+	2.4538713036750726,
+	3.4656517695088755,
+	4.8995276398597856,
+	6.9283970402160842,
+	9.7980274940131444,
+	13.8564306871112652,
+	19.5959265076535587,
+	27.7128159494245487,
+	39.1918369552045860,
+	55.4256262207444053,
+	78.3836719028959124,
+	110.8512517317256822,
+	156.7673435548526868,
+	221.7025033739244293,
+	313.5346870787551552,
+	443.4050067351659550,
+	/* approximations */
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550,
+	443.4050067351659550
+};
+
+static const double jpc_ns_lpenergywts[32] = {
+	1.4021081679297411,
+	2.0303718560817923,
+	2.9011625562785555,
+	4.1152851751758002,
+	5.8245108637728071,
+	8.2387599345725171,
+	11.6519546479210838,
+	16.4785606470644375,
+	23.3042776444606794,
+	32.9572515613740435,
+	46.6086013487782793,
+	65.9145194076860861,
+	93.2172084551803977,
+	131.8290408510004283,
+	186.4344176300625691,
+	263.6580819564562148,
+	372.8688353500955373,
+	527.3161639447193920,
+	745.7376707114038936,
+	1054.6323278917823245,
+	/* approximations follow */
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245,
+	1054.6323278917823245
+};
+
+static const double jpc_ns_hpenergywts[32] = {
+	1.4425227650161456,
+	1.9669426082455688,
+	2.8839248082788891,
+	4.1475208393432981,
+	5.8946497530677817,
+	8.3471789178590949,
+	11.8086046551047463,
+	16.7012780415647804,
+	23.6196657032246620,
+	33.4034255108592362,
+	47.2396388881632632,
+	66.8069597416714061,
+	94.4793162154500692,
+	133.6139330736999113,
+	188.9586372358249378,
+	267.2278678461869390,
+	377.9172750722391356,
+	534.4557359047058753,
+	755.8345502191498326,
+	1068.9114718353569060,
+	/* approximations follow */
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060,
+	1068.9114718353569060
+};
+
+const jpc_qmfb2d_t jpc_ft_qmfb2d = {
+	jpc_ft_analyze,
+	jpc_ft_synthesize,
+	jpc_ft_lpenergywts,
+	jpc_ft_hpenergywts
+};
+
+const jpc_qmfb2d_t jpc_ns_qmfb2d = {
+	jpc_ns_analyze,
+	jpc_ns_synthesize,
+	jpc_ns_lpenergywts,
+	jpc_ns_hpenergywts
+};
+
+/******************************************************************************\
+* generic
+\******************************************************************************/
+
+static void jpc_qmfb_split_row(jpc_fix_t *a, unsigned numcols, bool parity)
+{
+	jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
+	jpc_fix_t *buf = splitbuf;
+	register jpc_fix_t *srcptr;
+	register jpc_fix_t *dstptr;
+
+	/* Get a buffer. */
+	const size_t bufsize = JPC_CEILDIVPOW2(numcols, 1);
+	if (bufsize > QMFB_SPLITBUFSIZE) {
+		if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
+			/* We have no choice but to commit suicide in this case. */
+			abort();
+		}
+	}
+
+	if (numcols >= 2) {
+		const unsigned hstartcol = (numcols + !parity) >> 1;
+		// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numcols - hstartcol);
+		const unsigned m = numcols - hstartcol;
+
+		/* Save the samples destined for the highpass channel. */
+		dstptr = buf;
+		srcptr = &a[!parity];
+		for (unsigned n = m; n > 0; --n) {
+			*dstptr = *srcptr;
+			++dstptr;
+			srcptr += 2;
+		}
+		/* Copy the appropriate samples into the lowpass channel. */
+		dstptr = &a[!parity];
+		srcptr = &a[2 - parity];
+		for (unsigned n = numcols - m - (!parity); n > 0; --n) {
+			*dstptr = *srcptr;
+			++dstptr;
+			srcptr += 2;
+		}
+		/* Copy the saved samples into the highpass channel. */
+		dstptr = &a[hstartcol];
+		srcptr = buf;
+		for (unsigned n = m; n > 0; --n) {
+			*dstptr = *srcptr;
+			++dstptr;
+			++srcptr;
+		}
+	}
+
+	/* If the split buffer was allocated on the heap, free this memory. */
+	if (buf != splitbuf) {
+		jas_free(buf);
+	}
+
+}
+
+static void jpc_qmfb_split_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride,
+  bool parity)
+{
+
+	jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
+	jpc_fix_t *buf = splitbuf;
+	jpc_fix_t *srcptr;
+	jpc_fix_t *dstptr;
+	register jpc_fix_t *srcptr2;
+	register jpc_fix_t *dstptr2;
+
+	/* Get a buffer. */
+	const size_t bufsize = JPC_CEILDIVPOW2(numrows, 1);
+	if (bufsize > QMFB_SPLITBUFSIZE) {
+		if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE,
+		  sizeof(jpc_fix_t)))) {
+			/* We have no choice but to commit suicide in this case. */
+			abort();
+		}
+	}
+
+	if (numrows >= 2) {
+		const unsigned hstartrow = (numrows + !parity) >> 1;
+		// ORIGINAL (WRONG): m = (parity) ? hstartrow : (numrows - hstartrow);
+		const unsigned m = numrows - hstartrow;
+
+		/* Save the samples destined for the highpass channel. */
+		dstptr = buf;
+		srcptr = &a[(!parity) * stride];
+		for (unsigned n = m; n > 0; --n) {
+			dstptr2 = dstptr;
+			srcptr2 = srcptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				*dstptr2 = *srcptr2;
+				++dstptr2;
+				++srcptr2;
+			}
+			dstptr += JPC_QMFB_COLGRPSIZE;
+			srcptr += stride << 1;
+		}
+		/* Copy the appropriate samples into the lowpass channel. */
+		dstptr = &a[(!parity) * stride];
+		srcptr = &a[(2 - parity) * stride];
+		for (unsigned n = numrows - m - (!parity); n > 0; --n) {
+			dstptr2 = dstptr;
+			srcptr2 = srcptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				*dstptr2 = *srcptr2;
+				++dstptr2;
+				++srcptr2;
+			}
+			dstptr += stride;
+			srcptr += stride << 1;
+		}
+		/* Copy the saved samples into the highpass channel. */
+		dstptr = &a[hstartrow * stride];
+		srcptr = buf;
+		for (unsigned n = m; n > 0; --n) {
+			dstptr2 = dstptr;
+			srcptr2 = srcptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				*dstptr2 = *srcptr2;
+				++dstptr2;
+				++srcptr2;
+			}
+			dstptr += stride;
+			srcptr += JPC_QMFB_COLGRPSIZE;
+		}
+	}
+
+	/* If the split buffer was allocated on the heap, free this memory. */
+	if (buf != splitbuf) {
+		jas_free(buf);
+	}
+
+}
+
+static void jpc_qmfb_split_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols,
+  unsigned stride, bool parity)
+{
+
+	jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
+	jpc_fix_t *buf = splitbuf;
+	jpc_fix_t *srcptr;
+	jpc_fix_t *dstptr;
+	register jpc_fix_t *srcptr2;
+	register jpc_fix_t *dstptr2;
+
+	/* Get a buffer. */
+	const size_t bufsize = JPC_CEILDIVPOW2(numrows, 1);
+	if (bufsize > QMFB_SPLITBUFSIZE) {
+		if (!(buf = jas_alloc3(bufsize, numcols, sizeof(jpc_fix_t)))) {
+			/* We have no choice but to commit suicide in this case. */
+			abort();
+		}
+	}
+
+	if (numrows >= 2) {
+		const unsigned hstartcol = (numrows + !parity) >> 1;
+		// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol);
+		const unsigned m = numrows - hstartcol;
+
+		/* Save the samples destined for the highpass channel. */
+		dstptr = buf;
+		srcptr = &a[(!parity) * stride];
+		for (unsigned n = m; n > 0; --n) {
+			dstptr2 = dstptr;
+			srcptr2 = srcptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				*dstptr2 = *srcptr2;
+				++dstptr2;
+				++srcptr2;
+			}
+			dstptr += numcols;
+			srcptr += stride << 1;
+		}
+		/* Copy the appropriate samples into the lowpass channel. */
+		dstptr = &a[(!parity) * stride];
+		srcptr = &a[(2 - parity) * stride];
+		for (unsigned n = numrows - m - (!parity); n > 0; --n) {
+			dstptr2 = dstptr;
+			srcptr2 = srcptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				*dstptr2 = *srcptr2;
+				++dstptr2;
+				++srcptr2;
+			}
+			dstptr += stride;
+			srcptr += stride << 1;
+		}
+		/* Copy the saved samples into the highpass channel. */
+		dstptr = &a[hstartcol * stride];
+		srcptr = buf;
+		for (unsigned n = m; n > 0; --n) {
+			dstptr2 = dstptr;
+			srcptr2 = srcptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				*dstptr2 = *srcptr2;
+				++dstptr2;
+				++srcptr2;
+			}
+			dstptr += stride;
+			srcptr += numcols;
+		}
+	}
+
+	/* If the split buffer was allocated on the heap, free this memory. */
+	if (buf != splitbuf) {
+		jas_free(buf);
+	}
+
+}
+
+static void jpc_qmfb_join_row(jpc_fix_t *a, unsigned numcols, bool parity)
+{
+
+	jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
+	jpc_fix_t *buf = joinbuf;
+	register jpc_fix_t *srcptr;
+	register jpc_fix_t *dstptr;
+
+	/* Allocate memory for the join buffer from the heap. */
+	const size_t bufsize = JPC_CEILDIVPOW2(numcols, 1);
+	if (bufsize > QMFB_JOINBUFSIZE) {
+		if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
+			/* We have no choice but to commit suicide. */
+			abort();
+		}
+	}
+
+	const unsigned hstartcol = (numcols + !parity) >> 1;
+
+	/* Save the samples from the lowpass channel. */
+	srcptr = &a[0];
+	dstptr = buf;
+	for (unsigned n = hstartcol; n > 0; --n) {
+		*dstptr = *srcptr;
+		++srcptr;
+		++dstptr;
+	}
+	/* Copy the samples from the highpass channel into place. */
+	srcptr = &a[hstartcol];
+	dstptr = &a[!parity];
+	for (unsigned n = numcols - hstartcol; n > 0; --n) {
+		*dstptr = *srcptr;
+		dstptr += 2;
+		++srcptr;
+	}
+	/* Copy the samples from the lowpass channel into place. */
+	srcptr = buf;
+	dstptr = &a[parity];
+	for (unsigned n = hstartcol; n > 0; --n) {
+		*dstptr = *srcptr;
+		dstptr += 2;
+		++srcptr;
+	}
+
+	/* If the join buffer was allocated on the heap, free this memory. */
+	if (buf != joinbuf) {
+		jas_free(buf);
+	}
+
+}
+
+static void jpc_qmfb_join_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride,
+  bool parity)
+{
+
+	jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
+	jpc_fix_t *buf = joinbuf;
+	jpc_fix_t *srcptr;
+	jpc_fix_t *dstptr;
+	register jpc_fix_t *srcptr2;
+	register jpc_fix_t *dstptr2;
+
+	/* Allocate memory for the join buffer from the heap. */
+	const size_t bufsize = JPC_CEILDIVPOW2(numrows, 1);
+	if (bufsize > QMFB_JOINBUFSIZE) {
+		if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE,
+		  sizeof(jpc_fix_t)))) {
+			/* We have no choice but to commit suicide. */
+			abort();
+		}
+	}
+
+	const unsigned hstartcol = (numrows + !parity) >> 1;
+
+	/* Save the samples from the lowpass channel. */
+	srcptr = &a[0];
+	dstptr = buf;
+	for (unsigned n = hstartcol; n > 0; --n) {
+		dstptr2 = dstptr;
+		srcptr2 = srcptr;
+		for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+			*dstptr2 = *srcptr2;
+			++dstptr2;
+			++srcptr2;
+		}
+		srcptr += stride;
+		dstptr += JPC_QMFB_COLGRPSIZE;
+	}
+	/* Copy the samples from the highpass channel into place. */
+	srcptr = &a[hstartcol * stride];
+	dstptr = &a[(!parity) * stride];
+	for (unsigned n = numrows - hstartcol; n > 0; --n) {
+		dstptr2 = dstptr;
+		srcptr2 = srcptr;
+		for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+			*dstptr2 = *srcptr2;
+			++dstptr2;
+			++srcptr2;
+		}
+		dstptr += 2 * stride;
+		srcptr += stride;
+	}
+	/* Copy the samples from the lowpass channel into place. */
+	srcptr = buf;
+	dstptr = &a[parity * stride];
+	for (unsigned n = hstartcol; n > 0; --n) {
+		dstptr2 = dstptr;
+		srcptr2 = srcptr;
+		for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+			*dstptr2 = *srcptr2;
+			++dstptr2;
+			++srcptr2;
+		}
+		dstptr += 2 * stride;
+		srcptr += JPC_QMFB_COLGRPSIZE;
+	}
+
+	/* If the join buffer was allocated on the heap, free this memory. */
+	if (buf != joinbuf) {
+		jas_free(buf);
+	}
+
+}
+
+static void jpc_qmfb_join_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols,
+  unsigned stride, bool parity)
+{
+
+	jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
+	jpc_fix_t *buf = joinbuf;
+	jpc_fix_t *srcptr;
+	jpc_fix_t *dstptr;
+	register jpc_fix_t *srcptr2;
+	register jpc_fix_t *dstptr2;
+
+	/* Allocate memory for the join buffer from the heap. */
+	const size_t bufsize = JPC_CEILDIVPOW2(numrows, 1);
+	if (bufsize > QMFB_JOINBUFSIZE) {
+		if (!(buf = jas_alloc3(bufsize, numcols, sizeof(jpc_fix_t)))) {
+			/* We have no choice but to commit suicide. */
+			abort();
+		}
+	}
+
+	const unsigned hstartcol = (numrows + !parity) >> 1;
+
+	/* Save the samples from the lowpass channel. */
+	srcptr = &a[0];
+	dstptr = buf;
+	for (unsigned n = hstartcol; n > 0; --n) {
+		dstptr2 = dstptr;
+		srcptr2 = srcptr;
+		for (unsigned i = 0; i < numcols; ++i) {
+			*dstptr2 = *srcptr2;
+			++dstptr2;
+			++srcptr2;
+		}
+		srcptr += stride;
+		dstptr += numcols;
+	}
+	/* Copy the samples from the highpass channel into place. */
+	srcptr = &a[hstartcol * stride];
+	dstptr = &a[(!parity) * stride];
+	for (unsigned n = numrows - hstartcol; n > 0; --n) {
+		dstptr2 = dstptr;
+		srcptr2 = srcptr;
+		for (unsigned i = 0; i < numcols; ++i) {
+			*dstptr2 = *srcptr2;
+			++dstptr2;
+			++srcptr2;
+		}
+		dstptr += 2 * stride;
+		srcptr += stride;
+	}
+	/* Copy the samples from the lowpass channel into place. */
+	srcptr = buf;
+	dstptr = &a[parity * stride];
+	for (unsigned n = hstartcol; n > 0; --n) {
+		dstptr2 = dstptr;
+		srcptr2 = srcptr;
+		for (unsigned i = 0; i < numcols; ++i) {
+			*dstptr2 = *srcptr2;
+			++dstptr2;
+			++srcptr2;
+		}
+		dstptr += 2 * stride;
+		srcptr += numcols;
+	}
+
+	/* If the join buffer was allocated on the heap, free this memory. */
+	if (buf != joinbuf) {
+		jas_free(buf);
+	}
+
+}
+
+/******************************************************************************\
+* 5/3 transform
+\******************************************************************************/
+
+static void jpc_ft_fwdlift_row(jpc_fix_t *a, unsigned numcols, bool parity)
+{
+
+	register jpc_fix_t *lptr;
+	register jpc_fix_t *hptr;
+
+	const unsigned llen = (numcols + !parity) >> 1;
+	const bool end_parity = parity == (numcols & 1);
+
+	if (numcols > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen];
+		if (parity) {
+			hptr[0] -= lptr[0];
+			++hptr;
+		}
+		for (unsigned n = numcols - llen - parity - end_parity; n > 0; --n) {
+			//hptr[0] -= (lptr[0] + lptr[1]) >> 1;
+			hptr[0] -= jpc_fix_asr(lptr[0] + lptr[1], 1);
+			++hptr;
+			++lptr;
+		}
+		if (end_parity) {
+			hptr[0] -= lptr[0];
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen];
+		if (!parity) {
+			//lptr[0] += (hptr[0] + 1) >> 1;
+			lptr[0] += jpc_fix_asr(hptr[0] + 1, 1);
+			++lptr;
+		}
+		for (unsigned n = llen - (!parity) - (!end_parity); n > 0; --n) {
+			//lptr[0] += (hptr[0] + hptr[1] + 2) >> 2;
+			lptr[0] += jpc_fix_asr(hptr[0] + hptr[1] + 2, 2);
+			++lptr;
+			++hptr;
+		}
+		if (!end_parity) {
+			//lptr[0] += (hptr[0] + 1) >> 1;
+			lptr[0] += jpc_fix_asr(hptr[0] + 1, 1);
+		}
+
+	} else {
+
+		if (parity) {
+			lptr = &a[0];
+			//lptr[0] <<= 1;
+			lptr[0] = jpc_fix_asl(lptr[0], 1);
+		}
+
+	}
+
+}
+
+static void jpc_ft_fwdlift_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride, bool parity)
+{
+
+	jpc_fix_t *lptr;
+	jpc_fix_t *hptr;
+	register jpc_fix_t *lptr2;
+	register jpc_fix_t *hptr2;
+
+	const unsigned llen = (numrows + !parity) >> 1;
+	const bool end_parity = parity == (numrows & 1);
+
+	if (numrows > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				hptr2[0] -= lptr2[0];
+				++hptr2;
+				++lptr2;
+			}
+			hptr += stride;
+		}
+		for (unsigned n = numrows - llen - parity - end_parity; n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//hptr2[0] -= (lptr2[0] + lptr2[stride]) >> 1;
+				hptr2[0] -= jpc_fix_asr(lptr2[0] + lptr2[stride], 1);
+				++lptr2;
+				++hptr2;
+			}
+			hptr += stride;
+			lptr += stride;
+		}
+		if (end_parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				hptr2[0] -= lptr2[0];
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (!parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] += (hptr2[0] + 1) >> 1;
+				lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1);
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+		}
+		for (unsigned n = llen - (!parity) - (parity != (numrows & 1)); n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] += (hptr2[0] + hptr2[stride] + 2) >> 2;
+				lptr2[0] += jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2);
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+			hptr += stride;
+		}
+		if (parity != (numrows & 1)) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] += (hptr2[0] + 1) >> 1;
+				lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1);
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+	} else {
+
+		if (parity) {
+			lptr2 = &a[0];
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] <<= 1;
+				lptr2[0] = jpc_fix_asl(lptr2[0], 1);
+				++lptr2;
+			}
+		}
+
+	}
+
+}
+
+static void jpc_ft_fwdlift_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols, unsigned stride,
+  bool parity)
+{
+
+	jpc_fix_t *lptr;
+	jpc_fix_t *hptr;
+	register jpc_fix_t *lptr2;
+	register jpc_fix_t *hptr2;
+
+	const unsigned llen = (numrows + !parity) >> 1;
+	const bool end_parity = parity == (numrows & 1);
+
+	if (numrows > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				hptr2[0] -= lptr2[0];
+				++hptr2;
+				++lptr2;
+			}
+			hptr += stride;
+		}
+		for (unsigned n = numrows - llen - parity - end_parity; n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				//hptr2[0] -= (lptr2[0] + lptr2[stride]) >> 1;
+				hptr2[0] -= jpc_fix_asr(lptr2[0] + lptr2[stride], 1);
+				++lptr2;
+				++hptr2;
+			}
+			hptr += stride;
+			lptr += stride;
+		}
+		if (end_parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				hptr2[0] -= lptr2[0];
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (!parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] += (hptr2[0] + 1) >> 1;
+				lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1);
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+		}
+		for (unsigned n = llen - (!parity) - (parity != (numrows & 1)); n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] += (hptr2[0] + hptr2[stride] + 2) >> 2;
+				lptr2[0] += jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2);
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+			hptr += stride;
+		}
+		if (parity != (numrows & 1)) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] += (hptr2[0] + 1) >> 1;
+				lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1);
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+	} else {
+
+		if (parity) {
+			lptr2 = &a[0];
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] <<= 1;
+				lptr2[0] = jpc_fix_asl(lptr2[0], 1);
+				++lptr2;
+			}
+		}
+
+	}
+
+}
+
+static void jpc_ft_invlift_row(jpc_fix_t *a, unsigned numcols, bool parity)
+{
+
+	register jpc_fix_t *lptr;
+	register jpc_fix_t *hptr;
+
+	const unsigned llen = (numcols + !parity) >> 1;
+	const bool end_parity = parity == (numcols & 1);
+
+	if (numcols > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen];
+		if (!parity) {
+			//lptr[0] -= (hptr[0] + 1) >> 1;
+			lptr[0] -= jpc_fix_asr(hptr[0] + 1, 1);
+			++lptr;
+		}
+		for (unsigned n = llen - (!parity) - (!end_parity); n > 0; --n) {
+			//lptr[0] -= (hptr[0] + hptr[1] + 2) >> 2;
+			lptr[0] -= jpc_fix_asr(hptr[0] + hptr[1] + 2, 2);
+			++lptr;
+			++hptr;
+		}
+		if (!end_parity) {
+			//lptr[0] -= (hptr[0] + 1) >> 1;
+			lptr[0] -= jpc_fix_asr(hptr[0] + 1, 1);
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen];
+		if (parity) {
+			hptr[0] += lptr[0];
+			++hptr;
+		}
+		for (unsigned n = numcols - llen - parity - end_parity; n > 0; --n) {
+			//hptr[0] += (lptr[0] + lptr[1]) >> 1;
+			hptr[0] += jpc_fix_asr(lptr[0] + lptr[1], 1);
+			++hptr;
+			++lptr;
+		}
+		if (end_parity) {
+			hptr[0] += lptr[0];
+		}
+
+	} else {
+
+		if (parity) {
+			lptr = &a[0];
+			//lptr[0] >>= 1;
+			lptr[0] = jpc_fix_asr(lptr[0], 1);
+		}
+
+	}
+
+}
+
+static void jpc_ft_invlift_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride, bool parity)
+{
+
+	jpc_fix_t *lptr;
+	jpc_fix_t *hptr;
+	register jpc_fix_t *lptr2;
+	register jpc_fix_t *hptr2;
+
+	const unsigned llen = (numrows + !parity) >> 1;
+	const bool end_parity = parity == (numrows & 1);
+
+	if (numrows > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (!parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] -= (hptr2[0] + 1) >> 1;
+				lptr2[0] -= jpc_fix_asr(hptr2[0] + 1, 1);
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+		}
+		for (unsigned n = llen - (!parity) - (parity != (numrows & 1)); n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] -= (hptr2[0] + hptr2[stride] + 2) >> 2;
+				lptr2[0] -= jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2);
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+			hptr += stride;
+		}
+		if (parity != (numrows & 1)) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] -= (hptr2[0] + 1) >> 1;
+				lptr2[0] -= jpc_fix_asr(hptr2[0] + 1, 1);
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				hptr2[0] += lptr2[0];
+				++hptr2;
+				++lptr2;
+			}
+			hptr += stride;
+		}
+		for (unsigned n = numrows - llen - parity - end_parity; n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//hptr2[0] += (lptr2[0] + lptr2[stride]) >> 1;
+				hptr2[0] += jpc_fix_asr(lptr2[0] + lptr2[stride], 1);
+				++lptr2;
+				++hptr2;
+			}
+			hptr += stride;
+			lptr += stride;
+		}
+		if (end_parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				hptr2[0] += lptr2[0];
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+	} else {
+
+		if (parity) {
+			lptr2 = &a[0];
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] >>= 1;
+				lptr2[0] = jpc_fix_asr(lptr2[0], 1);
+				++lptr2;
+			}
+		}
+
+	}
+
+}
+
+static void jpc_ft_invlift_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols, unsigned stride,
+  bool parity)
+{
+
+	jpc_fix_t *lptr;
+	jpc_fix_t *hptr;
+	register jpc_fix_t *lptr2;
+	register jpc_fix_t *hptr2;
+
+	const unsigned llen = (numrows + !parity) >> 1;
+	const bool end_parity = parity == (numrows & 1);
+
+	if (numrows > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (!parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] -= (hptr2[0] + 1) >> 1;
+				lptr2[0] -= jpc_fix_asr(hptr2[0] + 1, 1);
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+		}
+		for (unsigned n = llen - (!parity) - (parity != (numrows & 1)); n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] -= (hptr2[0] + hptr2[stride] + 2) >> 2;
+				lptr2[0] -= jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2);
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+			hptr += stride;
+		}
+		if (parity != (numrows & 1)) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] -= (hptr2[0] + 1) >> 1;
+				lptr2[0] -= jpc_fix_asr(hptr2[0] + 1, 1);
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				hptr2[0] += lptr2[0];
+				++hptr2;
+				++lptr2;
+			}
+			hptr += stride;
+		}
+		for (unsigned n = numrows - llen - parity - end_parity; n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				//hptr2[0] += (lptr2[0] + lptr2[stride]) >> 1;
+				hptr2[0] += jpc_fix_asr(lptr2[0] + lptr2[stride], 1);
+				++lptr2;
+				++hptr2;
+			}
+			hptr += stride;
+			lptr += stride;
+		}
+		if (end_parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				hptr2[0] += lptr2[0];
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+	} else {
+
+		if (parity) {
+			lptr2 = &a[0];
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] >>= 1;
+				lptr2[0] = jpc_fix_asr(lptr2[0], 1);
+				++lptr2;
+			}
+		}
+
+	}
+
+}
+
+static int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+  int stride)
+{
+	const unsigned numrows = height;
+	const unsigned numcols = width;
+	const unsigned rowparity = ystart & 1;
+	const unsigned colparity = xstart & 1;
+	jpc_fix_t *startptr;
+
+	const unsigned maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+	startptr = &a[0];
+	for (unsigned i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
+		jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity);
+		jpc_ft_fwdlift_colgrp(startptr, numrows, stride, rowparity);
+		startptr += JPC_QMFB_COLGRPSIZE;
+	}
+	if (maxcols < numcols) {
+		jpc_qmfb_split_colres(startptr, numrows, numcols - maxcols, stride,
+		  rowparity);
+		jpc_ft_fwdlift_colres(startptr, numrows, numcols - maxcols, stride,
+		  rowparity);
+	}
+
+	startptr = &a[0];
+	for (unsigned i = 0; i < numrows; ++i) {
+		jpc_qmfb_split_row(startptr, numcols, colparity);
+		jpc_ft_fwdlift_row(startptr, numcols, colparity);
+		startptr += stride;
+	}
+
+	return 0;
+
+}
+
+static int jpc_ft_synthesize(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+  int stride)
+{
+	const unsigned numrows = height;
+	const unsigned numcols = width;
+	const unsigned rowparity = ystart & 1;
+	const unsigned colparity = xstart & 1;
+
+	jpc_fix_t *startptr;
+
+	startptr = &a[0];
+	for (unsigned i = 0; i < numrows; ++i) {
+		jpc_ft_invlift_row(startptr, numcols, colparity);
+		jpc_qmfb_join_row(startptr, numcols, colparity);
+		startptr += stride;
+	}
+
+	const unsigned maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+	startptr = &a[0];
+	for (unsigned i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
+		jpc_ft_invlift_colgrp(startptr, numrows, stride, rowparity);
+		jpc_qmfb_join_colgrp(startptr, numrows, stride, rowparity);
+		startptr += JPC_QMFB_COLGRPSIZE;
+	}
+	if (maxcols < numcols) {
+		jpc_ft_invlift_colres(startptr, numrows, numcols - maxcols, stride,
+		  rowparity);
+		jpc_qmfb_join_colres(startptr, numrows, numcols - maxcols, stride,
+		  rowparity);
+	}
+
+	return 0;
+
+}
+
+/******************************************************************************\
+* 9/7 transform
+\******************************************************************************/
+
+#define ALPHA (-1.586134342059924)
+#define BETA (-0.052980118572961)
+#define GAMMA (0.882911075530934)
+#define DELTA (0.443506852043971)
+#define LGAIN (1.0 / 1.23017410558578)
+#define HGAIN (1.0 / 1.62578613134411)
+
+static void jpc_ns_fwdlift_row(jpc_fix_t *a, unsigned numcols, bool parity)
+{
+
+	register jpc_fix_t *lptr;
+	register jpc_fix_t *hptr;
+
+	const unsigned llen = (numcols + !parity) >> 1;
+	const bool end_parity = parity == (numcols & 1);
+
+	if (numcols > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen];
+		if (parity) {
+			jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+			  lptr[0]));
+			++hptr;
+		}
+		for (unsigned n = numcols - llen - parity - end_parity; n > 0; --n) {
+			jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+			  jpc_fix_add(lptr[0], lptr[1])));
+			++hptr;
+			++lptr;
+		}
+		if (end_parity) {
+			jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+			  lptr[0]));
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen];
+		if (!parity) {
+			jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+			  hptr[0]));
+			++lptr;
+		}
+		for (unsigned n = llen - (!parity) - (!end_parity); n > 0; --n) {
+			jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(BETA),
+			  jpc_fix_add(hptr[0], hptr[1])));
+			++lptr;
+			++hptr;
+		}
+		if (!end_parity) {
+			jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+			  hptr[0]));
+		}
+
+		/* Apply the third lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen];
+		if (parity) {
+			jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+			  lptr[0]));
+			++hptr;
+		}
+		for (unsigned n = numcols - llen - parity - end_parity; n > 0; --n) {
+			jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+			  jpc_fix_add(lptr[0], lptr[1])));
+			++hptr;
+			++lptr;
+		}
+		if (end_parity) {
+			jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+			  lptr[0]));
+		}
+
+		/* Apply the fourth lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen];
+		if (!parity) {
+			jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+			  hptr[0]));
+			++lptr;
+		}
+		for (unsigned n = llen - (!parity) - (!end_parity); n > 0; --n) {
+			jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+			  jpc_fix_add(hptr[0], hptr[1])));
+			++lptr;
+			++hptr;
+		}
+		if (!end_parity) {
+			jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+			  hptr[0]));
+		}
+
+		/* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+		lptr = &a[0];
+		for (unsigned n = llen; n > 0; --n) {
+			lptr[0] = jpc_fix_mul(lptr[0], jpc_dbltofix(LGAIN));
+			++lptr;
+		}
+		hptr = &a[llen];
+		for (unsigned n = numcols - llen; n > 0; --n) {
+			hptr[0] = jpc_fix_mul(hptr[0], jpc_dbltofix(HGAIN));
+			++hptr;
+		}
+#endif
+
+	} else {
+
+#if defined(WT_LENONE)
+		if (parity) {
+			lptr = &a[0];
+			//lptr[0] <<= 1;
+			lptr[0] = jpc_fix_asl(lptr[0], 1);
+		}
+#endif
+
+	}
+
+}
+
+static void jpc_ns_fwdlift_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride,
+  bool parity)
+{
+
+	jpc_fix_t *lptr;
+	jpc_fix_t *hptr;
+	register jpc_fix_t *lptr2;
+	register jpc_fix_t *hptr2;
+
+	const unsigned llen = (numrows + !parity) >> 1;
+	const bool end_parity = parity == (numrows & 1);
+
+	if (numrows > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+				  lptr2[0]));
+				++hptr2;
+				++lptr2;
+			}
+			hptr += stride;
+		}
+		for (unsigned n = numrows - llen - parity - end_parity; n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+				  jpc_fix_add(lptr2[0], lptr2[stride])));
+				++lptr2;
+				++hptr2;
+			}
+			hptr += stride;
+			lptr += stride;
+		}
+		if (end_parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+				  lptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (!parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+				  hptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+		}
+		for (unsigned n = llen - (!parity) - (parity != (numrows & 1)); n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
+				  jpc_fix_add(hptr2[0], hptr2[stride])));
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+			hptr += stride;
+		}
+		if (parity != (numrows & 1)) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+				  hptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the third lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+				  lptr2[0]));
+				++hptr2;
+				++lptr2;
+			}
+			hptr += stride;
+		}
+		for (unsigned n = numrows - llen - parity - end_parity; n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+				  jpc_fix_add(lptr2[0], lptr2[stride])));
+				++lptr2;
+				++hptr2;
+			}
+			hptr += stride;
+			lptr += stride;
+		}
+		if (end_parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+				  lptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the fourth lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (!parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+				  hptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+		}
+		for (unsigned n = llen - (!parity) - (parity != (numrows & 1)); n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+				  jpc_fix_add(hptr2[0], hptr2[stride])));
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+			hptr += stride;
+		}
+		if (parity != (numrows & 1)) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+				  hptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+		lptr = &a[0];
+		for (unsigned n = llen; n > 0; --n) {
+			lptr2 = lptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(LGAIN));
+				++lptr2;
+			}
+			lptr += stride;
+		}
+		hptr = &a[llen * stride];
+		for (unsigned n = numrows - llen; n > 0; --n) {
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(HGAIN));
+				++hptr2;
+			}
+			hptr += stride;
+		}
+#endif
+
+	} else {
+
+#if defined(WT_LENONE)
+		if (parity) {
+			lptr2 = &a[0];
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] <<= 1;
+				lptr2[0] = jpc_fix_asl(lptr2[0], 1);
+				++lptr2;
+			}
+		}
+#endif
+
+	}
+
+}
+
+static void jpc_ns_fwdlift_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols,
+  unsigned stride, bool parity)
+{
+
+	jpc_fix_t *lptr;
+	jpc_fix_t *hptr;
+	register jpc_fix_t *lptr2;
+	register jpc_fix_t *hptr2;
+
+	const unsigned llen = (numrows + !parity) >> 1;
+	const bool end_parity = parity == (numrows & 1);
+
+	if (numrows > 1) {
+
+		/* Apply the first lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+				  lptr2[0]));
+				++hptr2;
+				++lptr2;
+			}
+			hptr += stride;
+		}
+		for (unsigned n = numrows - llen - parity - end_parity; n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+				  jpc_fix_add(lptr2[0], lptr2[stride])));
+				++lptr2;
+				++hptr2;
+			}
+			hptr += stride;
+			lptr += stride;
+		}
+		if (end_parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+				  lptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the second lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (!parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+				  hptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+		}
+		for (unsigned n = llen - (!parity) - (parity != (numrows & 1)); n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
+				  jpc_fix_add(hptr2[0], hptr2[stride])));
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+			hptr += stride;
+		}
+		if (parity != (numrows & 1)) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+				  hptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the third lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+				  lptr2[0]));
+				++hptr2;
+				++lptr2;
+			}
+			hptr += stride;
+		}
+		for (unsigned n = numrows - llen - parity - end_parity; n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+				  jpc_fix_add(lptr2[0], lptr2[stride])));
+				++lptr2;
+				++hptr2;
+			}
+			hptr += stride;
+			lptr += stride;
+		}
+		if (end_parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+				  lptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the fourth lifting step. */
+		lptr = &a[0];
+		hptr = &a[llen * stride];
+		if (!parity) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+				  hptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+		}
+		for (unsigned n = llen - (!parity) - (parity != (numrows & 1)); n > 0; --n) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+				  jpc_fix_add(hptr2[0], hptr2[stride])));
+				++lptr2;
+				++hptr2;
+			}
+			lptr += stride;
+			hptr += stride;
+		}
+		if (parity != (numrows & 1)) {
+			lptr2 = lptr;
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+				  hptr2[0]));
+				++lptr2;
+				++hptr2;
+			}
+		}
+
+		/* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+		lptr = &a[0];
+		for (unsigned n = llen; n > 0; --n) {
+			lptr2 = lptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(LGAIN));
+				++lptr2;
+			}
+			lptr += stride;
+		}
+		hptr = &a[llen * stride];
+		for (unsigned n = numrows - llen; n > 0; --n) {
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(HGAIN));
+				++hptr2;
+			}
+			hptr += stride;
+		}
+#endif
+
+	} else {
+
+#if defined(WT_LENONE)
+		if (parity) {
+			lptr2 = &a[0];
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] <<= 1;
+				lptr2[0] = jpc_fix_asl(lptr2[0], 1);
+				++lptr2;
+			}
+		}
+#endif
+
+	}
+
+}
+
+#ifdef _MSC_VER
+/* MSVC doesn't support C99 "restrict" */
+#define restrict
+#endif
+
+JAS_FORCE_INLINE
+static void jpc_invlift_n(jpc_fix_t *restrict dest,
+			  const jpc_fix_t *restrict src,
+			  jpc_fix_t factor,
+			  size_t n)
+{
+	for (size_t i = 0; i < n; ++i)
+		jpc_fix_minuseq(dest[i], jpc_fix_mul(factor, src[i]));
+}
+
+JAS_FORCE_INLINE
+static void jpc_invlift_pair_stride(jpc_fix_t *restrict dest,
+				    const jpc_fix_t *restrict src,
+				    jpc_fix_t factor,
+				    size_t n, size_t stride)
+{
+	for (size_t i = 0; i < n; ++i)
+		jpc_fix_minuseq(dest[i],
+				jpc_fix_mul(factor,
+					    jpc_fix_add(src[i], src[i + stride])));
+}
+
+JAS_FORCE_INLINE
+static void jpc_invlift_pair(jpc_fix_t *restrict dest,
+			     const jpc_fix_t *restrict src,
+			     jpc_fix_t factor,
+			     size_t n)
+{
+	jpc_invlift_pair_stride(dest, src, factor, n, 1);
+}
+
+static void jpc_invlift_pair_with_parity(jpc_fix_t *restrict dest,
+					 const jpc_fix_t *restrict src,
+					 jpc_fix_t factor,
+					 jpc_fix_t border_factor,
+					 size_t n,
+					 bool start_parity, bool end_parity)
+{
+	if (start_parity) {
+		jpc_fix_minuseq(*dest, jpc_fix_mul(border_factor, *src));
+		++dest;
+	}
+
+	n -= start_parity + end_parity;
+	jpc_invlift_pair(dest, src, factor, n);
+	dest += n;
+	src += n;
+
+	if (end_parity)
+		jpc_fix_minuseq(*dest, jpc_fix_mul(border_factor, *src));
+}
+
+static void jpc_invlift_column_with_parity(jpc_fix_t *restrict dest,
+					   const jpc_fix_t *restrict src,
+					   jpc_fix_t factor,
+					   jpc_fix_t border_factor,
+					   size_t n_columns,
+					   size_t n_rows,
+					   size_t stride,
+					   bool start_parity, bool end_parity)
+{
+	if (start_parity) {
+		jpc_invlift_n(dest, src, border_factor, n_columns);
+		dest += stride;
+	}
+
+	n_rows -= start_parity + end_parity;
+	for (size_t i = 0; i < n_rows; ++i) {
+		jpc_invlift_pair_stride(dest, src, factor,
+					n_columns, stride);
+		dest += stride;
+		src += stride;
+	}
+
+	if (end_parity)
+		jpc_invlift_n(dest, src, border_factor, n_columns);
+}
+
+static void jpc_ns_invlift_row(jpc_fix_t *a, unsigned numcols, bool parity)
+{
+
+	register jpc_fix_t *lptr;
+	register jpc_fix_t *hptr;
+
+	const unsigned llen = (numcols + !parity) >> 1;
+	const bool end_parity = parity == (numcols & 1);
+
+	if (numcols > 1) {
+
+		/* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+		lptr = &a[0];
+		for (unsigned n = llen; n > 0; --n) {
+			lptr[0] = jpc_fix_mul(lptr[0], jpc_dbltofix(1.0 / LGAIN));
+			++lptr;
+		}
+		hptr = &a[llen];
+		for (unsigned n = numcols - llen; n > 0; --n) {
+			hptr[0] = jpc_fix_mul(hptr[0], jpc_dbltofix(1.0 / HGAIN));
+			++hptr;
+		}
+#endif
+
+		/* Apply the first lifting step. */
+		jpc_invlift_pair_with_parity(&a[0], &a[llen],
+					     jpc_dbltofix(DELTA),
+					     jpc_dbltofix(2 * DELTA),
+					     llen,
+					     !parity, !end_parity);
+
+		/* Apply the second lifting step. */
+		jpc_invlift_pair_with_parity(&a[llen], &a[0],
+					     jpc_dbltofix(GAMMA),
+					     jpc_dbltofix(2 * GAMMA),
+					     numcols - llen,
+					     parity, end_parity);
+
+		/* Apply the third lifting step. */
+		jpc_invlift_pair_with_parity(&a[0], &a[llen],
+					     jpc_dbltofix(BETA),
+					     jpc_dbltofix(2 * BETA),
+					     llen, !parity, !end_parity);
+
+		/* Apply the fourth lifting step. */
+		jpc_invlift_pair_with_parity(&a[llen], &a[0],
+					     jpc_dbltofix(ALPHA),
+					     jpc_dbltofix(2 * ALPHA),
+					     numcols - llen,
+					     parity, end_parity);
+
+	} else {
+
+#if defined(WT_LENONE)
+		if (parity) {
+			lptr = &a[0];
+			//lptr[0] >>= 1;
+			lptr[0] = jpc_fix_asr(lptr[0], 1);
+		}
+#endif
+
+	}
+
+}
+
+static void jpc_ns_invlift_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride,
+  bool parity)
+{
+
+	jpc_fix_t *lptr;
+	jpc_fix_t *hptr;
+	register jpc_fix_t *lptr2;
+	register jpc_fix_t *hptr2;
+
+	const unsigned llen = (numrows + !parity) >> 1;
+	const bool end_parity = parity == (numrows & 1);
+
+	if (numrows > 1) {
+
+		/* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+		lptr = &a[0];
+		for (unsigned n = llen; n > 0; --n) {
+			lptr2 = lptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN));
+				++lptr2;
+			}
+			lptr += stride;
+		}
+		hptr = &a[llen * stride];
+		for (unsigned n = numrows - llen; n > 0; --n) {
+			hptr2 = hptr;
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN));
+				++hptr2;
+			}
+			hptr += stride;
+		}
+#endif
+
+		/* Apply the first lifting step. */
+		jpc_invlift_column_with_parity(&a[0], &a[llen * stride],
+					       jpc_dbltofix(DELTA),
+					       jpc_dbltofix(2 * DELTA),
+					       JPC_QMFB_COLGRPSIZE,
+					       llen, stride,
+					       !parity, !end_parity);
+
+		/* Apply the second lifting step. */
+		jpc_invlift_column_with_parity(&a[llen * stride], &a[0],
+					       jpc_dbltofix(GAMMA),
+					       jpc_dbltofix(2 * GAMMA),
+					       JPC_QMFB_COLGRPSIZE,
+					       numrows - llen, stride,
+					       parity, end_parity);
+
+		/* Apply the third lifting step. */
+		jpc_invlift_column_with_parity(&a[0], &a[llen * stride],
+					       jpc_dbltofix(BETA),
+					       jpc_dbltofix(2 * BETA),
+					       JPC_QMFB_COLGRPSIZE,
+					       llen, stride,
+					       !parity, !end_parity);
+
+		/* Apply the fourth lifting step. */
+		jpc_invlift_column_with_parity(&a[llen * stride], &a[0],
+					       jpc_dbltofix(ALPHA),
+					       jpc_dbltofix(2 * ALPHA),
+					       JPC_QMFB_COLGRPSIZE,
+					       numrows - llen, stride,
+					       parity, end_parity);
+
+	} else {
+
+#if defined(WT_LENONE)
+		if (parity) {
+			lptr2 = &a[0];
+			for (unsigned i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+				//lptr2[0] >>= 1;
+				lptr2[0] = jpc_fix_asr(lptr2[0], 1);
+				++lptr2;
+			}
+		}
+#endif
+
+	}
+
+}
+
+static void jpc_ns_invlift_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols,
+  unsigned stride, bool parity)
+{
+
+	jpc_fix_t *lptr;
+	jpc_fix_t *hptr;
+	register jpc_fix_t *lptr2;
+	register jpc_fix_t *hptr2;
+
+	const unsigned llen = (numrows + !parity) >> 1;
+	const bool end_parity = parity == (numrows & 1);
+
+	if (numrows > 1) {
+
+		/* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+		lptr = &a[0];
+		for (unsigned n = llen; n > 0; --n) {
+			lptr2 = lptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN));
+				++lptr2;
+			}
+			lptr += stride;
+		}
+		hptr = &a[llen * stride];
+		for (unsigned n = numrows - llen; n > 0; --n) {
+			hptr2 = hptr;
+			for (unsigned i = 0; i < numcols; ++i) {
+				hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN));
+				++hptr2;
+			}
+			hptr += stride;
+		}
+#endif
+
+		/* Apply the first lifting step. */
+		jpc_invlift_column_with_parity(&a[0], &a[llen * stride],
+					       jpc_dbltofix(DELTA),
+					       jpc_dbltofix(2 * DELTA),
+					       numcols,
+					       llen, stride,
+					       !parity, !end_parity);
+
+		/* Apply the second lifting step. */
+		jpc_invlift_column_with_parity(&a[llen * stride], &a[0],
+					       jpc_dbltofix(GAMMA),
+					       jpc_dbltofix(2 * GAMMA),
+					       numcols,
+					       numrows - llen, stride,
+					       parity, end_parity);
+
+		/* Apply the third lifting step. */
+		jpc_invlift_column_with_parity(&a[0], &a[llen * stride],
+					       jpc_dbltofix(BETA),
+					       jpc_dbltofix(2 * BETA),
+					       numcols,
+					       llen, stride,
+					       !parity, !end_parity);
+
+		/* Apply the fourth lifting step. */
+		jpc_invlift_column_with_parity(&a[llen * stride], &a[0],
+					       jpc_dbltofix(ALPHA),
+					       jpc_dbltofix(2 * ALPHA),
+					       numcols,
+					       numrows - llen, stride,
+					       parity, end_parity);
+
+	} else {
+
+#if defined(WT_LENONE)
+		if (parity) {
+			lptr2 = &a[0];
+			for (unsigned i = 0; i < numcols; ++i) {
+				//lptr2[0] >>= 1;
+				lptr2[0] = jpc_fix_asr(lptr2[0], 1);
+				++lptr2;
+			}
+		}
+#endif
+
+	}
+
+}
+
+static int jpc_ns_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+  int stride)
+{
+
+	const unsigned numrows = height;
+	const unsigned numcols = width;
+	const unsigned rowparity = ystart & 1;
+	const unsigned colparity = xstart & 1;
+	jpc_fix_t *startptr;
+
+	const unsigned maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+	startptr = &a[0];
+	for (unsigned i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
+		jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity);
+		jpc_ns_fwdlift_colgrp(startptr, numrows, stride, rowparity);
+		startptr += JPC_QMFB_COLGRPSIZE;
+	}
+	if (maxcols < numcols) {
+		jpc_qmfb_split_colres(startptr, numrows, numcols - maxcols, stride,
+		  rowparity);
+		jpc_ns_fwdlift_colres(startptr, numrows, numcols - maxcols, stride,
+		  rowparity);
+	}
+
+	startptr = &a[0];
+	for (unsigned i = 0; i < numrows; ++i) {
+		jpc_qmfb_split_row(startptr, numcols, colparity);
+		jpc_ns_fwdlift_row(startptr, numcols, colparity);
+		startptr += stride;
+	}
+
+	return 0;
+
+}
+
+static int jpc_ns_synthesize(jpc_fix_t *a, int xstart, int ystart, int width,
+  int height, int stride)
+{
+
+	const unsigned numrows = height;
+	const unsigned numcols = width;
+	const unsigned rowparity = ystart & 1;
+	const unsigned colparity = xstart & 1;
+	jpc_fix_t *startptr;
+
+	startptr = &a[0];
+	for (unsigned i = 0; i < numrows; ++i) {
+		jpc_ns_invlift_row(startptr, numcols, colparity);
+		jpc_qmfb_join_row(startptr, numcols, colparity);
+		startptr += stride;
+	}
+
+	const unsigned maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+	startptr = &a[0];
+	for (unsigned i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
+		jpc_ns_invlift_colgrp(startptr, numrows, stride, rowparity);
+		jpc_qmfb_join_colgrp(startptr, numrows, stride, rowparity);
+		startptr += JPC_QMFB_COLGRPSIZE;
+	}
+	if (maxcols < numcols) {
+		jpc_ns_invlift_colres(startptr, numrows, numcols - maxcols, stride,
+		  rowparity);
+		jpc_qmfb_join_colres(startptr, numrows, numcols - maxcols, stride,
+		  rowparity);
+	}
+
+	return 0;
+
+}
+
--- /dev/null
+++ b/jpc_qmfb.h
@@ -1,0 +1,113 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2004 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Quadrature Mirror-Image Filter Bank (QMFB) Routines
+ *
+ * $Id$
+ */
+
+#ifndef JPC_QMFB_H
+#define JPC_QMFB_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_fix.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* QMFB IDs. */
+#define	JPC_QMFB1D_FT	1	/* 5/3 */
+#define	JPC_QMFB1D_NS	2	/* 9/7 */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+#if !defined(JPC_QMFB_COLGRPSIZE)
+/* The number of columns to group together during the vertical processing
+stage of the wavelet transform. */
+/* The default value for this parameter is probably not optimal for
+any particular platform.  Hopefully, it is not too unreasonable, however. */
+#define JPC_QMFB_COLGRPSIZE	16
+#endif
+
+typedef struct {
+	int (*analyze)(jpc_fix_t *, int, int, int, int, int);
+	int (*synthesize)(jpc_fix_t *, int, int, int, int, int);
+	const double *lpenergywts;
+	const double *hpenergywts;
+} jpc_qmfb2d_t;
+
+extern const jpc_qmfb2d_t jpc_ft_qmfb2d;
+extern const jpc_qmfb2d_t jpc_ns_qmfb2d;
+
+#endif
--- /dev/null
+++ b/jpc_t1cod.c
@@ -1,0 +1,485 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_t1cod.h"
+#include "jpc_cod.h"
+#include "jpc_cs.h"
+#include "jpc_mqcod.h"
+#include "jpc_tsfb.h"
+
+#include "jasper/jas_math.h"
+
+JAS_ATTRIBUTE_CONST
+static double jpc_pow2i(int n);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+uint_least8_t jpc_zcctxnolut[4 * 256];
+bool jpc_spblut[256];
+uint_least8_t jpc_scctxnolut[256];
+uint_least8_t jpc_magctxnolut[4096];
+
+jpc_fix_t jpc_signmsedec[1 << JPC_NMSEDEC_BITS];
+jpc_fix_t jpc_refnmsedec[1 << JPC_NMSEDEC_BITS];
+jpc_fix_t jpc_signmsedec0[1 << JPC_NMSEDEC_BITS];
+jpc_fix_t jpc_refnmsedec0[1 << JPC_NMSEDEC_BITS];
+
+jpc_mqctx_t jpc_mqctxs[JPC_NUMCTXS];
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+JAS_ATTRIBUTE_CONST
+static uint_least8_t jpc_getzcctxno(unsigned f, enum jpc_tsfb_orient orient);
+
+JAS_ATTRIBUTE_CONST
+static bool jpc_getspb(unsigned f);
+
+JAS_ATTRIBUTE_CONST
+static uint_least8_t jpc_getscctxno(unsigned f);
+
+JAS_ATTRIBUTE_CONST
+static uint_least8_t jpc_getmagctxno(unsigned f);
+
+static void jpc_initmqctxs(void);
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+enum jpc_passtype JPC_PASSTYPE(unsigned passno)
+{
+	unsigned passtype = -1;
+	switch (passno % 3) {
+	case 0:
+		passtype = JPC_CLNPASS;
+		break;
+	case 1:
+		passtype = JPC_SIGPASS;
+		break;
+	case 2:
+		passtype = JPC_REFPASS;
+		break;
+	default:
+		assert(0);
+		JAS_UNREACHABLE();
+	}
+	return passtype;
+}
+
+unsigned JPC_NOMINALGAIN(unsigned qmfbid, unsigned numlvls, unsigned lvlno, enum jpc_tsfb_orient orient)
+{
+	/* Avoid compiler warnings about unused parameters. */
+	(void)numlvls;
+
+	if (qmfbid == JPC_COX_INS) {
+		return 0;
+	}
+	assert(qmfbid == JPC_COX_RFT);
+	if (lvlno == 0) {
+		assert(orient == JPC_TSFB_LL);
+		return 0;
+	} else {
+		switch (orient) {
+		case JPC_TSFB_LH:
+		case JPC_TSFB_HL:
+			return 1;
+		case JPC_TSFB_HH:
+			return 2;
+		default:
+			assert(false);
+			JAS_UNREACHABLE();
+		}
+	}
+	return -1;
+}
+
+/******************************************************************************\
+* Coding pass related functions.
+\******************************************************************************/
+
+enum jpc_segtype JPC_SEGTYPE(unsigned passno, unsigned firstpassno, bool bypass)
+{
+	if (bypass) {
+		enum jpc_passtype passtype = JPC_PASSTYPE(passno);
+		if (passtype == JPC_CLNPASS) {
+			return JPC_SEG_MQ;
+		}
+		return ((passno < firstpassno + 10) ? JPC_SEG_MQ : JPC_SEG_RAW);
+	} else {
+		return JPC_SEG_MQ;
+	}
+}
+
+unsigned JPC_SEGPASSCNT(unsigned passno, unsigned firstpassno, unsigned numpasses, bool bypass, bool termall)
+{
+	unsigned ret = -1;
+
+	if (termall) {
+		ret = 1;
+	} else if (bypass) {
+		if (passno < firstpassno + 10) {
+			ret = 10 - (passno - firstpassno);
+		} else {
+			enum jpc_passtype passtype = JPC_PASSTYPE(passno);
+			switch (passtype) {
+			case JPC_SIGPASS:
+				ret = 2;
+				break;
+			case JPC_REFPASS:
+				ret = 1;
+				break;
+			case JPC_CLNPASS:
+				ret = 1;
+				break;
+			default:
+				assert(0);
+				JAS_UNREACHABLE();
+			}
+		}
+	} else {
+		ret = JPC_PREC * 3 - 2;
+	}
+	ret = JAS_MIN(ret, numpasses - passno);
+	return ret;
+}
+
+bool JPC_ISTERMINATED(unsigned passno, unsigned firstpassno, unsigned numpasses, bool termall,
+  bool lazy)
+{
+	if (passno - firstpassno == numpasses - 1) {
+		return true;
+	} else {
+		unsigned n = JPC_SEGPASSCNT(passno, firstpassno, numpasses, lazy, termall);
+		return n <= 1;
+	}
+}
+
+/******************************************************************************\
+* Lookup table code.
+\******************************************************************************/
+
+void jpc_initluts()
+{
+	float u;
+	float v;
+	float t;
+
+/* XXX - hack */
+jpc_initmqctxs();
+
+	for (unsigned orient = 0; orient < 4; ++orient) {
+		for (unsigned i = 0; i < 256; ++i) {
+			jpc_zcctxnolut[(orient << 8) | i] = jpc_getzcctxno(i, orient);
+		}
+	}
+
+	for (unsigned i = 0; i < 256; ++i) {
+		jpc_spblut[i] = jpc_getspb(i << 4);
+	}
+
+	for (unsigned i = 0; i < 256; ++i) {
+		jpc_scctxnolut[i] = jpc_getscctxno(i << 4);
+	}
+
+	for (unsigned refine = 0; refine < 2; ++refine) {
+		for (unsigned i = 0; i < 2048; ++i) {
+			jpc_magctxnolut[(refine << 11) + i] = jpc_getmagctxno((refine ? JPC_REFINE : 0) | i);
+		}
+	}
+
+	for (unsigned i = 0; i < (1 << JPC_NMSEDEC_BITS); ++i) {
+		t = i * jpc_pow2i(-JPC_NMSEDEC_FRACBITS);
+		u = t;
+		v = t - 1.5f;
+		jpc_signmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
+/* XXX - this calc is not correct */
+		jpc_signmsedec0[i] = jpc_dbltofix(floor((u * u) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
+		u = t - 1.0f;
+		if (i & (1 << (JPC_NMSEDEC_BITS - 1))) {
+			v = t - 1.5f;
+		} else {
+			v = t - 0.5f;
+		}
+		jpc_refnmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
+/* XXX - this calc is not correct */
+		jpc_refnmsedec0[i] = jpc_dbltofix(floor((u * u) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
+	}
+}
+
+static uint_least8_t jpc_getzcctxno(unsigned f, enum jpc_tsfb_orient orient)
+{
+	assert(orient < 4);
+
+	unsigned n = -1;
+	unsigned t;
+	unsigned hv;
+
+	unsigned h = ((f & JPC_WSIG) != 0) + ((f & JPC_ESIG) != 0);
+	unsigned v = ((f & JPC_NSIG) != 0) + ((f & JPC_SSIG) != 0);
+	const unsigned d = ((f & JPC_NWSIG) != 0) + ((f & JPC_NESIG) != 0) + ((f & JPC_SESIG) != 0) + ((f & JPC_SWSIG) != 0);
+	switch (orient) {
+	case JPC_TSFB_HL:
+		t = h;
+		h = v;
+		v = t;
+		/* fall through */
+	case JPC_TSFB_LL:
+	case JPC_TSFB_LH:
+		if (!h) {
+			if (!v) {
+				if (!d) {
+					n = 0;
+				} else if (d == 1) {
+					n = 1;
+				} else {
+					n = 2;
+				}
+			} else if (v == 1) {
+				n = 3;
+			} else {
+				n = 4;
+			}
+		} else if (h == 1) {
+			if (!v) {
+				if (!d) {
+					n = 5;
+				} else {
+					n = 6;
+				}
+			} else {
+				n = 7;
+			}
+		} else {
+			n = 8;
+		}
+		break;
+	case JPC_TSFB_HH:
+		hv = h + v;
+		if (!d) {
+			if (!hv) {
+				n = 0;
+			} else if (hv == 1) {
+				n = 1;
+			} else {
+				n = 2;
+			}
+		} else if (d == 1) {
+			if (!hv) {
+				n = 3;
+			} else if (hv == 1) {
+				n = 4;
+			} else {
+				n = 5;
+			}
+		} else if (d == 2) {
+			if (!hv) {
+				n = 6;
+			} else {
+				n = 7;
+			}
+		} else {
+			n = 8;
+		}
+		break;
+
+	default:
+		assert(false);
+		JAS_UNREACHABLE();
+	}
+	assert(n < JPC_NUMZCCTXS);
+	return JPC_ZCCTXNO + n;
+}
+
+static bool jpc_getspb(unsigned f)
+{
+	int hc;
+	int vc;
+	bool n;
+
+	hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG), 1) -
+	  JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) + ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1);
+	vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG), 1) -
+	  JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) + ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1);
+	if (!hc && !vc) {
+		n = 0;
+	} else {
+		n = (!(hc > 0 || (!hc && vc > 0)));
+	}
+	return n;
+}
+
+static uint_least8_t jpc_getscctxno(unsigned f)
+{
+	int hc;
+	int vc;
+
+	hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG),
+	  1) - JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) +
+	  ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1);
+	vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG),
+	  1) - JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) +
+	  ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1);
+	assert(hc >= -1 && hc <= 1 && vc >= -1 && vc <= 1);
+	if (hc < 0) {
+		hc = -hc;
+		vc = -vc;
+	}
+
+	unsigned n;
+	if (!hc) {
+		if (vc == -1) {
+			n = 1;
+		} else if (!vc) {
+			n = 0;
+		} else {
+			n = 1;
+		}
+	} else {
+		assert(hc == 1);
+
+		if (vc == -1) {
+			n = 2;
+		} else if (!vc) {
+			n = 3;
+		} else {
+			n = 4;
+		}
+	}
+	assert(n < JPC_NUMSCCTXS);
+	return JPC_SCCTXNO + n;
+}
+
+static uint_least8_t jpc_getmagctxno(unsigned f)
+{
+	unsigned n;
+
+	if (!(f & JPC_REFINE)) {
+		n = (f & (JPC_OTHSIGMSK)) ? 1 : 0;
+	} else {
+		n = 2;
+	}
+
+	assert(n < JPC_NUMMAGCTXS);
+	return JPC_MAGCTXNO + n;
+}
+
+static void jpc_initctxs(jpc_mqctx_t *ctxs)
+{
+	jpc_mqctx_t *ctx;
+
+	ctx = ctxs;
+	for (unsigned i = 0; i < JPC_NUMCTXS; ++i) {
+		ctx->mps = 0;
+		switch (i) {
+		case JPC_UCTXNO:
+			ctx->ind = 46;
+			break;
+		case JPC_ZCCTXNO:
+			ctx->ind = 4;
+			break;
+		case JPC_AGGCTXNO:
+			ctx->ind = 3;
+			break;
+		default:
+			ctx->ind = 0;
+			break;
+		}
+		++ctx;
+	}
+}
+
+static void jpc_initmqctxs()
+{
+	jpc_initctxs(jpc_mqctxs);
+}
+
+/* Calculate the real quantity exp2(n), where x is an integer. */
+static double jpc_pow2i(int n)
+{
+	double x;
+	double a;
+
+	x = 1.0;
+	if (n < 0) {
+		a = 0.5;
+		n = -n;
+	} else {
+		a = 2.0;
+	}
+	while (--n >= 0) {
+		x *= a;
+	}
+	return x;
+}
--- /dev/null
+++ b/jpc_t1cod.h
@@ -1,0 +1,319 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef JPC_T1COD_H
+#define JPC_T1COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_fix.h"
+#include "jpc_mqcod.h"
+#include "jpc_tsfb.h"
+#include "jasper/jas_math.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* The number of bits used to index into various lookup tables. */
+#define JPC_NMSEDEC_BITS	7
+#define JPC_NMSEDEC_FRACBITS	(JPC_NMSEDEC_BITS - 1)
+
+/*
+ * Segment types.
+ */
+
+enum jpc_segtype {
+	/** Invalid. */
+	JPC_SEG_INVALID,
+
+	/* MQ. */
+	JPC_SEG_MQ,
+
+	/* Raw. */
+	JPC_SEG_RAW,
+};
+
+/* The nominal word size. */
+#define	JPC_PREC	32
+
+/* Tier-1 coding pass types. */
+enum jpc_passtype {
+	JPC_SIGPASS, /*< significance */
+	JPC_REFPASS, /*< refinement */
+	JPC_CLNPASS, /*< cleanup */
+};
+
+/*
+ * Per-sample state information for tier-1 coding.
+ */
+
+/* The northeast neighbour has been found to be significant. */
+#define	JPC_NESIG	0x0001
+/* The southeast neighbour has been found to be significant. */
+#define	JPC_SESIG	0x0002
+/* The southwest neighbour has been found to be significant. */
+#define	JPC_SWSIG	0x0004
+/* The northwest neighbour has been found to be significant. */
+#define	JPC_NWSIG	0x0008
+/* The north neighbour has been found to be significant. */
+#define	JPC_NSIG	0x0010
+/* The east neighbour has been found to be significant. */
+#define	JPC_ESIG	0x0020
+/* The south neighbour has been found to be significant. */
+#define	JPC_SSIG	0x0040
+/* The west neighbour has been found to be significant. */
+#define	JPC_WSIG	0x0080
+/* The significance mask for 8-connected neighbours. */
+#define	JPC_OTHSIGMSK \
+	(JPC_NSIG | JPC_NESIG | JPC_ESIG | JPC_SESIG | JPC_SSIG | JPC_SWSIG | JPC_WSIG | JPC_NWSIG)
+/* The significance mask for 4-connected neighbours. */
+#define	JPC_PRIMSIGMSK	(JPC_NSIG | JPC_ESIG | JPC_SSIG | JPC_WSIG)
+
+/* The north neighbour is negative in value. */
+#define	JPC_NSGN	0x0100
+/* The east neighbour is negative in value. */
+#define	JPC_ESGN	0x0200
+/* The south neighbour is negative in value. */
+#define	JPC_SSGN	0x0400
+/* The west neighbour is negative in value. */
+#define	JPC_WSGN	0x0800
+/* The sign mask for 4-connected neighbours. */
+#define	JPC_SGNMSK	(JPC_NSGN | JPC_ESGN | JPC_SSGN | JPC_WSGN)
+
+/* This sample has been found to be significant. */
+#define JPC_SIG		0x1000
+/* The sample has been refined. */
+#define	JPC_REFINE	0x2000
+/* This sample has been processed during the significance pass. */
+#define	JPC_VISIT	0x4000
+
+/* The number of aggregation contexts. */
+#define	JPC_NUMAGGCTXS	1
+/* The number of zero coding contexts. */
+#define	JPC_NUMZCCTXS	9
+/* The number of magnitude contexts. */
+#define	JPC_NUMMAGCTXS	3
+/* The number of sign coding contexts. */
+#define	JPC_NUMSCCTXS	5
+/* The number of uniform contexts. */
+#define	JPC_NUMUCTXS	1
+
+/* The context ID for the first aggregation context. */
+#define	JPC_AGGCTXNO	0
+/* The context ID for the first zero coding context. */
+#define	JPC_ZCCTXNO		(JPC_AGGCTXNO + JPC_NUMAGGCTXS)
+/* The context ID for the first magnitude context. */
+#define	JPC_MAGCTXNO	(JPC_ZCCTXNO + JPC_NUMZCCTXS)
+/* The context ID for the first sign coding context. */
+#define	JPC_SCCTXNO		(JPC_MAGCTXNO + JPC_NUMMAGCTXS)
+/* The context ID for the first uniform context. */
+#define	JPC_UCTXNO		(JPC_SCCTXNO + JPC_NUMSCCTXS)
+/* The total number of contexts. */
+#define	JPC_NUMCTXS		(JPC_UCTXNO + JPC_NUMUCTXS)
+
+/******************************************************************************\
+* External data.
+\******************************************************************************/
+
+/* These lookup tables are used by various macros/functions. */
+/* Do not access these lookup tables directly. */
+extern uint_least8_t jpc_zcctxnolut[];
+extern bool jpc_spblut[];
+extern uint_least8_t jpc_scctxnolut[];
+extern uint_least8_t jpc_magctxnolut[];
+extern jpc_fix_t jpc_refnmsedec[];
+extern jpc_fix_t jpc_signmsedec[];
+extern jpc_fix_t jpc_refnmsedec0[];
+extern jpc_fix_t jpc_signmsedec0[];
+
+/* The initial settings for the MQ contexts. */
+extern jpc_mqctx_t jpc_mqctxs[];
+
+/******************************************************************************\
+* Functions and macros.
+\******************************************************************************/
+
+/* Arithmetic shift right (with ability to shift left also). */
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t JPC_ASR(jpc_fix_t x, int n)
+{
+	return n >= 0
+		? x >> n
+		: x << -n;
+}
+
+/* Get the zero coding context. */
+JAS_ATTRIBUTE_CONST
+static inline uint_least8_t JPC_GETZCCTXNO(unsigned f, enum jpc_tsfb_orient orient)
+{
+	return jpc_zcctxnolut[((unsigned)orient << 8) | (f & JPC_OTHSIGMSK)];
+}
+
+/* Get the sign prediction bit. */
+JAS_ATTRIBUTE_CONST
+static inline bool JPC_GETSPB(unsigned f)
+{
+	return jpc_spblut[(f & (JPC_PRIMSIGMSK | JPC_SGNMSK)) >> 4];
+}
+
+/* Get the sign coding context. */
+JAS_ATTRIBUTE_CONST
+static inline uint_least8_t JPC_GETSCCTXNO(unsigned f)
+{
+	return jpc_scctxnolut[(f & (JPC_PRIMSIGMSK | JPC_SGNMSK)) >> 4];
+}
+
+/* Get the magnitude context. */
+JAS_ATTRIBUTE_CONST
+static inline uint_least8_t JPC_GETMAGCTXNO(unsigned f)
+{
+	return jpc_magctxnolut[(f & JPC_OTHSIGMSK) | (((f & JPC_REFINE) != 0) << 11)];
+}
+
+/* Get the normalized MSE reduction for significance passes. */
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t JPC_GETSIGNMSEDEC(jpc_fix_t x, int bitpos)
+{
+	return bitpos > JPC_NMSEDEC_FRACBITS
+		? jpc_signmsedec[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)]
+		: jpc_signmsedec0[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)];
+}
+
+/* Get the normalized MSE reduction for refinement passes. */
+JAS_ATTRIBUTE_CONST
+static inline jpc_fix_t JPC_GETREFNMSEDEC(jpc_fix_t x, int bitpos)
+{
+	return bitpos > JPC_NMSEDEC_FRACBITS
+		? jpc_refnmsedec[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)]
+		: jpc_refnmsedec0[JPC_ASR(x, bitpos - JPC_NMSEDEC_FRACBITS) & JAS_ONES(JPC_NMSEDEC_BITS)];
+}
+
+/* Update the per-sample state information. */
+static inline void JPC_UPDATEFLAGS4(jpc_fix_t *fp, unsigned rowstep, bool s, bool vcausalflag)
+{
+	jpc_fix_t *np = fp - rowstep;
+	jpc_fix_t *sp = fp + rowstep;
+	if (vcausalflag) {
+		sp[-1] |= JPC_NESIG;
+		sp[1] |= JPC_NWSIG;
+		if (s) {
+			*sp |= JPC_NSIG | JPC_NSGN;
+			fp[-1] |= JPC_ESIG | JPC_ESGN;
+			fp[1] |= JPC_WSIG | JPC_WSGN;
+		} else {
+			*sp |= JPC_NSIG;
+			fp[-1] |= JPC_ESIG;
+			fp[1] |= JPC_WSIG;
+		}
+	} else {
+		np[-1] |= JPC_SESIG;
+		np[1] |= JPC_SWSIG;
+		sp[-1] |= JPC_NESIG;
+		sp[1] |= JPC_NWSIG;
+		if (s) {
+			*np |= JPC_SSIG | JPC_SSGN;
+			*sp |= JPC_NSIG | JPC_NSGN;
+			fp[-1] |= JPC_ESIG | JPC_ESGN;
+			fp[1] |= JPC_WSIG | JPC_WSGN;
+		} else {
+			*np |= JPC_SSIG;
+			*sp |= JPC_NSIG;
+			fp[-1] |= JPC_ESIG;
+			fp[1] |= JPC_WSIG;
+		}
+	}
+}
+
+/* Initialize the lookup tables used by the codec. */
+void jpc_initluts(void);
+
+/* Get the nominal gain associated with a particular band. */
+JAS_ATTRIBUTE_CONST
+unsigned JPC_NOMINALGAIN(unsigned qmfbid, unsigned numlvls, unsigned lvlno, enum jpc_tsfb_orient orient);
+
+/* Get the coding pass type. */
+JAS_ATTRIBUTE_CONST
+enum jpc_passtype JPC_PASSTYPE(unsigned passno);
+
+/* Get the segment type. */
+JAS_ATTRIBUTE_CONST
+enum jpc_segtype JPC_SEGTYPE(unsigned passno, unsigned firstpassno, bool bypass);
+
+/* Get the number of coding passess in the segment. */
+JAS_ATTRIBUTE_CONST
+unsigned JPC_SEGPASSCNT(unsigned passno, unsigned firstpassno, unsigned numpasses, bool bypass,
+  bool termall);
+
+/* Is the coding pass terminated? */
+JAS_ATTRIBUTE_CONST
+bool JPC_ISTERMINATED(unsigned passno, unsigned firstpassno, unsigned numpasses, bool termall,
+  bool lazy);
+
+#endif
--- /dev/null
+++ b/jpc_t1dec.c
@@ -1,0 +1,799 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 1 Decoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_t1dec.h"
+#include "jpc_bs.h"
+#include "jpc_mqdec.h"
+#include "jpc_t1cod.h"
+#include "jpc_dec.h"
+
+#include "jasper/jas_stream.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int jpc_dec_decodecblk(jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band,
+  jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs);
+static int dec_sigpass(jpc_mqdec_t *mqdec, unsigned bitpos, enum jpc_tsfb_orient orient,
+  bool vcausalflag, jas_matrix_t *flags, jas_matrix_t *data);
+static int dec_rawsigpass(jpc_bitstream_t *in, unsigned bitpos,
+  bool vcausalflag, jas_matrix_t *flags, jas_matrix_t *data);
+static int dec_refpass(jpc_mqdec_t *mqdec, unsigned bitpos,
+  jas_matrix_t *flags, jas_matrix_t *data);
+static int dec_rawrefpass(jpc_bitstream_t *in, unsigned bitpos,
+  jas_matrix_t *flags, jas_matrix_t *data);
+static int dec_clnpass(jpc_mqdec_t *mqdec, unsigned bitpos, enum jpc_tsfb_orient orient,
+  bool vcausalflag, bool segsymflag, jas_matrix_t *flags, jas_matrix_t *data);
+
+#ifndef NDEBUG
+static long t1dec_cnt = 0;
+#endif
+
+JAS_FORCE_INLINE
+static bool JPC_T1D_GETBIT(jpc_mqdec_t *mqdec, const char *passtypename, const char *symtypename)
+{
+	bool v = jpc_mqdec_getbit(mqdec);
+#ifndef NDEBUG
+	if (jas_getdbglevel() >= 100) {
+		jas_eprintf("index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v);
+		++t1dec_cnt;
+	}
+#else
+	(void)passtypename;
+	(void)symtypename;
+#endif
+	return v;
+}
+
+JAS_FORCE_INLINE
+static bool JPC_T1D_GETBITNOSKEW(jpc_mqdec_t *mqdec, const char *passtypename, const char *symtypename)
+{
+	return JPC_T1D_GETBIT(mqdec, passtypename, symtypename);
+}
+
+JAS_FORCE_INLINE
+static int JPC_T1D_RAWGETBIT(jpc_bitstream_t *bitstream, const char *passtypename, const char *symtypename)
+{
+	int v = jpc_bitstream_getbit(bitstream);
+#ifndef NDEBUG
+	if (jas_getdbglevel() >= 100) {
+		jas_eprintf("index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v);
+		++t1dec_cnt;
+	}
+#else
+	(void)passtypename;
+	(void)symtypename;
+#endif
+	return v;
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+int jpc_dec_decodecblks(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+	jpc_dec_tcomp_t *tcomp;
+	jpc_dec_rlvl_t *rlvl;
+	jpc_dec_band_t *band;
+	jpc_dec_prc_t *prc;
+	jpc_dec_cblk_t *cblk;
+
+	unsigned compcnt;
+	for (compcnt = dec->numcomps, tcomp = tile->tcomps; compcnt > 0;
+	  --compcnt, ++tcomp) {
+		unsigned rlvlcnt;
+		for (rlvlcnt = tcomp->numrlvls, rlvl = tcomp->rlvls;
+		  rlvlcnt > 0; --rlvlcnt, ++rlvl) {
+			if (!rlvl->bands) {
+				continue;
+			}
+			unsigned bandcnt;
+			for (bandcnt = rlvl->numbands, band = rlvl->bands;
+			  bandcnt > 0; --bandcnt, ++band) {
+				if (!band->data) {
+					continue;
+				}
+				unsigned prccnt;
+				for (prccnt = rlvl->numprcs, prc = band->prcs;
+				  prccnt > 0; --prccnt, ++prc) {
+					if (!prc->cblks) {
+						continue;
+					}
+					unsigned cblkcnt;
+					for (cblkcnt = prc->numcblks,
+					  cblk = prc->cblks; cblkcnt > 0;
+					  --cblkcnt, ++cblk) {
+						if (jpc_dec_decodecblk(tile, tcomp,
+						  band, cblk, 1, JPC_MAXLYRS)) {
+							return -1;
+						}
+					}
+				}
+
+			}
+		}
+	}
+
+	return 0;
+}
+
+static int jpc_dec_decodecblk(jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band,
+  jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs)
+{
+	jpc_dec_seg_t *seg;
+	int bpno;
+	int ret = -1;
+	int filldata;
+	int fillmask;
+
+	const size_t compno = tcomp - tile->tcomps;
+	const jpc_dec_ccp_t *const ccp = &tile->cp->ccps[compno];
+
+	/* The MQ decoder. */
+	jpc_mqdec_t *mqdec = NULL;
+
+	/* The raw bit stream decoder. */
+	jpc_bitstream_t *nulldec = NULL;
+
+	/* The per-sample state information for this code block. */
+	/* Note: matrix is assumed to be zeroed */
+	jas_matrix_t *const flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + 2, jas_matrix_numcols(cblk->data) + 2);
+	if (!flags)
+		goto error;
+
+	seg = cblk->segs.head;
+	while (seg && (seg != cblk->curseg || dopartial) && (maxlyrs < 0 ||
+	  seg->lyrno < (unsigned)maxlyrs)) {
+		assert(seg->numpasses >= seg->maxpasses || dopartial);
+		assert(seg->stream);
+		jas_stream_rewind(seg->stream);
+		jas_stream_setrwcount(seg->stream, 0);
+		if (seg->type == JPC_SEG_MQ) {
+			if (!mqdec) {
+				if (!(mqdec = jpc_mqdec_create(JPC_NUMCTXS, 0))) {
+					goto error;
+				}
+				jpc_mqdec_setctxs(mqdec, JPC_NUMCTXS, jpc_mqctxs);
+			}
+			jpc_mqdec_setinput(mqdec, seg->stream);
+			jpc_mqdec_init(mqdec);
+		} else {
+			assert(seg->type == JPC_SEG_RAW);
+			if (!nulldec) {
+				if (!(nulldec = jpc_bitstream_sopen(seg->stream, "r"))) {
+					goto error;
+				}
+			}
+		}
+
+
+		for (unsigned i = 0; i < seg->numpasses; ++i) {
+			if (cblk->numimsbs > band->numbps) {
+				if (ccp->roishift <= 0) {
+					jas_eprintf("warning: corrupt code stream\n");
+				} else {
+					if (cblk->numimsbs < ccp->roishift - band->numbps) {
+						jas_eprintf("warning: corrupt code stream\n");
+					}
+				}
+			}
+			bpno = band->roishift + band->numbps - 1 - (cblk->numimsbs +
+			  (seg->passno + i - cblk->firstpassno + 2) / 3);
+if (bpno < 0) {
+	goto premature_exit;
+}
+			enum jpc_passtype passtype = JPC_PASSTYPE(seg->passno + i);
+			assert(bpno >= 0 && bpno < 31);
+			switch (passtype) {
+			case JPC_SIGPASS:
+				ret = (seg->type == JPC_SEG_MQ) ? dec_sigpass(mqdec, bpno, band->orient,
+				  (ccp->cblkctx & JPC_COX_VSC) != 0,
+				  flags, cblk->data) :
+				  dec_rawsigpass(nulldec, bpno,
+				  (ccp->cblkctx & JPC_COX_VSC) != 0,
+				  flags, cblk->data);
+				break;
+			case JPC_REFPASS:
+				ret = (seg->type == JPC_SEG_MQ) ?
+				  dec_refpass(mqdec, bpno,
+				  flags, cblk->data) :
+				  dec_rawrefpass(nulldec, bpno,
+				  flags, cblk->data);
+				break;
+			case JPC_CLNPASS:
+				assert(seg->type == JPC_SEG_MQ);
+				ret = dec_clnpass(mqdec, bpno,
+				  band->orient, (ccp->cblkctx &
+				  JPC_COX_VSC) != 0, (ccp->cblkctx &
+				  JPC_COX_SEGSYM) != 0, flags,
+				  cblk->data);
+				break;
+			default:
+				assert(false);
+				JAS_UNREACHABLE();
+			}
+			/* Do we need to reset after each coding pass? */
+			if ((ccp->cblkctx & JPC_COX_RESET) && mqdec) {
+				jpc_mqdec_setctxs(mqdec, JPC_NUMCTXS, jpc_mqctxs);
+			}
+
+			if (ret) {
+				jas_eprintf("coding pass failed passtype=%d segtype=%d\n", passtype, seg->type);
+				goto error;
+			}
+
+		}
+
+		if (seg->type == JPC_SEG_MQ) {
+/* Note: dont destroy mq decoder because context info will be lost */
+		} else {
+			assert(seg->type == JPC_SEG_RAW);
+			if (ccp->cblkctx & JPC_COX_PTERM) {
+				fillmask = 0x7f;
+				filldata = 0x2a;
+			} else {
+				fillmask = 0;
+				filldata = 0;
+			}
+			if ((ret = jpc_bitstream_inalign(nulldec, fillmask,
+			  filldata)) < 0) {
+				goto error;
+			} else if (ret > 0) {
+				jas_eprintf("warning: bad termination pattern detected\n");
+			}
+			jpc_bitstream_close(nulldec);
+			nulldec = 0;
+		}
+
+		cblk->curseg = seg->next;
+		jpc_seglist_remove(&cblk->segs, seg);
+		jpc_seg_destroy(seg);
+		seg = cblk->curseg;
+	}
+
+	assert(dopartial ? (!cblk->curseg) : 1);
+
+premature_exit:
+	if (mqdec)
+		jpc_mqdec_destroy(mqdec);
+	if (nulldec)
+		jpc_bitstream_close(nulldec);
+	if (flags)
+		jas_matrix_destroy(flags);
+	return 0;
+
+error:
+	if (mqdec)
+		jpc_mqdec_destroy(mqdec);
+	if (nulldec)
+		jpc_bitstream_close(nulldec);
+	if (flags)
+		jas_matrix_destroy(flags);
+	return -1;
+}
+
+/******************************************************************************\
+* Code for significance pass.
+\******************************************************************************/
+
+JAS_FORCE_INLINE
+static void jpc_sigpass_step(jpc_fix_t *fp, size_t frowstep, jpc_fix_t *dp, jpc_fix_t oneplushalf, enum jpc_tsfb_orient orient, jpc_mqdec_t *mqdec, bool vcausalflag)
+{
+	const jpc_fix_t f = *(fp);
+	if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) {
+		jpc_mqdec_setcurctx(mqdec, JPC_GETZCCTXNO(f, orient));
+
+		if (JPC_T1D_GETBIT(mqdec, "SIG", "ZC")) {
+			jpc_mqdec_setcurctx(mqdec, JPC_GETSCCTXNO(f));
+			bool v = JPC_T1D_GETBIT(mqdec, "SIG", "SC");
+			v ^= JPC_GETSPB(f);
+			JPC_UPDATEFLAGS4(fp, frowstep, v, vcausalflag);
+			*fp |= JPC_SIG;
+			*dp = v ? -oneplushalf : oneplushalf;
+		}
+		*fp |= JPC_VISIT;
+	}
+}
+
+static int dec_sigpass(jpc_mqdec_t *mqdec, unsigned bitpos, enum jpc_tsfb_orient orient,
+  bool vcausalflag, jas_matrix_t *flags, jas_matrix_t *data)
+{
+	int i;
+	jpc_fix_t *fp;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fvscanstart;
+	jpc_fix_t *dp;
+	jpc_fix_t *dstripestart;
+	jpc_fix_t *dvscanstart;
+
+	const unsigned width = jas_matrix_numcols(data);
+	const unsigned height = jas_matrix_numrows(data);
+	const unsigned frowstep = jas_matrix_rowstep(flags);
+	const unsigned drowstep = jas_matrix_rowstep(data);
+	const unsigned fstripestep = frowstep << 2;
+	const unsigned dstripestep = drowstep << 2;
+
+	const jpc_fix_t one = (jpc_fix_t)1 << bitpos;
+	const jpc_fix_t half = one >> 1;
+	const jpc_fix_t oneplushalf = one | half;
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			dp = dvscanstart;
+			unsigned k = vscanlen;
+
+			/* Process first sample in vertical scan. */
+			jpc_sigpass_step(fp, frowstep, dp, oneplushalf,
+			  orient, mqdec, vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process second sample in vertical scan. */
+			jpc_sigpass_step(fp, frowstep, dp, oneplushalf,
+			  orient, mqdec, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process third sample in vertical scan. */
+			jpc_sigpass_step(fp, frowstep, dp, oneplushalf,
+			  orient, mqdec, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process fourth sample in vertical scan. */
+			jpc_sigpass_step(fp, frowstep, dp, oneplushalf,
+			  orient, mqdec, 0);
+		}
+	}
+	return 0;
+}
+
+JAS_FORCE_INLINE
+static int jpc_rawsigpass_step(jpc_fix_t *fp, size_t frowstep, jpc_fix_t *dp, jpc_fix_t oneplushalf, jpc_bitstream_t *in, bool vcausalflag)
+{
+	const jpc_fix_t f = *fp;
+	if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) {
+		int v = JPC_T1D_RAWGETBIT(in, "SIG", "ZC");
+		if (v < 0) {
+			return -1;
+		}
+		if (v) {
+			v = JPC_T1D_RAWGETBIT(in, "SIG", "SC");
+			if (v < 0) {
+				return -1;
+			}
+			JPC_UPDATEFLAGS4(fp, frowstep, v, vcausalflag);
+			*fp |= JPC_SIG;
+			*dp = v ? -oneplushalf : oneplushalf;
+		}
+		*fp |= JPC_VISIT;
+	}
+
+	return 0;
+}
+
+static int dec_rawsigpass(jpc_bitstream_t *in, unsigned bitpos, bool vcausalflag,
+  jas_matrix_t *flags, jas_matrix_t *data)
+{
+	int i;
+	jpc_fix_t *fp;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fvscanstart;
+	jpc_fix_t *dp;
+	jpc_fix_t *dstripestart;
+	jpc_fix_t *dvscanstart;
+
+	const unsigned width = jas_matrix_numcols(data);
+	const unsigned height = jas_matrix_numrows(data);
+	const unsigned frowstep = jas_matrix_rowstep(flags);
+	const unsigned drowstep = jas_matrix_rowstep(data);
+	const unsigned fstripestep = frowstep << 2;
+	const unsigned dstripestep = drowstep << 2;
+
+	const jpc_fix_t one = (jpc_fix_t)1 << bitpos;
+	const jpc_fix_t half = one >> 1;
+	const jpc_fix_t oneplushalf = one | half;
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			dp = dvscanstart;
+			unsigned k = vscanlen;
+
+			/* Process first sample in vertical scan. */
+			if (jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, in, vcausalflag))
+				return -1;
+
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process second sample in vertical scan. */
+			if (jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, in, 0))
+				return -1;
+
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process third sample in vertical scan. */
+			if (jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, in, 0))
+				return -1;
+
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process fourth sample in vertical scan. */
+			jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+			  in, 0);
+
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Code for refinement pass.
+\******************************************************************************/
+
+JAS_FORCE_INLINE
+static void jpc_refpass_step(jpc_fix_t *fp, jpc_fix_t *dp, jpc_fix_t poshalf, jpc_fix_t neghalf, jpc_mqdec_t *mqdec)
+{
+	if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+		jpc_mqdec_setcurctx(mqdec, JPC_GETMAGCTXNO(*fp));
+		const bool v = JPC_T1D_GETBITNOSKEW(mqdec, "REF", "MR");
+		const jpc_fix_t t = v ? poshalf : neghalf;
+		*dp += *dp < 0 ? -t : t;
+		*fp |= JPC_REFINE;
+	}
+}
+
+static int dec_refpass(jpc_mqdec_t *mqdec, unsigned bitpos,
+  jas_matrix_t *flags, jas_matrix_t *data)
+{
+	int i;
+	jpc_fix_t *fp;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fvscanstart;
+	jpc_fix_t *dp;
+	jpc_fix_t *dstripestart;
+	jpc_fix_t *dvscanstart;
+
+	const unsigned width = jas_matrix_numcols(data);
+	const unsigned height = jas_matrix_numrows(data);
+	const unsigned frowstep = jas_matrix_rowstep(flags);
+	const unsigned drowstep = jas_matrix_rowstep(data);
+	const unsigned fstripestep = frowstep << 2;
+	const unsigned dstripestep = drowstep << 2;
+
+	const jpc_fix_t one = (jpc_fix_t)1 << bitpos;
+	const jpc_fix_t poshalf = one >> 1;
+	const jpc_fix_t neghalf = bitpos > 0 ? -poshalf : -1;
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			dp = dvscanstart;
+
+			for (unsigned k = 0; k < vscanlen; ++k) {
+				jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec);
+				fp += frowstep;
+				dp += drowstep;
+			}
+		}
+	}
+
+	return 0;
+}
+
+static int jpc_rawrefpass_step(jpc_fix_t *fp, jpc_fix_t *dp, jpc_fix_t poshalf, jpc_fix_t neghalf, jpc_bitstream_t *in)
+{
+	if ((*fp & (JPC_SIG | JPC_VISIT)) == JPC_SIG) {
+		int v = JPC_T1D_RAWGETBIT(in, "REF", "MAGREF");
+		if (v < 0) {
+			return -1;
+		}
+		jpc_fix_t t = v ? poshalf : neghalf;
+		*dp += *dp < 0 ? -t : t;
+		*fp |= JPC_REFINE;
+	}
+
+	return 0;
+}
+
+static int dec_rawrefpass(jpc_bitstream_t *in, unsigned bitpos,
+  jas_matrix_t *flags, jas_matrix_t *data)
+{
+	int i;
+	jpc_fix_t *fp;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fvscanstart;
+	jpc_fix_t *dp;
+	jpc_fix_t *dstripestart;
+	jpc_fix_t *dvscanstart;
+
+	const unsigned width = jas_matrix_numcols(data);
+	const unsigned height = jas_matrix_numrows(data);
+	const unsigned frowstep = jas_matrix_rowstep(flags);
+	const unsigned drowstep = jas_matrix_rowstep(data);
+	const unsigned fstripestep = frowstep << 2;
+	const unsigned dstripestep = drowstep << 2;
+
+	const jpc_fix_t one = (jpc_fix_t)1 << bitpos;
+	const jpc_fix_t poshalf = one >> 1;
+	const jpc_fix_t neghalf = bitpos > 0 ? -poshalf : -1;
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			dp = dvscanstart;
+
+			for (unsigned k = 0; k < vscanlen; ++k) {
+				if (jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in))
+					return -1;
+				fp += frowstep;
+				dp += drowstep;
+			}
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Code for cleanup pass.
+\******************************************************************************/
+
+#define	jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, mqdec, flabel, plabel, vcausalflag) \
+{ \
+flabel \
+	if (!((f) & (JPC_SIG | JPC_VISIT))) { \
+		jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO((f), (orient))); \
+		if (JPC_T1D_GETBIT((mqdec), "CLN", "ZC")) { \
+plabel \
+			/* Coefficient is significant. */ \
+			jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \
+			bool v = JPC_T1D_GETBIT((mqdec), "CLN", "SC"); \
+			v ^= JPC_GETSPB(f); \
+			*(dp) = (v) ? (-(jpc_fix_t)(oneplushalf)) : (jpc_fix_t)(oneplushalf); \
+			JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
+			*(fp) |= JPC_SIG; \
+		} \
+	} \
+	/* XXX - Is this correct?  Can aggregation cause some VISIT bits not to be reset?  Check. */ \
+	*(fp) &= ~JPC_VISIT; \
+}
+
+static int dec_clnpass(jpc_mqdec_t *mqdec, unsigned bitpos, enum jpc_tsfb_orient orient,
+  bool vcausalflag, bool segsymflag, jas_matrix_t *flags, jas_matrix_t *data)
+{
+	int f;
+
+	jpc_fix_t *fp;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fvscanstart;
+
+	jpc_fix_t *dp;
+	jpc_fix_t *dstripestart;
+	jpc_fix_t *dvscanstart;
+
+	const jpc_fix_t one = (jpc_fix_t)1 << bitpos;
+	const jpc_fix_t half = one >> 1;
+	const jpc_fix_t oneplushalf = one | half;
+
+	const unsigned width = jas_matrix_numcols(data);
+	const unsigned height = jas_matrix_numrows(data);
+
+	const unsigned frowstep = jas_matrix_rowstep(flags);
+	const unsigned drowstep = jas_matrix_rowstep(data);
+	const unsigned fstripestep = frowstep << 2;
+	const unsigned dstripestep = drowstep << 2;
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	dstripestart = jas_matrix_getref(data, 0, 0);
+	for (unsigned i = 0; i < height; i += 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(4, height - i);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			unsigned k;
+			if (vscanlen >= 4 && (!((*fp) & (JPC_SIG | JPC_VISIT |
+			  JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) & (JPC_SIG |
+			  JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) &
+			  (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep,
+			  !((*fp) & (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK)))) {
+
+				jpc_mqdec_setcurctx(mqdec, JPC_AGGCTXNO);
+				if (!JPC_T1D_GETBIT(mqdec, "CLN", "AGG")) {
+					continue;
+				}
+				jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO);
+				unsigned runlen = JPC_T1D_GETBITNOSKEW(mqdec, "CLN", "RL");
+				runlen = (runlen << 1) | JPC_T1D_GETBITNOSKEW(mqdec, "CLN", "RL");
+				f = *(fp = fvscanstart + frowstep * runlen);
+				dp = dvscanstart + drowstep * runlen;
+				k = vscanlen - runlen;
+				switch (runlen) {
+				case 0:
+					goto clnpass_partial0;
+				case 1:
+					goto clnpass_partial1;
+				case 2:
+					goto clnpass_partial2;
+				case 3:
+					goto clnpass_partial3;
+				}
+			} else {
+				f = *(fp = fvscanstart);
+				dp = dvscanstart;
+				k = vscanlen;
+				goto clnpass_full0;
+			}
+
+			/* Process first sample in vertical scan. */
+			jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+			  mqdec, clnpass_full0:, clnpass_partial0:,
+			  vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process second sample in vertical scan. */
+			f = *fp;
+			jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+				mqdec, ;, clnpass_partial1:, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process third sample in vertical scan. */
+			f = *fp;
+			jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+				mqdec, ;, clnpass_partial2:, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			/* Process fourth sample in vertical scan. */
+			f = *fp;
+			jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+				mqdec, ;, clnpass_partial3:, 0);
+		}
+	}
+
+	if (segsymflag) {
+		unsigned segsymval = 0;
+		jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO);
+		segsymval = (segsymval << 1) | JPC_T1D_GETBITNOSKEW(mqdec, "CLN", "SEGSYM");
+		segsymval = (segsymval << 1) | JPC_T1D_GETBITNOSKEW(mqdec, "CLN", "SEGSYM");
+		segsymval = (segsymval << 1) | JPC_T1D_GETBITNOSKEW(mqdec, "CLN", "SEGSYM");
+		segsymval = (segsymval << 1) | JPC_T1D_GETBITNOSKEW(mqdec, "CLN", "SEGSYM");
+		if (segsymval != 0xa) {
+			jas_eprintf("warning: bad segmentation symbol\n");
+		}
+	}
+
+	return 0;
+}
--- /dev/null
+++ b/jpc_t1dec.h
@@ -1,0 +1,86 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 1 Decoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T1DEC_H
+#define JPC_T1DEC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_dec.h"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Decode all of the code blocks for a particular tile. */
+int jpc_dec_decodecblks(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+
+#endif
--- /dev/null
+++ b/jpc_t2cod.c
@@ -1,0 +1,702 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier-2 Coding Library
+ *
+ * $Id$
+ */
+
+#include "jpc_t2cod.h"
+#include "jpc_cs.h"
+#include "jpc_math.h"
+
+#include "jasper/jas_math.h"
+#include "jasper/jas_malloc.h"
+
+static int jpc_pi_nextlrcp(jpc_pi_t *pi);
+static int jpc_pi_nextrlcp(jpc_pi_t *pi);
+static int jpc_pi_nextrpcl(jpc_pi_t *pi);
+static int jpc_pi_nextpcrl(jpc_pi_t *pi);
+static int jpc_pi_nextcprl(jpc_pi_t *pi);
+
+int jpc_pi_next(jpc_pi_t *pi)
+{
+	int ret;
+
+	for (;;) {
+
+		pi->valid = false;
+
+		if (!pi->pchg) {
+			++pi->pchgno;
+			pi->compno = 0;
+			pi->rlvlno = 0;
+			pi->prcno = 0;
+			pi->lyrno = 0;
+			pi->prgvolfirst = true;
+			if ((unsigned)pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) {
+				pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno);
+			} else if ((unsigned)pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) {
+				pi->pchg = &pi->defaultpchg;
+			} else {
+				return 1;
+			}
+		}
+
+		const jpc_pchg_t *pchg = pi->pchg;
+		switch (pchg->prgord) {
+		case JPC_COD_LRCPPRG:
+			ret = jpc_pi_nextlrcp(pi);
+			break;
+		case JPC_COD_RLCPPRG:
+			ret = jpc_pi_nextrlcp(pi);
+			break;
+		case JPC_COD_RPCLPRG:
+			ret = jpc_pi_nextrpcl(pi);
+			break;
+		case JPC_COD_PCRLPRG:
+			ret = jpc_pi_nextpcrl(pi);
+			break;
+		case JPC_COD_CPRLPRG:
+			ret = jpc_pi_nextcprl(pi);
+			break;
+		default:
+			ret = -1;
+			break;
+		}
+		if (!ret) {
+			pi->valid = true;
+			++pi->pktno;
+			return 0;
+		}
+		pi->pchg = 0;
+	}
+}
+
+static int jpc_pi_nextlrcp(register jpc_pi_t *pi)
+{
+	unsigned *prclyrno;
+
+	const jpc_pchg_t *pchg = pi->pchg;
+	if (!pi->prgvolfirst) {
+		prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+		goto skip;
+	} else {
+		pi->prgvolfirst = false;
+	}
+
+	for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
+	  pchg->lyrnoend; ++pi->lyrno) {
+		for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
+		  pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
+			for (pi->compno = pchg->compnostart, pi->picomp =
+			  &pi->picomps[pi->compno]; pi->compno < pi->numcomps
+			  && pi->compno < pchg->compnoend; ++pi->compno,
+			  ++pi->picomp) {
+				if (pi->rlvlno >= pi->picomp->numrlvls) {
+					continue;
+				}
+				pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+				for (pi->prcno = 0, prclyrno =
+				  pi->pirlvl->prclyrnos; pi->prcno <
+				  pi->pirlvl->numprcs; ++pi->prcno,
+				  ++prclyrno) {
+					if (pi->lyrno >= *prclyrno) {
+						*prclyrno = pi->lyrno;
+						++(*prclyrno);
+						return 0;
+					}
+skip:
+					;
+				}
+			}
+		}
+	}
+	return 1;
+}
+
+static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
+{
+	unsigned *prclyrno;
+
+	const jpc_pchg_t *pchg = pi->pchg;
+	if (!pi->prgvolfirst) {
+		assert(pi->prcno < pi->pirlvl->numprcs);
+		prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+		goto skip;
+	} else {
+		pi->prgvolfirst = 0;
+	}
+
+	for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
+	  pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
+		for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
+		  pchg->lyrnoend; ++pi->lyrno) {
+			for (pi->compno = pchg->compnostart, pi->picomp =
+			  &pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
+			  pi->compno < pchg->compnoend; ++pi->compno,
+			  ++pi->picomp) {
+				if (pi->rlvlno >= pi->picomp->numrlvls) {
+					continue;
+				}
+				pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+				for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
+				  pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
+					if (pi->lyrno >= *prclyrno) {
+						*prclyrno = pi->lyrno;
+						++(*prclyrno);
+						return 0;
+					}
+skip:
+					;
+				}
+			}
+		}
+	}
+	return 1;
+}
+
+static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
+{
+	unsigned rlvlno;
+	unsigned *prclyrno;
+	unsigned compno;
+	unsigned xstep;
+	unsigned ystep;
+	uint_fast32_t r;
+	uint_fast32_t rpx;
+	uint_fast32_t rpy;
+	uint_fast32_t trx0;
+	uint_fast32_t try0;
+
+	const jpc_pchg_t *pchg = pi->pchg;
+	if (!pi->prgvolfirst) {
+		goto skip;
+	} else {
+		pi->xstep = 0;
+		pi->ystep = 0;
+		const jpc_picomp_t *picomp;
+		for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
+		  ++compno, ++picomp) {
+			const jpc_pirlvl_t *pirlvl;
+			for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
+			  picomp->numrlvls; ++rlvlno, ++pirlvl) {
+				// Check for the potential for overflow problems.
+				if (pirlvl->prcwidthexpn + picomp->numrlvls >
+				  JAS_UINTFAST32_NUMBITS - 2 ||
+				  pirlvl->prcheightexpn + picomp->numrlvls >
+				  JAS_UINTFAST32_NUMBITS - 2) {
+					return -1;
+				}
+				xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
+				  (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
+				ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
+				  (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
+				pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
+				pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
+			}
+		}
+		pi->prgvolfirst = 0;
+	}
+
+	if (pi->xstep == 0 || pi->ystep == 0)
+		/* avoid division by zero */
+		return -1;
+
+	for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
+	  pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
+		for (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=
+		  pi->ystep - (pi->y % pi->ystep)) {
+			for (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=
+			  pi->xstep - (pi->x % pi->xstep)) {
+				for (pi->compno = pchg->compnostart,
+				  pi->picomp = &pi->picomps[pi->compno];
+				  pi->compno < pchg->compnoend && pi->compno <
+				  pi->numcomps; ++pi->compno, ++pi->picomp) {
+					if (pi->rlvlno >= pi->picomp->numrlvls) {
+						continue;
+					}
+					pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+					if (pi->pirlvl->numprcs == 0) {
+						continue;
+					}
+					r = pi->picomp->numrlvls - 1 - pi->rlvlno;
+					rpx = r + pi->pirlvl->prcwidthexpn;
+					rpy = r + pi->pirlvl->prcheightexpn;
+					trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
+					try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
+					if (((pi->x == pi->xstart &&
+					  ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))
+					  || !(pi->x % (pi->picomp->hsamp << rpx))) &&
+					  ((pi->y == pi->ystart &&
+					  ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))
+					  || !(pi->y % (pi->picomp->vsamp << rpy)))) {
+						const unsigned prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
+						  pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
+						  JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
+						const unsigned prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
+						  pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
+						  JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
+						pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
+						if (pi->prcno >= pi->pirlvl->numprcs) {
+							return -1;
+						}
+
+						for (pi->lyrno = 0; pi->lyrno <
+						  pi->numlyrs && pi->lyrno < pchg->lyrnoend; ++pi->lyrno) {
+							prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+							if (pi->lyrno >= *prclyrno) {
+								++(*prclyrno);
+								return 0;
+							}
+skip:
+							;
+						}
+					}
+				}
+			}
+		}
+	}
+	return 1;
+}
+
+static int jpc_pi_nextpcrl(register jpc_pi_t *pi)
+{
+	unsigned rlvlno;
+	unsigned *prclyrno;
+	unsigned compno;
+	unsigned xstep;
+	unsigned ystep;
+	uint_fast32_t trx0;
+	uint_fast32_t try0;
+	uint_fast32_t r;
+	uint_fast32_t rpx;
+	uint_fast32_t rpy;
+
+	const jpc_pchg_t *pchg = pi->pchg;
+	if (!pi->prgvolfirst) {
+		goto skip;
+	} else {
+		pi->xstep = 0;
+		pi->ystep = 0;
+		const jpc_picomp_t *picomp;
+		for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
+		  ++compno, ++picomp) {
+			const jpc_pirlvl_t *pirlvl;
+			for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
+			  picomp->numrlvls; ++rlvlno, ++pirlvl) {
+				// Check for the potential for overflow problems.
+				if (pirlvl->prcwidthexpn + picomp->numrlvls >
+				  JAS_UINTFAST32_NUMBITS - 2 ||
+				  pirlvl->prcheightexpn + picomp->numrlvls >
+				  JAS_UINTFAST32_NUMBITS - 2) {
+					return -1;
+				}
+				xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
+				  (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));
+				ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
+				  (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));
+				pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
+				pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
+			}
+		}
+		pi->prgvolfirst = 0;
+	}
+
+	if (pi->xstep == 0 || pi->ystep == 0)
+		/* avoid division by zero */
+		return -1;
+
+	for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep -
+	  (pi->y % pi->ystep)) {
+		for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep -
+		  (pi->x % pi->xstep)) {
+			for (pi->compno = pchg->compnostart, pi->picomp =
+			  &pi->picomps[pi->compno]; pi->compno < pi->numcomps
+			  && pi->compno < pchg->compnoend; ++pi->compno,
+			  ++pi->picomp) {
+				for (pi->rlvlno = pchg->rlvlnostart,
+				  pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+				  pi->rlvlno < pi->picomp->numrlvls &&
+				  pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno,
+				  ++pi->pirlvl) {
+					if (pi->pirlvl->numprcs == 0) {
+						continue;
+					}
+					r = pi->picomp->numrlvls - 1 - pi->rlvlno;
+					trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
+					try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
+					rpx = r + pi->pirlvl->prcwidthexpn;
+					rpy = r + pi->pirlvl->prcheightexpn;
+					if (((pi->x == pi->xstart &&
+					  ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) ||
+					  !(pi->x % (pi->picomp->hsamp << rpx))) &&
+					  ((pi->y == pi->ystart &&
+					  ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) ||
+					  !(pi->y % (pi->picomp->vsamp << rpy)))) {
+						const unsigned prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
+						  pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
+						  JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
+						const unsigned prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
+						  pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
+						  JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
+						pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
+						assert(pi->prcno < pi->pirlvl->numprcs);
+						for (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&
+						  pi->lyrno < pchg->lyrnoend;
+						  ++pi->lyrno) {
+							prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+							if (pi->lyrno >= *prclyrno) {
+								++(*prclyrno);
+								return 0;
+							}
+skip:
+							;
+						}
+					}
+				}
+			}
+		}
+	}
+	return 1;
+}
+
+static int jpc_pi_nextcprl(register jpc_pi_t *pi)
+{
+	unsigned rlvlno;
+	unsigned *prclyrno;
+	uint_fast32_t trx0;
+	uint_fast32_t try0;
+	uint_fast32_t r;
+	uint_fast32_t rpx;
+	uint_fast32_t rpy;
+
+	const jpc_pchg_t *pchg = pi->pchg;
+	if (!pi->prgvolfirst) {
+		goto skip;
+	} else {
+		pi->prgvolfirst = 0;
+	}
+
+	if (pi->xstep == 0 || pi->ystep == 0)
+		/* avoid division by zero */
+		return -1;
+
+	for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno];
+	  pi->compno < pchg->compnoend && pi->compno < pi->numcomps;
+	  ++pi->compno, ++pi->picomp) {
+		const jpc_pirlvl_t *pirlvl = pi->picomp->pirlvls;
+		// Check for the potential for overflow problems.
+		if (pirlvl->prcwidthexpn + pi->picomp->numrlvls >
+		  JAS_UINTFAST32_NUMBITS - 2 ||
+		  pirlvl->prcheightexpn + pi->picomp->numrlvls >
+		  JAS_UINTFAST32_NUMBITS - 2) {
+			return -1;
+		}
+		pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
+		  (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
+		pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
+		  (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
+		for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
+		  rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
+			pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
+			  (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
+			  pi->picomp->numrlvls - rlvlno - 1)));
+			pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
+			  (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
+			  pi->picomp->numrlvls - rlvlno - 1)));
+		}
+		for (pi->y = pi->ystart; pi->y < pi->yend;
+		  pi->y += pi->ystep - (pi->y % pi->ystep)) {
+			for (pi->x = pi->xstart; pi->x < pi->xend;
+			  pi->x += pi->xstep - (pi->x % pi->xstep)) {
+				for (pi->rlvlno = pchg->rlvlnostart,
+				  pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+				  pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
+				  pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
+					if (pi->pirlvl->numprcs == 0) {
+						continue;
+					}
+					r = pi->picomp->numrlvls - 1 - pi->rlvlno;
+					trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
+					try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
+					rpx = r + pi->pirlvl->prcwidthexpn;
+					rpy = r + pi->pirlvl->prcheightexpn;
+					if (((pi->x == pi->xstart &&
+					  ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) ||
+					  !(pi->x % (pi->picomp->hsamp << rpx))) &&
+					  ((pi->y == pi->ystart &&
+					  ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) ||
+					  !(pi->y % (pi->picomp->vsamp << rpy)))) {
+						const unsigned prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
+						  pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
+						  JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
+						const unsigned prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
+						  pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
+						  JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
+						pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
+						assert(pi->prcno < pi->pirlvl->numprcs);
+						for (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&
+						  pi->lyrno < pchg->lyrnoend;
+						  ++pi->lyrno) {
+							prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+							if (pi->lyrno >= *prclyrno) {
+								++(*prclyrno);
+								return 0;
+							}
+skip:
+							;
+						}
+					}
+				}
+			}
+		}
+	}
+	return 1;
+}
+
+static void pirlvl_destroy(jpc_pirlvl_t *rlvl)
+{
+	if (rlvl->prclyrnos) {
+		jas_free(rlvl->prclyrnos);
+	}
+}
+
+static void jpc_picomp_destroy(jpc_picomp_t *picomp)
+{
+	unsigned rlvlno;
+	jpc_pirlvl_t *pirlvl;
+	if (picomp->pirlvls) {
+		for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
+		  picomp->numrlvls; ++rlvlno, ++pirlvl) {
+			pirlvl_destroy(pirlvl);
+		}
+		jas_free(picomp->pirlvls);
+	}
+}
+
+void jpc_pi_destroy(jpc_pi_t *pi)
+{
+	jpc_picomp_t *picomp;
+	unsigned compno;
+	if (pi->picomps) {
+		for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
+		  ++compno, ++picomp) {
+			jpc_picomp_destroy(picomp);
+		}
+		jas_free(pi->picomps);
+	}
+	if (pi->pchglist) {
+		jpc_pchglist_destroy(pi->pchglist);
+	}
+	jas_free(pi);
+}
+
+jpc_pi_t *jpc_pi_create0()
+{
+	jpc_pi_t *pi;
+	if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) {
+		return 0;
+	}
+	pi->picomps = 0;
+	pi->pchgno = 0;
+	if (!(pi->pchglist = jpc_pchglist_create())) {
+		jas_free(pi);
+		return 0;
+	}
+	return pi;
+}
+
+int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg)
+{
+	return jpc_pchglist_insert(pi->pchglist, -1, pchg);
+}
+
+jpc_pchglist_t *jpc_pchglist_create()
+{
+	jpc_pchglist_t *pchglist;
+	if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) {
+		return 0;
+	}
+	pchglist->numpchgs = 0;
+	pchglist->maxpchgs = 0;
+	pchglist->pchgs = 0;
+	return pchglist;
+}
+
+int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg)
+{
+	jpc_pchg_t **newpchgs;
+	if (pchgno < 0) {
+		pchgno = pchglist->numpchgs;
+	}
+	if (pchglist->numpchgs >= pchglist->maxpchgs) {
+		const unsigned newmaxpchgs = pchglist->maxpchgs + 128;
+		if (!(newpchgs = jas_realloc2(pchglist->pchgs, newmaxpchgs,
+		  sizeof(jpc_pchg_t *)))) {
+			return -1;
+		}
+		pchglist->maxpchgs = newmaxpchgs;
+		pchglist->pchgs = newpchgs;
+	}
+	for (unsigned i = pchglist->numpchgs; i > (unsigned)pchgno; --i) {
+		pchglist->pchgs[i] = pchglist->pchgs[i - 1];
+	}
+	pchglist->pchgs[pchgno] = pchg;
+	++pchglist->numpchgs;
+	return 0;
+}
+
+jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, unsigned pchgno)
+{
+	jpc_pchg_t *pchg;
+	assert(pchgno < pchglist->numpchgs);
+	pchg = pchglist->pchgs[pchgno];
+	for (unsigned i = pchgno + 1; i < pchglist->numpchgs; ++i) {
+		pchglist->pchgs[i - 1] = pchglist->pchgs[i];
+	}
+	--pchglist->numpchgs;
+	return pchg;
+}
+
+jpc_pchg_t *jpc_pchg_copy(const jpc_pchg_t *pchg)
+{
+	jpc_pchg_t *newpchg;
+	if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) {
+		return 0;
+	}
+	*newpchg = *pchg;
+	return newpchg;
+}
+
+jpc_pchglist_t *jpc_pchglist_copy(const jpc_pchglist_t *pchglist)
+{
+	jpc_pchglist_t *newpchglist;
+	jpc_pchg_t *newpchg;
+	if (!(newpchglist = jpc_pchglist_create())) {
+		return 0;
+	}
+	for (unsigned pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) {
+		if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) ||
+		  jpc_pchglist_insert(newpchglist, -1, newpchg)) {
+			jpc_pchglist_destroy(newpchglist);
+			return 0;
+		}
+	}
+	return newpchglist;
+}
+
+void jpc_pchglist_destroy(jpc_pchglist_t *pchglist)
+{
+	if (pchglist->pchgs) {
+		for (unsigned pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) {
+			jpc_pchg_destroy(pchglist->pchgs[pchgno]);
+		}
+		jas_free(pchglist->pchgs);
+	}
+	jas_free(pchglist);
+}
+
+void jpc_pchg_destroy(jpc_pchg_t *pchg)
+{
+	jas_free(pchg);
+}
+
+const jpc_pchg_t *jpc_pchglist_get(const jpc_pchglist_t *pchglist, unsigned pchgno)
+{
+	return pchglist->pchgs[pchgno];
+}
+
+unsigned jpc_pchglist_numpchgs(const jpc_pchglist_t *pchglist)
+{
+	return pchglist->numpchgs;
+}
+
+int jpc_pi_init(jpc_pi_t *pi)
+{
+	unsigned compno;
+	unsigned rlvlno;
+	unsigned prcno;
+	unsigned *prclyrno;
+
+	pi->prgvolfirst = 0;
+	pi->valid = 0;
+	pi->pktno = -1;
+	pi->pchgno = -1;
+	pi->pchg = 0;
+
+	const jpc_picomp_t *picomp;
+	for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
+	  ++compno, ++picomp) {
+		const jpc_pirlvl_t *pirlvl;
+		for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
+		  picomp->numrlvls; ++rlvlno, ++pirlvl) {
+			for (prcno = 0, prclyrno = pirlvl->prclyrnos;
+			  prcno < pirlvl->numprcs; ++prcno, ++prclyrno) {
+				*prclyrno = 0;
+			}
+		}
+	}
+	return 0;
+}
--- /dev/null
+++ b/jpc_t2cod.h
@@ -1,0 +1,301 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier-2 Coding Library
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T2COD_H
+#define	JPC_T2COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_cs.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Progression change list. */
+
+typedef struct {
+
+	/* The number of progression changes. */
+	unsigned numpchgs;
+
+	/* The maximum number of progression changes that can be accomodated
+	  without growing the progression change array. */
+	unsigned maxpchgs;
+
+	/* The progression changes. */
+	jpc_pchg_t **pchgs;
+
+} jpc_pchglist_t;
+
+/* Packet iterator per-resolution-level information. */
+
+typedef struct {
+
+	/* The number of precincts. */
+	unsigned numprcs;
+
+	/* The last layer processed for each precinct. */
+	unsigned *prclyrnos;
+
+	/* The precinct width exponent. */
+	unsigned prcwidthexpn;
+
+	/* The precinct height exponent. */
+	unsigned prcheightexpn;
+
+	/* The number of precincts spanning the resolution level in the horizontal
+	  direction. */
+	unsigned numhprcs;
+
+} jpc_pirlvl_t;
+
+/* Packet iterator per-component information. */
+
+typedef struct {
+
+	/* The number of resolution levels. */
+	unsigned numrlvls;
+
+	/* The per-resolution-level information. */
+	jpc_pirlvl_t *pirlvls;
+
+	/* The horizontal sampling period. */
+	uint_fast32_t hsamp;
+
+	/* The vertical sampling period. */
+	uint_fast32_t vsamp;
+
+} jpc_picomp_t;
+
+/* Packet iterator class. */
+
+typedef struct {
+
+	/* The number of layers. */
+	unsigned numlyrs;
+
+	/* The number of resolution levels. */
+	unsigned maxrlvls;
+
+	/* The number of components. */
+	unsigned numcomps;
+
+	/* The per-component information. */
+	jpc_picomp_t *picomps;
+
+	/* The current component. */
+	jpc_picomp_t *picomp;
+
+	/* The current resolution level. */
+	jpc_pirlvl_t *pirlvl;
+
+	/* The number of the current component. */
+	unsigned compno;
+
+	/* The number of the current resolution level. */
+	unsigned rlvlno;
+
+	/* The number of the current precinct. */
+	unsigned prcno;
+
+	/* The number of the current layer. */
+	unsigned lyrno;
+
+	/* The x-coordinate of the current position. */
+	uint_fast32_t x;
+
+	/* The y-coordinate of the current position. */
+	uint_fast32_t y;
+
+	/* The horizontal step size. */
+	uint_fast32_t xstep;
+
+	/* The vertical step size. */
+	uint_fast32_t ystep;
+
+	/* The x-coordinate of the top-left corner of the tile on the reference
+	  grid. */
+	uint_fast32_t xstart;
+
+	/* The y-coordinate of the top-left corner of the tile on the reference
+	  grid. */
+	uint_fast32_t ystart;
+
+	/* The x-coordinate of the bottom-right corner of the tile on the
+	  reference grid (plus one). */
+	uint_fast32_t xend;
+
+	/* The y-coordinate of the bottom-right corner of the tile on the
+	  reference grid (plus one). */
+	uint_fast32_t yend;
+
+	/* The current progression change. */
+	const jpc_pchg_t *pchg;
+
+	/* The progression change list. */
+	jpc_pchglist_t *pchglist;
+
+	/* The progression to use in the absense of explicit specification. */
+	jpc_pchg_t defaultpchg;
+
+	/* The current progression change number. */
+	int pchgno;
+
+	/* Is this the first time in the current progression volume? */
+	bool prgvolfirst;
+
+	/* Is the current iterator value valid? */
+	bool valid;
+
+	/* The current packet number. */
+	int pktno;
+
+} jpc_pi_t;
+
+/******************************************************************************\
+* Functions/macros for packet iterators.
+\******************************************************************************/
+
+/* Create a packet iterator. */
+jpc_pi_t *jpc_pi_create0(void);
+
+/* Destroy a packet iterator. */
+void jpc_pi_destroy(jpc_pi_t *pi);
+
+/* Add a progression change to a packet iterator. */
+int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg);
+
+/* Prepare a packet iterator for iteration. */
+int jpc_pi_init(jpc_pi_t *pi);
+
+/* Set the iterator to the first packet. */
+int jpc_pi_begin(jpc_pi_t *pi);
+
+/* Proceed to the next packet in sequence. */
+int jpc_pi_next(jpc_pi_t *pi);
+
+/* Get the index of the current packet. */
+#define	jpc_pi_getind(pi)	((pi)->pktno)
+
+/* Get the component number of the current packet. */
+#define jpc_pi_cmptno(pi)	((pi)->compno)
+
+/* Get the resolution level of the current packet. */
+#define jpc_pi_rlvlno(pi)	((pi)->rlvlno)
+
+/* Get the layer number of the current packet. */
+#define jpc_pi_lyrno(pi)	((pi)->lyrno)
+
+/* Get the precinct number of the current packet. */
+#define jpc_pi_prcno(pi)	((pi)->prcno)
+
+/* Get the progression order for the current packet. */
+#define jpc_pi_prg(pi)	((pi)->pchg->prgord)
+
+/******************************************************************************\
+* Functions/macros for progression change lists.
+\******************************************************************************/
+
+/* Create a progression change list. */
+jpc_pchglist_t *jpc_pchglist_create(void);
+
+/* Destroy a progression change list. */
+void jpc_pchglist_destroy(jpc_pchglist_t *pchglist);
+
+/* Insert a new element into a progression change list. */
+int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg);
+
+/* Remove an element from a progression change list. */
+jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, unsigned pchgno);
+
+/* Get an element from a progression change list. */
+JAS_ATTRIBUTE_PURE
+const jpc_pchg_t *jpc_pchglist_get(const jpc_pchglist_t *pchglist, unsigned pchgno);
+
+/* Copy a progression change list. */
+jpc_pchglist_t *jpc_pchglist_copy(const jpc_pchglist_t *pchglist);
+
+/* Get the number of elements in a progression change list. */
+JAS_ATTRIBUTE_PURE
+unsigned jpc_pchglist_numpchgs(const jpc_pchglist_t *pchglist);
+
+/******************************************************************************\
+* Functions/macros for progression changes.
+\******************************************************************************/
+
+/* Destroy a progression change. */
+void jpc_pchg_destroy(jpc_pchg_t *pchg);
+
+/* Copy a progression change. */
+jpc_pchg_t *jpc_pchg_copy(const jpc_pchg_t *pchg);
+
+#endif
--- /dev/null
+++ b/jpc_t2dec.c
@@ -1,0 +1,603 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 2 Decoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_t2dec.h"
+#include "jpc_bs.h"
+#include "jpc_dec.h"
+#include "jpc_cs.h"
+#include "jpc_t1cod.h"
+#include "jpc_math.h"
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static long jpc_dec_lookahead(jas_stream_t *in);
+static int jpc_getcommacode(jpc_bitstream_t *in);
+static int jpc_getnumnewpasses(jpc_bitstream_t *in);
+static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int lvlno,
+  int prcno, unsigned lyrno);
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+static int jpc_getcommacode(jpc_bitstream_t *in)
+{
+	int n;
+	int v;
+
+	n = 0;
+	for (;;) {
+		if ((v = jpc_bitstream_getbit(in)) < 0) {
+			return -1;
+		}
+		if (jpc_bitstream_eof(in)) {
+			return -1;
+		}
+		if (!v) {
+			break;
+		}
+		++n;
+	}
+
+	return n;
+}
+
+static int jpc_getnumnewpasses(jpc_bitstream_t *in)
+{
+	int n;
+
+	if ((n = jpc_bitstream_getbit(in)) > 0) {
+		if ((n = jpc_bitstream_getbit(in)) > 0) {
+			if ((n = jpc_bitstream_getbits(in, 2)) == 3) {
+				if ((n = jpc_bitstream_getbits(in, 5)) == 31) {
+					if ((n = jpc_bitstream_getbits(in, 7)) >= 0) {
+						n += 36 + 1;
+					}
+				} else if (n >= 0) {
+					n += 5 + 1;
+				}
+			} else if (n >= 0) {
+				n += 2 + 1;
+			}
+		} else if (!n) {
+			n += 2;
+		}
+	} else if (!n) {
+		++n;
+	}
+
+	return n;
+}
+
+static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,
+  int prcno, unsigned lyrno)
+{
+	jpc_bitstream_t *inb;
+	jpc_dec_tcomp_t *tcomp;
+	jpc_dec_rlvl_t *rlvl;
+	jpc_dec_band_t *band;
+	jpc_dec_cblk_t *cblk;
+	int m;
+	jpc_tagtreenode_t *leaf;
+	int included;
+	int ret;
+	int numnewpasses;
+	jpc_dec_seg_t *seg;
+	int len;
+	int present;
+	jpc_ms_t *ms;
+	jpc_dec_tile_t *tile;
+	jpc_dec_ccp_t *ccp;
+	jpc_dec_cp_t *cp;
+	jpc_dec_prc_t *prc;
+	uint_fast32_t bodylen;
+	bool discard;
+
+	/* Avoid compiler warning about possible use of uninitialized
+	  variable. */
+	bodylen = 0;
+
+	discard = (lyrno >= dec->maxlyrs);
+
+	tile = dec->curtile;
+	cp = tile->cp;
+	ccp = &cp->ccps[compno];
+
+	/*
+	 * Decode the packet header.
+	 */
+
+	/* Decode the SOP marker segment if present. */
+	if (cp->csty & JPC_COD_SOP) {
+		if (jpc_dec_lookahead(in) == JPC_MS_SOP) {
+			if (!(ms = jpc_getms(in, dec->cstate))) {
+				return -1;
+			}
+			if (jpc_ms_gettype(ms) != JPC_MS_SOP) {
+				jpc_ms_destroy(ms);
+				jas_eprintf("cannot get (SOP) marker segment\n");
+				return -1;
+			}
+			unsigned int maxNsop = 65536;
+			/* checking the packet sequence number */
+			if (tile->pi->pktno % maxNsop != ms->parms.sop.seqno) {
+				jas_eprintf("incorrect packet sequence number %d was found, but expected %d\n",
+					ms->parms.sop.seqno, tile->pi->pktno % maxNsop);
+				jpc_ms_destroy(ms);
+				return -1;
+			}
+			jpc_ms_destroy(ms);
+		}
+	}
+
+	const uint_least64_t hdroffstart = jas_stream_getrwcount(pkthdrstream);
+
+	if (!(inb = jpc_bitstream_sopen(pkthdrstream, "r"))) {
+		return -1;
+	}
+
+	if ((present = jpc_bitstream_getbit(inb)) < 0) {
+		jpc_bitstream_close(inb);
+		return 1;
+	}
+	JAS_DBGLOG(10, ("\n", present));
+	JAS_DBGLOG(10, ("present=%d ", present));
+
+	/* Is the packet non-empty? */
+	if (present) {
+		/* The packet is non-empty. */
+		tcomp = &tile->tcomps[compno];
+		rlvl = &tcomp->rlvls[rlvlno];
+		bodylen = 0;
+		unsigned bandno;
+		for (bandno = 0, band = rlvl->bands; bandno < (unsigned)rlvl->numbands;
+		  ++bandno, ++band) {
+			if (!band->data) {
+				continue;
+			}
+			prc = &band->prcs[prcno];
+			if (!prc->cblks) {
+				continue;
+			}
+			unsigned cblkno;
+			unsigned usedcblkcnt = 0;
+			for (cblkno = 0, cblk = prc->cblks; cblkno < (unsigned)prc->numcblks;
+			  ++cblkno, ++cblk) {
+				++usedcblkcnt;
+				if (!cblk->numpasses) {
+					leaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);
+					if ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {
+						jpc_bitstream_close(inb);
+						return -1;
+					}
+				} else {
+					if ((included = jpc_bitstream_getbit(inb)) < 0) {
+						jpc_bitstream_close(inb);
+						return -1;
+					}
+				}
+				JAS_DBGLOG(10, ("\n"));
+				JAS_DBGLOG(10, ("included=%d ", included));
+				if (!included) {
+					continue;
+				}
+				if (!cblk->numpasses) {
+					unsigned i = 1;
+					leaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);
+					for (;;) {
+						if ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {
+							jpc_bitstream_close(inb);
+							return -1;
+						}
+						if (ret) {
+							break;
+						}
+						++i;
+					}
+					cblk->numimsbs = i - 1;
+					cblk->firstpassno = cblk->numimsbs * 3;
+				}
+				if ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {
+					jpc_bitstream_close(inb);
+					return -1;
+				}
+				JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses));
+				seg = cblk->curseg;
+				const unsigned savenumnewpasses = numnewpasses;
+				unsigned mycounter = 0;
+				if (numnewpasses > 0) {
+					if (cblk->firstpassno > 10000) {
+						/* workaround for
+						   CVE-2016-9398: this
+						   large value would
+						   make
+						   JPC_SEGPASSCNT()
+						   return a negative
+						   value, causing an
+						   assertion failure
+						   in
+						   jpc_floorlog2() */
+						jpc_bitstream_close(inb);
+						return -1;
+					}
+					if ((m = jpc_getcommacode(inb)) < 0) {
+						jpc_bitstream_close(inb);
+						return -1;
+					}
+					cblk->numlenbits += m;
+					JAS_DBGLOG(10, ("increment=%d ", m));
+					while (numnewpasses > 0) {
+						const unsigned passno = cblk->firstpassno + cblk->numpasses + mycounter;
+						if (passno >= 10000) {
+							/* with this value,
+							   JPC_SEGPASSCNT()
+							   would return 0,
+							   which is an illegal
+							   value and would
+							   later crash in
+							   jpc_floorlog2() */
+							jpc_bitstream_close(inb);
+							return -1;
+						}
+	/* XXX - the maxpasses is not set precisely but this doesn't matter... */
+						const unsigned maxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0);
+						if (!discard && !seg) {
+							if (!(seg = jpc_seg_alloc())) {
+								jpc_bitstream_close(inb);
+								return -1;
+							}
+							jpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);
+							if (!cblk->curseg) {
+								cblk->curseg = seg;
+							}
+							seg->passno = passno;
+							seg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);
+							seg->maxpasses = maxpasses;
+						}
+						const unsigned n = JAS_MIN((unsigned)numnewpasses, maxpasses);
+						mycounter += n;
+						numnewpasses -= n;
+						if ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {
+							jpc_bitstream_close(inb);
+							return -1;
+						}
+						JAS_DBGLOG(10, ("len=%d ", len));
+						if (!discard) {
+							seg->lyrno = lyrno;
+							seg->numpasses += n;
+							seg->cnt = len;
+							seg = seg->next;
+						}
+						bodylen += len;
+					}
+				}
+				cblk->numpasses += savenumnewpasses;
+			}
+		}
+
+		jpc_bitstream_inalign(inb, 0, 0);
+
+	} else {
+		if (jpc_bitstream_inalign(inb, 0x7f, 0)) {
+			jas_eprintf("alignment failed\n");
+			jpc_bitstream_close(inb);
+			return -1;
+		}
+	}
+	jpc_bitstream_close(inb);
+
+	if (jas_getdbglevel() >= 5) {
+		const uint_least64_t hdroffend = jas_stream_getrwcount(pkthdrstream);
+		const unsigned long hdrlen = hdroffend - hdroffstart;
+		jas_eprintf("hdrlen=%lu bodylen=%lu \n", (unsigned long) hdrlen,
+		  (unsigned long) bodylen);
+	}
+
+	if (cp->csty & JPC_COD_EPH) {
+		if (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {
+			jas_eprintf("cannot get (EPH) marker segment\n");
+			return -1;
+		}
+		if (jpc_ms_gettype(ms) != JPC_MS_EPH) {
+			jpc_ms_destroy(ms);
+			jas_eprintf("missing EPH marker segment\n");
+			return -1;
+		}
+		jpc_ms_destroy(ms);
+	}
+
+	/* decode the packet body. */
+
+	if (jas_getdbglevel() >= 1) {
+		jas_eprintf("packet body offset=%06ld\n", (long) jas_stream_getrwcount(in));
+	}
+
+	if (!discard) {
+		tcomp = &tile->tcomps[compno];
+		rlvl = &tcomp->rlvls[rlvlno];
+		unsigned bandno;
+		for (bandno = 0, band = rlvl->bands; bandno < (unsigned)rlvl->numbands;
+		  ++bandno, ++band) {
+			if (!band->data) {
+				continue;
+			}
+			prc = &band->prcs[prcno];
+			if (!prc->cblks) {
+				continue;
+			}
+			unsigned cblkno;
+			for (cblkno = 0, cblk = prc->cblks; cblkno < (unsigned)prc->numcblks;
+			  ++cblkno, ++cblk) {
+				seg = cblk->curseg;
+				while (seg) {
+					if (!seg->stream) {
+						if (!(seg->stream = jas_stream_memopen(0, 0))) {
+							return -1;
+						}
+					}
+#if 0
+jas_eprintf("lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\n", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);
+#endif
+					if (seg->cnt > 0) {
+						if (jpc_getdata(in, seg->stream, seg->cnt) < 0) {
+							return -1;
+						}
+						seg->cnt = 0;
+					}
+					if (seg->numpasses >= seg->maxpasses) {
+						cblk->curseg = seg->next;
+					}
+					seg = seg->next;
+				}
+			}
+		}
+	} else {
+		if (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {
+			return -1;
+		}
+	}
+	return 0;
+}
+
+/********************************************************************************************/
+/********************************************************************************************/
+
+int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
+{
+	jpc_dec_tile_t *tile;
+	jpc_pi_t *pi;
+	int ret;
+
+	tile = dec->curtile;
+	pi = tile->pi;
+	for (;;) {
+		if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
+			switch (jpc_dec_lookahead(in)) {
+			case JPC_MS_EOC:
+			case JPC_MS_SOT:
+				return 0;
+			case JPC_MS_SOP:
+			case JPC_MS_EPH:
+			case 0:
+				break;
+			default:
+				return -1;
+			}
+		}
+		if ((ret = jpc_pi_next(pi))) {
+			return ret;
+		}
+		if (dec->maxpkts >= 0 && dec->numpkts >= (unsigned)dec->maxpkts) {
+			jas_eprintf("warning: stopping decode prematurely as requested\n");
+			return 0;
+		}
+		if (jas_getdbglevel() >= 1) {
+			jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
+			  "rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
+			  jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
+			  jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
+		}
+		if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi),
+		  jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
+			return -1;
+		}
+		++dec->numpkts;
+	}
+}
+
+jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+	jpc_pi_t *pi;
+	unsigned compno;
+	jpc_picomp_t *picomp;
+	jpc_pirlvl_t *pirlvl;
+	jpc_dec_tcomp_t *tcomp;
+	unsigned rlvlno;
+	jpc_dec_rlvl_t *rlvl;
+	unsigned prcno;
+	unsigned *prclyrno;
+	jpc_dec_cmpt_t *cmpt;
+
+	if (!(pi = jpc_pi_create0())) {
+		return 0;
+	}
+	pi->numcomps = dec->numcomps;
+	if (!(pi->picomps = jas_alloc2(pi->numcomps, sizeof(jpc_picomp_t)))) {
+		jpc_pi_destroy(pi);
+		return 0;
+	}
+	for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno,
+	  ++picomp) {
+		picomp->pirlvls = 0;
+	}
+
+	for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps;
+	  compno < pi->numcomps; ++compno, ++tcomp, ++picomp) {
+		picomp->numrlvls = tcomp->numrlvls;
+		if (!(picomp->pirlvls = jas_alloc2(picomp->numrlvls,
+		  sizeof(jpc_pirlvl_t)))) {
+			jpc_pi_destroy(pi);
+			return 0;
+		}
+		for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
+		  picomp->numrlvls; ++rlvlno, ++pirlvl) {
+			pirlvl->prclyrnos = 0;
+		}
+		for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
+		  rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
+/* XXX sizeof(long) should be sizeof different type */
+			pirlvl->numprcs = rlvl->numprcs;
+			if (!(pirlvl->prclyrnos = jas_alloc2(pirlvl->numprcs,
+			  sizeof(long)))) {
+				jpc_pi_destroy(pi);
+				return 0;
+			}
+		}
+	}
+
+	pi->maxrlvls = 0;
+	for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps, cmpt =
+	  dec->cmpts; compno < pi->numcomps; ++compno, ++tcomp, ++picomp,
+	  ++cmpt) {
+		picomp->hsamp = cmpt->hstep;
+		picomp->vsamp = cmpt->vstep;
+		for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
+		  rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
+			pirlvl->prcwidthexpn = rlvl->prcwidthexpn;
+			pirlvl->prcheightexpn = rlvl->prcheightexpn;
+			for (prcno = 0, prclyrno = pirlvl->prclyrnos;
+			  prcno < pirlvl->numprcs; ++prcno, ++prclyrno) {
+				*prclyrno = 0;
+			}
+			pirlvl->numhprcs = rlvl->numhprcs;
+		}
+		if (pi->maxrlvls < tcomp->numrlvls) {
+			pi->maxrlvls = tcomp->numrlvls;
+		}
+	}
+
+	pi->numlyrs = tile->cp->numlyrs;
+	pi->xstart = tile->xstart;
+	pi->ystart = tile->ystart;
+	pi->xend = tile->xend;
+	pi->yend = tile->yend;
+
+	pi->picomp = 0;
+	pi->pirlvl = 0;
+	pi->x = 0;
+	pi->y = 0;
+	pi->compno = 0;
+	pi->rlvlno = 0;
+	pi->prcno = 0;
+	pi->lyrno = 0;
+	pi->xstep = 0;
+	pi->ystep = 0;
+
+	pi->pchgno = -1;
+
+	pi->defaultpchg.prgord = tile->cp->prgord;
+	pi->defaultpchg.compnostart = 0;
+	pi->defaultpchg.compnoend = pi->numcomps;
+	pi->defaultpchg.rlvlnostart = 0;
+	pi->defaultpchg.rlvlnoend = pi->maxrlvls;
+	pi->defaultpchg.lyrnoend = pi->numlyrs;
+	pi->pchg = 0;
+
+	pi->valid = 0;
+
+	return pi;
+}
+
+static long jpc_dec_lookahead(jas_stream_t *in)
+{
+	uint_fast16_t x;
+	if (jpc_getuint16(in, &x)) {
+		return -1;
+	}
+	if (jas_stream_ungetc(in, x & 0xff) == EOF ||
+	  jas_stream_ungetc(in, x >> 8) == EOF) {
+		return -1;
+	}
+	if (x >= JPC_MS_INMIN) {
+		return x;
+	}
+	return 0;
+}
--- /dev/null
+++ b/jpc_t2dec.h
@@ -1,0 +1,93 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 2 Decoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T2DEC_H
+#define JPC_T2DEC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_stream.h"
+
+#include "jpc_dec.h"
+#include "jpc_t2cod.h"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Decode the packets for a tile-part. */
+int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream,
+  jas_stream_t *in);
+
+/* Create a packet iterator for the decoder. */
+jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+
+#endif
--- /dev/null
+++ b/jpc_tagtree.c
@@ -1,0 +1,386 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tag Tree Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_tagtree.h"
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_stream.h"
+
+/******************************************************************************\
+* Prototypes.
+\******************************************************************************/
+
+static jpc_tagtree_t *jpc_tagtree_alloc(void);
+
+/******************************************************************************\
+* Code for creating and destroying tag trees.
+\******************************************************************************/
+
+/* Create a tag tree. */
+
+jpc_tagtree_t *jpc_tagtree_create(int numleafsh, int numleafsv)
+{
+	int nplh[JPC_TAGTREE_MAXDEPTH];
+	int nplv[JPC_TAGTREE_MAXDEPTH];
+	jpc_tagtreenode_t *node;
+	jpc_tagtreenode_t *parentnode;
+	jpc_tagtreenode_t *parentnode0;
+	jpc_tagtree_t *tree;
+	int i;
+	int j;
+	int k;
+	int numlvls;
+	int n;
+
+	assert(numleafsh > 0 && numleafsv > 0);
+
+	if (!(tree = jpc_tagtree_alloc())) {
+		return 0;
+	}
+	tree->numleafsh_ = numleafsh;
+	tree->numleafsv_ = numleafsv;
+
+	numlvls = 0;
+	nplh[0] = numleafsh;
+	nplv[0] = numleafsv;
+	do {
+		n = nplh[numlvls] * nplv[numlvls];
+		nplh[numlvls + 1] = (nplh[numlvls] + 1) / 2;
+		nplv[numlvls + 1] = (nplv[numlvls] + 1) / 2;
+		tree->numnodes_ += n;
+		++numlvls;
+	} while (n > 1);
+
+	if (!(tree->nodes_ = jas_alloc2(tree->numnodes_, sizeof(jpc_tagtreenode_t)))) {
+		jpc_tagtree_destroy(tree);
+		return 0;
+	}
+
+	/* Initialize the parent links for all nodes in the tree. */
+
+	node = tree->nodes_;
+	parentnode = &tree->nodes_[tree->numleafsh_ * tree->numleafsv_];
+	parentnode0 = parentnode;
+
+	for (i = 0; i < numlvls - 1; ++i) {
+		for (j = 0; j < nplv[i]; ++j) {
+			k = nplh[i];
+			while (--k >= 0) {
+				node->parent_ = parentnode;
+				++node;
+				if (--k >= 0) {
+					node->parent_ = parentnode;
+					++node;
+				}
+				++parentnode;
+			}
+			if ((j & 1) || j == nplv[i] - 1) {
+				parentnode0 = parentnode;
+			} else {
+				parentnode = parentnode0;
+				parentnode0 += nplh[i];
+			}
+		}
+	}
+	node->parent_ = 0;
+
+	/* Initialize the data values to something sane. */
+
+	jpc_tagtree_reset(tree);
+
+	return tree;
+}
+
+/* Destroy a tag tree. */
+
+void jpc_tagtree_destroy(jpc_tagtree_t *tree)
+{
+	jas_free(tree->nodes_);
+	jas_free(tree);
+}
+
+static jpc_tagtree_t *jpc_tagtree_alloc()
+{
+	jpc_tagtree_t *tree;
+
+	if (!(tree = jas_malloc(sizeof(jpc_tagtree_t)))) {
+		return 0;
+	}
+	tree->numleafsh_ = 0;
+	tree->numleafsv_ = 0;
+	tree->numnodes_ = 0;
+	tree->nodes_ = 0;
+
+	return tree;
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/* Copy state information from one tag tree to another. */
+
+void jpc_tagtree_copy(jpc_tagtree_t *dsttree, const jpc_tagtree_t *srctree)
+{
+	int n;
+	jpc_tagtreenode_t *dstnode;
+
+	/* The two tag trees must have similar sizes. */
+	assert(srctree->numleafsh_ == dsttree->numleafsh_ &&
+	  srctree->numleafsv_ == dsttree->numleafsv_);
+
+	n = srctree->numnodes_;
+	const jpc_tagtreenode_t *srcnode = srctree->nodes_;
+	dstnode = dsttree->nodes_;
+	while (--n >= 0) {
+		dstnode->value_ = srcnode->value_;
+		dstnode->low_ = srcnode->low_;
+		dstnode->known_ = srcnode->known_;
+		++dstnode;
+		++srcnode;
+	}
+}
+
+/* Reset all of the state information associated with a tag tree. */
+
+void jpc_tagtree_reset(jpc_tagtree_t *tree)
+{
+	int n;
+	jpc_tagtreenode_t *node;
+
+	n = tree->numnodes_;
+	node = tree->nodes_;
+
+	while (--n >= 0) {
+		node->value_ = INT_MAX;
+		node->low_ = 0;
+		node->known_ = 0;
+		++node;
+	}
+}
+
+/* Set the value associated with the specified leaf node, updating
+the other nodes as necessary. */
+
+void jpc_tagtree_setvalue(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+  int value)
+{
+	jpc_tagtreenode_t *node;
+
+	/* Avoid compiler warnings about unused parameters. */
+	USED(tree);
+
+	assert(value >= 0);
+
+	node = leaf;
+	while (node && node->value_ > value) {
+		node->value_ = value;
+		node = node->parent_;
+	}
+}
+
+/* Get a particular leaf node. */
+
+jpc_tagtreenode_t *jpc_tagtree_getleaf(jpc_tagtree_t *tree, int n)
+{
+	return &tree->nodes_[n];
+}
+
+/* Invoke the tag tree encoding procedure. */
+
+int jpc_tagtree_encode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+  int threshold, jpc_bitstream_t *out)
+{
+	jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1];
+	jpc_tagtreenode_t **stkptr;
+	jpc_tagtreenode_t *node;
+	int low;
+
+	/* Avoid compiler warnings about unused parameters. */
+	USED(tree);
+
+	assert(leaf);
+	assert(threshold >= 0);
+
+	/* Traverse to the root of the tree, recording the path taken. */
+	stkptr = stk;
+	node = leaf;
+	while (node->parent_) {
+		*stkptr++ = node;
+		node = node->parent_;
+	}
+
+	low = 0;
+	for (;;) {
+		if (low > node->low_) {
+			/* Deferred propagation of the lower bound downward in
+			  the tree. */
+			node->low_ = low;
+		} else {
+			low = node->low_;
+		}
+
+		while (low < threshold) {
+			if (low >= node->value_) {
+				if (!node->known_) {
+					if (jpc_bitstream_putbit(out, 1) == EOF) {
+						return -1;
+					}
+					node->known_ = 1;
+				}
+				break;
+			}
+			if (jpc_bitstream_putbit(out, 0) == EOF) {
+				return -1;
+			}
+			++low;
+		}
+		node->low_ = low;
+		if (stkptr == stk) {
+			break;
+		}
+		node = *--stkptr;
+
+	}
+	return (leaf->low_ < threshold) ? 1 : 0;
+
+}
+
+/* Invoke the tag tree decoding procedure. */
+
+int jpc_tagtree_decode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+  int threshold, jpc_bitstream_t *in)
+{
+	jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1];
+	jpc_tagtreenode_t **stkptr;
+	jpc_tagtreenode_t *node;
+	int low;
+	int ret;
+
+	/* Avoid compiler warnings about unused parameters. */
+	USED(tree);
+
+	assert(threshold >= 0);
+
+	/* Traverse to the root of the tree, recording the path taken. */
+	stkptr = stk;
+	node = leaf;
+	while (node->parent_) {
+		*stkptr++ = node;
+		node = node->parent_;
+	}
+
+	low = 0;
+	for (;;) {
+		if (low > node->low_) {
+			node->low_ = low;
+		} else {
+			low = node->low_;
+		}
+		while (low < threshold && low < node->value_) {
+			if ((ret = jpc_bitstream_getbit(in)) < 0) {
+				return -1;
+			}
+			if (ret) {
+				node->value_ = low;
+			} else {
+				++low;
+			}
+		}
+		node->low_ = low;
+		if (stkptr == stk) {
+			break;
+		}
+		node = *--stkptr;
+	}
+
+	return (node->value_ < threshold) ? 1 : 0;
+}
+
+/******************************************************************************\
+* Code for debugging.
+\******************************************************************************/
+
+void jpc_tagtree_dump(const jpc_tagtree_t *tree, FILE *out)
+{
+	int n;
+
+	const jpc_tagtreenode_t *node = tree->nodes_;
+	n = tree->numnodes_;
+	while (--n >= 0) {
+		fprintf(out, "node %p, parent %p, value %d, lower %d, known %d\n",
+		  (const void *) node, (const void *) node->parent_, node->value_, node->low_,
+		  node->known_);
+		++node;
+	}
+}
--- /dev/null
+++ b/jpc_tagtree.h
@@ -1,0 +1,165 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tag Tree Library
+ *
+ * $Id$
+ */
+
+#ifndef JPC_TAGTREE_H
+#define JPC_TAGTREE_H
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include "jpc_bs.h"
+
+/******************************************************************************\
+* Constants
+\******************************************************************************/
+
+/* The maximum allowable depth for a tag tree. */
+#define JPC_TAGTREE_MAXDEPTH	32
+
+/******************************************************************************\
+* Types
+\******************************************************************************/
+
+/*
+ * Tag tree node.
+ */
+
+typedef struct jpc_tagtreenode_ {
+
+	/* The parent of this node. */
+	struct jpc_tagtreenode_ *parent_;
+
+	/* The value associated with this node. */
+	int value_;
+
+	/* The lower bound on the value associated with this node. */
+	int low_;
+
+	/* A flag indicating if the value is known exactly. */
+	int known_;
+
+} jpc_tagtreenode_t;
+
+/*
+ * Tag tree.
+ */
+
+typedef struct {
+
+	/* The number of leaves in the horizontal direction. */
+	int numleafsh_;
+
+	/* The number of leaves in the vertical direction. */
+	int numleafsv_;
+
+	/* The total number of nodes in the tree. */
+	int numnodes_;
+
+	/* The nodes. */
+	jpc_tagtreenode_t *nodes_;
+
+} jpc_tagtree_t;
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Create a tag tree. */
+jpc_tagtree_t *jpc_tagtree_create(int numleafsh, int numleafsv);
+
+/* Destroy a tag tree. */
+void jpc_tagtree_destroy(jpc_tagtree_t *tree);
+
+/* Copy data from one tag tree to another. */
+void jpc_tagtree_copy(jpc_tagtree_t *dsttree, const jpc_tagtree_t *srctree);
+
+/* Reset the tag tree state. */
+void jpc_tagtree_reset(jpc_tagtree_t *tree);
+
+/* Set the value associated with a particular leaf node of a tag tree. */
+void jpc_tagtree_setvalue(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+  int value);
+
+/* Get a pointer to a particular leaf node. */
+JAS_ATTRIBUTE_PURE
+jpc_tagtreenode_t *jpc_tagtree_getleaf(jpc_tagtree_t *tree, int n);
+
+/* Invoke the tag tree decoding procedure. */
+int jpc_tagtree_decode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+  int threshold, jpc_bitstream_t *in);
+
+/* Invoke the tag tree encoding procedure. */
+int jpc_tagtree_encode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+  int threshold, jpc_bitstream_t *out);
+
+/* Dump a tag tree (for debugging purposes). */
+void jpc_tagtree_dump(const jpc_tagtree_t *tree, FILE *out);
+
+#endif
--- /dev/null
+++ b/jpc_tsfb.c
@@ -1,0 +1,299 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2004 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tree-Structured Filter Bank (TSFB) Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_tsfb.h"
+#include "jpc_cs.h"
+#include "jpc_math.h"
+#include "jpc_fix.h"
+
+#include "jasper/jas_seq.h"
+
+static int jpc_tsfb_analyze2(jpc_tsfb_t *tsfb, jpc_fix_t *a, int xstart, int ystart,
+  unsigned width, unsigned height, unsigned stride, unsigned numlvls);
+
+static int jpc_tsfb_synthesize2(jpc_tsfb_t *tsfb, jpc_fix_t *a, int xstart, int ystart,
+  unsigned width, unsigned height, unsigned stride, unsigned numlvls);
+
+static void jpc_tsfb_getbands2(jpc_tsfb_t *tsfb, int locxstart, int locystart,
+  int xstart, int ystart, int xend, int yend, jpc_tsfb_band_t **bands,
+  unsigned numlvls);
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+jpc_tsfb_t *jpc_cod_gettsfb(unsigned qmfbid, unsigned numlvls)
+{
+	jpc_tsfb_t *tsfb;
+
+	if (!(tsfb = malloc(sizeof(jpc_tsfb_t))))
+		return 0;
+
+	if (numlvls > 0) {
+		switch (qmfbid) {
+		case JPC_COX_INS:
+			tsfb->qmfb = &jpc_ns_qmfb2d;
+			break;
+		default:
+		case JPC_COX_RFT:
+			tsfb->qmfb = &jpc_ft_qmfb2d;
+			break;
+		}
+	} else {
+		tsfb->qmfb = 0;
+	}
+	tsfb->numlvls = numlvls;
+	return tsfb;
+}
+
+void jpc_tsfb_destroy(jpc_tsfb_t *tsfb)
+{
+	free(tsfb);
+}
+
+int jpc_tsfb_analyze(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
+{
+	if (tsfb->numlvls == 0)
+		return 0;
+
+	return jpc_tsfb_analyze2(tsfb,
+				 jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)),
+				 jas_seq2d_xstart(a), jas_seq2d_ystart(a),
+				 jas_seq2d_width(a), jas_seq2d_height(a),
+				 jas_seq2d_rowstep(a), tsfb->numlvls - 1);
+}
+
+static int jpc_tsfb_analyze2(jpc_tsfb_t *tsfb, jpc_fix_t *a, int xstart, int ystart,
+  unsigned width, unsigned height, unsigned stride, unsigned numlvls)
+{
+	if (width == 0 || height == 0)
+		return 0;
+
+	if ((*tsfb->qmfb->analyze)(a, xstart, ystart, width, height, stride))
+		return -1;
+
+	if (numlvls == 0)
+		return 0;
+
+	return jpc_tsfb_analyze2(tsfb, a,
+				 JPC_CEILDIVPOW2(xstart, 1),
+				 JPC_CEILDIVPOW2(ystart, 1),
+				 JPC_CEILDIVPOW2(xstart + width, 1) - JPC_CEILDIVPOW2(xstart, 1),
+				 JPC_CEILDIVPOW2(ystart + height, 1) - JPC_CEILDIVPOW2(ystart, 1),
+				 stride, numlvls - 1);
+}
+
+int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
+{
+	if (tsfb->numlvls == 0 || jas_seq2d_empty(a))
+		return 0;
+
+	return jpc_tsfb_synthesize2(tsfb,
+				    jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)),
+				    jas_seq2d_xstart(a), jas_seq2d_ystart(a),
+				    jas_seq2d_width(a), jas_seq2d_height(a),
+				    jas_seq2d_rowstep(a),
+				    tsfb->numlvls - 1);
+}
+
+static int jpc_tsfb_synthesize2(jpc_tsfb_t *tsfb, jpc_fix_t *a, int xstart, int ystart,
+  unsigned width, unsigned height, unsigned stride, unsigned numlvls)
+{
+	if (numlvls > 0) {
+		if (jpc_tsfb_synthesize2(tsfb, a, JPC_CEILDIVPOW2(xstart, 1),
+		  JPC_CEILDIVPOW2(ystart, 1), JPC_CEILDIVPOW2(xstart + width,
+		  1) - JPC_CEILDIVPOW2(xstart, 1), JPC_CEILDIVPOW2(ystart +
+		  height, 1) - JPC_CEILDIVPOW2(ystart, 1), stride, numlvls -
+		  1)) {
+			return -1;
+		}
+	}
+
+	if (width == 0 || height == 0)
+		return 0;
+
+	return tsfb->qmfb->synthesize(a, xstart, ystart, width, height, stride);
+}
+
+int jpc_tsfb_getbands(jpc_tsfb_t *tsfb, uint_fast32_t xstart,
+  uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend,
+  jpc_tsfb_band_t *bands)
+{
+	jpc_tsfb_band_t *band;
+
+	band = bands;
+	if (tsfb->numlvls > 0) {
+		jpc_tsfb_getbands2(tsfb, xstart, ystart, xstart, ystart, xend, yend,
+		  &band, tsfb->numlvls);
+	} else {
+
+		band->xstart = xstart;
+		band->ystart = ystart;
+		band->xend = xend;
+		band->yend = yend;
+		band->locxstart = xstart;
+		band->locystart = ystart;
+		band->locxend = band->locxstart + band->xend - band->xstart;
+		band->locyend = band->locystart + band->yend - band->ystart;
+		band->orient = JPC_TSFB_LL;
+		band->synenergywt = JPC_FIX_ONE;
+		++band;
+	}
+	return band - bands;
+}
+
+static void jpc_tsfb_getbands2(jpc_tsfb_t *tsfb, int locxstart, int locystart,
+  int xstart, int ystart, int xend, int yend, jpc_tsfb_band_t **bands,
+  unsigned numlvls)
+{
+	int newxstart;
+	int newystart;
+	int newxend;
+	int newyend;
+	jpc_tsfb_band_t *band;
+
+	newxstart = JPC_CEILDIVPOW2(xstart, 1);
+	newystart = JPC_CEILDIVPOW2(ystart, 1);
+	newxend = JPC_CEILDIVPOW2(xend, 1);
+	newyend = JPC_CEILDIVPOW2(yend, 1);
+
+	if (numlvls > 0) {
+
+		jpc_tsfb_getbands2(tsfb, locxstart, locystart, newxstart, newystart,
+		  newxend, newyend, bands, numlvls - 1);
+
+		band = *bands;
+		band->xstart = JPC_FLOORDIVPOW2(xstart, 1);
+		band->ystart = newystart;
+		band->xend = JPC_FLOORDIVPOW2(xend, 1);
+		band->yend = newyend;
+		band->locxstart = locxstart + newxend - newxstart;
+		band->locystart = locystart;
+		band->locxend = band->locxstart + band->xend - band->xstart;
+		band->locyend = band->locystart + band->yend - band->ystart;
+		band->orient = JPC_TSFB_HL;
+		band->synenergywt = jpc_dbltofix(tsfb->qmfb->hpenergywts[
+		  tsfb->numlvls - numlvls] * tsfb->qmfb->lpenergywts[
+		  tsfb->numlvls - numlvls]);
+		++(*bands);
+
+		band = *bands;
+		band->xstart = newxstart;
+		band->ystart = JPC_FLOORDIVPOW2(ystart, 1);
+		band->xend = newxend;
+		band->yend = JPC_FLOORDIVPOW2(yend, 1);
+		band->locxstart = locxstart;
+		band->locystart = locystart + newyend - newystart;
+		band->locxend = band->locxstart + band->xend - band->xstart;
+		band->locyend = band->locystart + band->yend - band->ystart;
+		band->orient = JPC_TSFB_LH;
+		band->synenergywt = jpc_dbltofix(tsfb->qmfb->lpenergywts[
+		  tsfb->numlvls - numlvls] * tsfb->qmfb->hpenergywts[
+		  tsfb->numlvls - numlvls]);
+		++(*bands);
+
+		band = *bands;
+		band->xstart = JPC_FLOORDIVPOW2(xstart, 1);
+		band->ystart = JPC_FLOORDIVPOW2(ystart, 1);
+		band->xend = JPC_FLOORDIVPOW2(xend, 1);
+		band->yend = JPC_FLOORDIVPOW2(yend, 1);
+		band->locxstart = locxstart + newxend - newxstart;
+		band->locystart = locystart + newyend - newystart;
+		band->locxend = band->locxstart + band->xend - band->xstart;
+		band->locyend = band->locystart + band->yend - band->ystart;
+		band->orient = JPC_TSFB_HH;
+		band->synenergywt = jpc_dbltofix(tsfb->qmfb->hpenergywts[
+		  tsfb->numlvls - numlvls] * tsfb->qmfb->hpenergywts[
+		  tsfb->numlvls - numlvls]);
+		++(*bands);
+
+	} else {
+
+		band = *bands;
+		band->xstart = xstart;
+		band->ystart = ystart;
+		band->xend = xend;
+		band->yend = yend;
+		band->locxstart = locxstart;
+		band->locystart = locystart;
+		band->locxend = band->locxstart + band->xend - band->xstart;
+		band->locyend = band->locystart + band->yend - band->ystart;
+		band->orient = JPC_TSFB_LL;
+		band->synenergywt = jpc_dbltofix(tsfb->qmfb->lpenergywts[
+		  tsfb->numlvls - numlvls - 1] * tsfb->qmfb->lpenergywts[
+		  tsfb->numlvls - numlvls - 1]);
+		++(*bands);
+
+	}
+
+}
--- /dev/null
+++ b/jpc_tsfb.h
@@ -1,0 +1,141 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2004 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tree-Structured Filter Bank (TSFB) Library
+ *
+ * $Id$
+ */
+
+#ifndef JPC_TSFB_H
+#define JPC_TSFB_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_seq.h"
+#include "jasper/jas_types.h"
+
+#include "jpc_fix.h"
+#include "jpc_qmfb.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+#define	JPC_TSFB_MAXBANDS	(JPC_TSFB_MAXDEPTH * 3 + 1)
+#define	JPC_TSFB_MAXDEPTH	32
+#define	JPC_TSFB_RITIMODE	JPC_QMFB1D_RITIMODE
+
+enum jpc_tsfb_orient {
+	JPC_TSFB_LL = 0,
+	JPC_TSFB_LH = 1,
+	JPC_TSFB_HL = 2,
+	JPC_TSFB_HH = 3,
+};
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+typedef struct {
+	int xstart;
+	int ystart;
+	int xend;
+	int yend;
+	enum jpc_tsfb_orient orient;
+	int locxstart;
+	int locystart;
+	int locxend;
+	int locyend;
+	jpc_fix_t synenergywt;
+} jpc_tsfb_band_t;
+
+typedef struct {
+	unsigned numlvls;
+	const jpc_qmfb2d_t *qmfb;
+} jpc_tsfb_t;
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Create a TSFB. */
+jpc_tsfb_t *jpc_cod_gettsfb(unsigned qmfbid, unsigned numlevels);
+
+/* Destroy a TSFB. */
+void jpc_tsfb_destroy(jpc_tsfb_t *tsfb);
+
+/* Perform analysis. */
+int jpc_tsfb_analyze(jpc_tsfb_t *tsfb, jas_seq2d_t *x);
+
+/* Perform synthesis. */
+int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *x);
+
+/* Get band information for a TSFB. */
+int jpc_tsfb_getbands(jpc_tsfb_t *tsfb, uint_fast32_t xstart,
+  uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend,
+  jpc_tsfb_band_t *bands);
+
+#endif
--- /dev/null
+++ b/jpc_util.c
@@ -1,0 +1,186 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ *   British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include "jpc_util.h"
+#include "jpc_fix.h"
+
+#include "jasper/jas_math.h"
+#include "jasper/jas_malloc.h"
+
+/******************************************************************************\
+* Miscellaneous Functions
+\******************************************************************************/
+
+int jpc_atoaf(const char *s, int *numvalues, double **values)
+{
+	static const char delim[] = ", \t\n";
+	char buf[4096];
+	int n;
+	double *vs;
+	char *cp;
+
+	strncpy(buf, s, sizeof(buf));
+	buf[sizeof(buf) - 1] = '\0';
+	n = 0;
+	if (strtok(buf, delim)) {
+		++n;
+		while ((cp = strtok(0, delim))) {
+			if (*cp != '\0') {
+				++n;
+			}
+		}
+	}
+
+	if (n) {
+		if (!(vs = jas_alloc2(n, sizeof(double)))) {
+			return -1;
+		}
+
+		strncpy(buf, s, sizeof(buf));
+		buf[sizeof(buf) - 1] = '\0';
+		n = 0;
+		if ((cp = strtok(buf, delim))) {
+			vs[n] = atof(cp);
+			++n;
+			while ((cp = strtok(0, delim))) {
+				if (*cp != '\0') {
+					vs[n] = atof(cp);
+					++n;
+				}
+			}
+		}
+	} else {
+		vs = 0;
+	}
+
+	*numvalues = n;
+	*values = vs;
+
+	return 0;
+}
+
+jas_seq_t *jpc_seq_upsample(const jas_seq_t *x, int m)
+{
+	jas_seq_t *z;
+	int i;
+
+	if (!(z = jas_seq_create(jas_seq_start(x) * m, (jas_seq_end(x) - 1) * m + 1)))
+		return 0;
+	for (i = jas_seq_start(z); i < jas_seq_end(z); i++) {
+		*jas_seq_getref(z, i) = (!JAS_MOD(i, m)) ? jas_seq_get(x, i / m) :
+		  jpc_inttofix(0);
+	}
+
+	return z;
+}
+
+jpc_fix_t jpc_seq_norm(const jas_seq_t *x)
+{
+	jpc_fix_t s;
+	int i;
+
+	s = jpc_inttofix(0);
+	for (i = jas_seq_start(x); i < jas_seq_end(x); i++) {
+		s = jpc_fix_add(s, jpc_fix_mul(jas_seq_get(x, i), jas_seq_get(x, i)));
+	}
+
+	return jpc_dbltofix(sqrt(jpc_fixtodbl(s)));
+}
+
+jas_seq_t *jpc_seq_conv(const jas_seq_t *x, const jas_seq_t *y)
+{
+	int i;
+	int j;
+	int k;
+	jas_seq_t *z;
+	jpc_fix_t s;
+	jpc_fix_t v;
+
+	z = jas_seq_create(jas_seq_start(x) + jas_seq_start(y),
+			   jas_seq_end(x) + jas_seq_end(y) - 1);
+	if (!z)
+		return NULL;
+	for (i = jas_seq_start(z); i < jas_seq_end(z); i++) {
+		s = jpc_inttofix(0);
+		for (j = jas_seq_start(y); j < jas_seq_end(y); j++) {
+			k = i - j;
+			if (k < jas_seq_start(x) || k >= jas_seq_end(x)) {
+				v = JPC_FIX_ZERO;
+			} else {
+				v = jas_seq_get(x, k);
+			}
+			s = jpc_fix_add(s, jpc_fix_mul(jas_seq_get(y, j), v));
+		}
+		*jas_seq_getref(z, i) = s;
+	}
+
+	return z;
+}
--- /dev/null
+++ b/jpc_util.h
@@ -1,0 +1,82 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ * 
+ * JasPer License Version 2.0
+ * 
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ * 
+ * All rights reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") 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, 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:
+ * 
+ * 1.  The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ * 
+ * 2.  The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ * 
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "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 OF THIRD PARTY RIGHTS.  IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ * 
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JPC_UTIL_H
+#define JPC_UTIL_H
+
+#include "jpc_fix.h"
+
+#include "jasper/jas_seq.h"
+
+/* Parse a comma separated list of real numbers into an array of doubles. */
+int jpc_atoaf(const char *s, int *numvalues, double **values);
+
+/* Upsample a sequence. */
+jas_seq_t *jpc_seq_upsample(const jas_seq_t *seq, int n);
+
+/* Convolve two sequences. */
+jas_seq_t *jpc_seq_conv(const jas_seq_t *seq0, const jas_seq_t *seq1);
+
+/* Compute the norm of a sequence. */
+JAS_ATTRIBUTE_PURE
+jpc_fix_t jpc_seq_norm(const jas_seq_t *x);
+
+#endif
--- /dev/null
+++ b/mkfile
@@ -1,0 +1,18 @@
+</$objtype/mkfile
+
+BIN=/$objtype/bin
+TARG=jp2
+CFLAGS=$CFLAGS -p
+CLEANFILES=libjp29.a
+
+OFILES=\
+	jp2.$O\
+
+default:V: all
+
+</sys/src/cmd/mkone
+
+jp2.$O: libjp29.a
+
+libjp29.a:
+	mk -f mklib
--- /dev/null
+++ b/mklib
@@ -1,0 +1,36 @@
+</$objtype/mkfile
+LIB=libjp29.a
+CFLAGS=$CFLAGS -p
+
+OFILES=\
+	jas_cm.$O\
+	jas_debug.$O\
+	jas_icc.$O\
+	jas_iccdata.$O\
+	jas_image.$O\
+	jas_init.$O\
+	jas_malloc.$O\
+	jas_seq.$O\
+	jas_stream.$O\
+	jas_string.$O\
+	jp2_cod.$O\
+	jp2_dec.$O\
+	jpc_bs.$O\
+	jpc_cs.$O\
+	jpc_dec.$O\
+	jpc_math.$O\
+	jpc_mct.$O\
+	jpc_mqcod.$O\
+	jpc_mqdec.$O\
+	jpc_qmfb.$O\
+	jpc_t1cod.$O\
+	jpc_t1dec.$O\
+	jpc_t2cod.$O\
+	jpc_t2dec.$O\
+	jpc_tagtree.$O\
+	jpc_tsfb.$O\
+	jpc_util.$O\
+
+HFILES=\
+
+</sys/src/cmd/mklib