shithub: jp2

Download patch

ref: f7e5af47f117be34669dc1e532d525dcbbff73f0
parent: 7cdf839293bf3c0b5c3f52d368635156530ddf85
author: Sigrid Solveig Haflínudóttir <sigrid@ftrv.se>
date: Fri Aug 11 20:23:07 EDT 2023

update to current

--- /dev/null
+++ b/.gitignore
@@ -1,0 +1,3 @@
+*.out
+*.[o0125678vqki]
+libjp2.a
--- a/jas_cm.c
+++ b/jas_cm.c
@@ -65,11 +65,22 @@
  * $Id$
  */
 
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#define JAS_FOR_INTERNAL_USE_ONLY
+
 #include "jasper/jas_cm.h"
 #include "jasper/jas_icc.h"
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
 
+/******************************************************************************\
+* Function prototypes.
+\******************************************************************************/
+
 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);
@@ -89,8 +100,10 @@
   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 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);
@@ -100,6 +113,10 @@
 static int jas_cmpxformseq_insertpxform(jas_cmpxformseq_t *pxformseq,
   int i, jas_cmpxform_t *pxform);
 
+/******************************************************************************\
+* Function prototypes.
+\******************************************************************************/
+
 #define	SEQFWD(intent)	(intent)
 #define	SEQREV(intent)	(4 + (intent))
 #define	SEQSIM(intent)	(8 + (intent))
@@ -122,21 +139,31 @@
 
 #define gampxformseq(prof)	((prof)->pxformseqs[SEQGAM])
 
-static jas_clrspc_t icctoclrspc(jas_iccsig_t iccclrspc, int refflag);
+static int icctoclrspc(jas_iccsig_t iccclrspc, jas_clrspc_t* clrspc, 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};
 static jas_cmprof_t *jas_cmprof_createsycc(void);
 
 /******************************************************************************\
+*
+\******************************************************************************/
+
+static const jas_cmpxformops_t shapmat_ops = {
+	jas_cmshapmat_destroy,
+	jas_cmshapmat_apply,
+	0
+};
+
+/******************************************************************************\
 * Color profile class.
 \******************************************************************************/
 
 jas_cmprof_t *jas_cmprof_createfromclrspc(jas_clrspc_t clrspc)
 {
+	JAS_LOGDEBUGF(1, "jas_cmprof_createfromclrspc(%d)\n", clrspc);
+
 	jas_iccprof_t *iccprof;
 	jas_cmprof_t *prof;
 
@@ -143,41 +170,50 @@
 	iccprof = 0;
 	switch (clrspc) {
 	case JAS_CLRSPC_SYCBCR:
-		if (!(prof = jas_cmprof_createsycc()))
+		if (!(prof = jas_cmprof_createsycc())) {
 			goto error;
+		}
 		break;
 	default:
-		if (!(iccprof = jas_iccprof_createfromclrspc(clrspc)))
+		if (!(iccprof = jas_iccprof_createfromclrspc(clrspc))) {
 			goto error;
-		if (!(prof = jas_cmprof_createfromiccprof(iccprof)))
+		}
+		if (!(prof = jas_cmprof_createfromiccprof(iccprof))) {
 			goto error;
+		}
 		jas_iccprof_destroy(iccprof);
-		if (!jas_clrspc_isgeneric(clrspc))
+		if (!jas_clrspc_isgeneric(clrspc)) {
 			prof->clrspc = clrspc;
+		}
 		break;
 	}
 	return prof;
 error:
-	if (iccprof)
+	if (iccprof) {
 		jas_iccprof_destroy(iccprof);
+	}
 	return 0;
 }
 
 static jas_cmprof_t *jas_cmprof_createsycc()
 {
+	JAS_LOGDEBUGF(1, "jas_cmprof_createsycc()\n");
+
 	jas_cmprof_t *prof;
-	jas_cmpxform_t *fwdpxform = NULL;
-	jas_cmpxform_t *revpxform = NULL;
+	jas_cmpxform_t *fwdpxform = 0;
+	jas_cmpxform_t *revpxform = 0;
 	jas_cmshapmat_t *fwdshapmat;
 	jas_cmshapmat_t *revshapmat;
 
-	if (!(prof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)))
+	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()))
+	if (!(fwdpxform = jas_cmpxform_createshapmat())) {
 		goto error;
+	}
 	fwdpxform->numinchans = 3;
 	fwdpxform->numoutchans = 3;
 	fwdshapmat = &fwdpxform->data.shapmat;
@@ -197,8 +233,9 @@
 	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()))
+	if (!(revpxform = jas_cmpxform_createshapmat())) {
 		goto error;
+	}
 	revpxform->numinchans = 3;
 	revpxform->numoutchans = 3;
 	revshapmat = &revpxform->data.shapmat;
@@ -206,20 +243,24 @@
 	revshapmat->order = 1;
 	revshapmat->useluts = 0;
 	revshapmat->usemat = 1;
-	jas_cmshapmat_invmat(revshapmat->mat, fwdshapmat->mat);
+	if (jas_cmshapmat_invmat(revshapmat->mat, fwdshapmat->mat)) {
+		goto error;
+	}
 
 	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))
+			  fwdpxform)) {
 				goto error;
+			}
 		}
 		j = SEQREV(i);
 		if (prof->pxformseqs[j]) {
 			if (jas_cmpxformseq_insertpxform(prof->pxformseqs[j],
-			  -1, revpxform))
+			  -1, revpxform)) {
 				goto error;
+			}
 		}
 	}
 
@@ -227,15 +268,22 @@
 	jas_cmpxform_destroy(revpxform);
 	return prof;
 error:
-	if (fwdpxform)
+	if (fwdpxform) {
 		jas_cmpxform_destroy(fwdpxform);
-	if (revpxform)
+	}
+	if (revpxform) {
 		jas_cmpxform_destroy(revpxform);
+	}
+	if (prof) {
+		jas_cmprof_destroy(prof);
+	}
 	return 0;
 }
 
 jas_cmprof_t *jas_cmprof_createfromiccprof(const jas_iccprof_t *iccprof)
 {
+	JAS_LOGDEBUGF(1, "jas_cmprof_createfromiccprof(%p)\n", iccprof);
+
 	jas_cmprof_t *prof;
 	jas_icchdr_t icchdr;
 	jas_cmpxformseq_t *fwdpxformseq;
@@ -244,26 +292,44 @@
 	fwdpxformseq = 0;
 	revpxformseq = 0;
 
-	if (!(prof = jas_cmprof_create()))
+	if (!(prof = jas_cmprof_create())) {
+		jas_logerrorf("error: cannot create CM profile\n");
 		goto error;
+	}
 	jas_iccprof_gethdr(iccprof, &icchdr);
-	if (!(prof->iccprof = jas_iccprof_copy(iccprof)))
+	if (!(prof->iccprof = jas_iccprof_copy(iccprof))) {
+		jas_logerrorf("error: cannot copy ICC profile\n");
 		goto error;
-	prof->clrspc = icctoclrspc(icchdr.colorspc, 0);
-	prof->refclrspc = icctoclrspc(icchdr.refcolorspc, 1);
+	}
+	if (icctoclrspc(icchdr.colorspc, &prof->clrspc, 0)) {
+		jas_logerrorf("error: unknown color profile\n");
+		goto error;
+	}
+	if (icctoclrspc(icchdr.refcolorspc, &prof->refclrspc, 1)) {
+		jas_logerrorf("error: unknown reference color profile\n");
+		goto error;
+	}
 	prof->numchans = jas_clrspc_numchans(prof->clrspc);
 	prof->numrefchans = jas_clrspc_numchans(prof->refclrspc);
 
 	if (prof->numchans == 1) {
-		if (mono(prof->iccprof, 0, &fwdpxformseq))
+		if (mono(prof->iccprof, 0, &fwdpxformseq)) {
+			jas_logerrorf("error: mono failed 1\n");
 			goto error;
-		if (mono(prof->iccprof, 1, &revpxformseq))
+		}
+		if (mono(prof->iccprof, 1, &revpxformseq)) {
+			jas_logerrorf("error: mono failed 2\n");
 			goto error;
+		}
 	} else if (prof->numchans == 3) {
-		if (triclr(prof->iccprof, 0, &fwdpxformseq))
+		if (triclr(prof->iccprof, 0, &fwdpxformseq)) {
+			jas_logerrorf("error: triclr failed 1\n");
 			goto error;
-		if (triclr(prof->iccprof, 1, &revpxformseq))
+		}
+		if (triclr(prof->iccprof, 1, &revpxformseq)) {
+			jas_logerrorf("error: triclr failed 2\n");
 			goto error;
+		}
 	}
 	prof->pxformseqs[SEQFWD(0)] = fwdpxformseq;
 	prof->pxformseqs[SEQREV(0)] = revpxformseq;
@@ -304,12 +370,14 @@
 static jas_cmprof_t *jas_cmprof_create()
 {
 	jas_cmprof_t *prof;
-	if (!(prof = jas_malloc(sizeof(jas_cmprof_t))))
+	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)
+	for (unsigned i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i) {
 		prof->pxformseqs[i] = 0;
+	}
 	return prof;
 }
 
@@ -321,8 +389,9 @@
 			prof->pxformseqs[i] = 0;
 		}
 	}
-	if (prof->iccprof)
+	if (prof->iccprof) {
 		jas_iccprof_destroy(prof->iccprof);
+	}
 	jas_free(prof);
 }
 
@@ -330,8 +399,9 @@
 {
 	jas_cmprof_t *newprof;
 
-	if (!(newprof = jas_cmprof_create()))
+	if (!(newprof = jas_cmprof_create())) {
 		goto error;
+	}
 	newprof->clrspc = prof->clrspc;
 	newprof->numchans = prof->numchans;
 	newprof->refclrspc = prof->refclrspc;
@@ -345,8 +415,9 @@
 	}
 	return newprof;
 error:
-	if (newprof)
+	if (newprof) {
 		jas_cmprof_destroy(newprof);
+	}
 	return 0;
 }
 
@@ -363,27 +434,30 @@
 	jas_cmpxformseq_t *altoutpxformseq;
 	jas_cmpxformseq_t *prfpxformseq;
 
-	/* Avoid compiler warnings about unused parameters. */
-	(void)optimize;
+	JAS_UNUSED(optimize);
 
 	const jas_cmxform_intent_t prfintent = intent;
 
-	if (!(xform = jas_malloc(sizeof(jas_cmxform_t))))
+	if (!(xform = jas_malloc(sizeof(jas_cmxform_t)))) {
 		goto error;
-	if (!(xform->pxformseq = jas_cmpxformseq_create()))
+	}
+	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)
+		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))
+		  jas_cmpxformseq_append(xform->pxformseq, outpxformseq)) {
 			goto error;
+		}
 		xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
 		xform->numoutchans = jas_clrspc_numchans(outprof->clrspc);
 		break;
@@ -390,13 +464,15 @@
 	case JAS_CMXFORM_OP_REV:
 		outpxformseq = fwdpxformseq(outprof, intent);
 		inpxformseq = revpxformseq(inprof, intent);
-		if (!outpxformseq || !inpxformseq)
+		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))
+		  jas_cmpxformseq_append(xform->pxformseq, inpxformseq)) {
 			goto error;
+		}
 		xform->numinchans = jas_clrspc_numchans(outprof->clrspc);
 		xform->numoutchans = jas_clrspc_numchans(inprof->clrspc);
 		break;
@@ -404,32 +480,38 @@
 		assert(prfprof);
 		inpxformseq = fwdpxformseq(inprof, intent);
 		prfpxformseq = fwdpxformseq(prfprof, prfintent);
-		if (!inpxformseq || !prfpxformseq)
+		if (!inpxformseq || !prfpxformseq) {
 			goto error;
+		}
 		outpxformseq = simpxformseq(outprof, intent);
 		altoutpxformseq = 0;
 		if (!outpxformseq) {
 			outpxformseq = revpxformseq(outprof, intent);
 			altoutpxformseq = fwdpxformseq(outprof, intent);
-			if (!outpxformseq || !altoutpxformseq)
+			if (!outpxformseq || !altoutpxformseq) {
 				goto error;
+			}
 		}
 		if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) ||
 		  jas_cmpxformseq_appendcnvt(xform->pxformseq,
-		  inprof->refclrspc, outprof->refclrspc))
+		  inprof->refclrspc, outprof->refclrspc)) {
 			goto error;
+		}
 		if (altoutpxformseq) {
 			if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq) ||
-			  jas_cmpxformseq_append(xform->pxformseq, altoutpxformseq))
+			  jas_cmpxformseq_append(xform->pxformseq, altoutpxformseq)) {
 				goto error;
+			}
 		} else {
-			if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq))
+			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))
+		  jas_cmpxformseq_append(xform->pxformseq, prfpxformseq)) {
 			goto error;
+		}
 		xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
 		xform->numoutchans = jas_clrspc_numchans(prfprof->clrspc);
 		break;
@@ -436,13 +518,15 @@
 	case JAS_CMXFORM_OP_GAMUT:
 		inpxformseq = fwdpxformseq(inprof, intent);
 		outpxformseq = gampxformseq(outprof);
-		if (!inpxformseq || !outpxformseq)
+		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))
+		  jas_cmpxformseq_append(xform->pxformseq, outpxformseq)) {
 			goto error;
+		}
 		xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
 		xform->numoutchans = 1;
 		break;
@@ -449,8 +533,9 @@
 	}
 	return xform;
 error:
-	if (xform)
+	if (xform) {
 		jas_cmxform_destroy(xform);
+	}
 	return 0;
 }
 
@@ -463,8 +548,10 @@
 	jas_cmreal_t scale;
 	long v;
 
-	if (xform->numinchans > in->numcmpts || xform->numoutchans > out->numcmpts)
+	if (xform->numinchans > in->numcmpts ||
+	  xform->numoutchans > out->numcmpts) {
 		goto error;
+	}
 
 	const jas_cmcmptfmt_t *fmt = &in->cmptfmts[0];
 	const unsigned width = fmt->width;
@@ -494,9 +581,10 @@
 		}
 	}
 
-	if (maxchans == 0)
+	if (maxchans == 0) {
 		/* avoid division by zero */
 		goto error;
+	}
 
 	const unsigned bufmax = APPLYBUFSIZ / maxchans;
 	assert(bufmax > 0);
@@ -515,8 +603,9 @@
 			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))
+				if (jas_cmgetint(&dataptr, fmt->sgnd, fmt->prec, &v)) {
 					goto error;
+				}
 				*bufptr = (jas_cmreal_t)(v - bias) / scale;
 				bufptr += xform->numinchans;
 			}
@@ -531,8 +620,9 @@
 			} else {
 				outbuf = inbuf;
 			}
-			if ((*pxform->ops->apply)(pxform, inbuf, outbuf, m))
+			if ((*pxform->ops->apply)(pxform, inbuf, outbuf, m)) {
 				goto error;
+			}
 			inbuf = outbuf;
 		}
 
@@ -545,8 +635,9 @@
 			for (unsigned j = 0; j < m; ++j) {
 				v = (long)((*bufptr) * scale + bias);
 				bufptr += xform->numoutchans;
-				if (jas_cmputint(&dataptr, fmt->sgnd, fmt->prec, v))
+				if (jas_cmputint(&dataptr, fmt->sgnd, fmt->prec, v)) {
 					goto error;
+				}
 			}
 		}
 	
@@ -560,8 +651,9 @@
 
 void jas_cmxform_destroy(jas_cmxform_t *xform)
 {
-	if (xform->pxformseq)
+	if (xform->pxformseq) {
 		jas_cmpxformseq_destroy(xform->pxformseq);
+	}
 	jas_free(xform);
 }
 
@@ -572,17 +664,20 @@
 static jas_cmpxformseq_t *jas_cmpxformseq_create()
 {
 	jas_cmpxformseq_t *pxformseq;
-	if (!(pxformseq = jas_malloc(sizeof(jas_cmpxformseq_t))))
+	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))
+	if (jas_cmpxformseq_resize(pxformseq, 16)) {
 		goto error;
+	}
 	return pxformseq;
 error:
-	if (pxformseq)
+	if (pxformseq) {
 		jas_cmpxformseq_destroy(pxformseq);
+	}
 	return 0;
 }
 
@@ -590,23 +685,28 @@
 {
 	jas_cmpxformseq_t *newpxformseq;
 
-	if (!(newpxformseq = jas_cmpxformseq_create()))
+	if (!(newpxformseq = jas_cmpxformseq_create())) {
 		goto error;
-	if (jas_cmpxformseq_append(newpxformseq, pxformseq))
+	}
+	if (jas_cmpxformseq_append(newpxformseq, pxformseq)) {
 		goto error;
+	}
 	return newpxformseq;
 error:
-	if (newpxformseq)
+	if (newpxformseq) {
 		jas_cmpxformseq_destroy(newpxformseq);
+	}
 	return 0;
 }
 
 static void jas_cmpxformseq_destroy(jas_cmpxformseq_t *pxformseq)
 {
-	while (pxformseq->numpxforms > 0)
+	while (pxformseq->numpxforms > 0) {
 		jas_cmpxformseq_delete(pxformseq, pxformseq->numpxforms - 1);
-	if (pxformseq->pxforms)
+	}
+	if (pxformseq->pxforms) {
 		jas_free(pxformseq->pxforms);
+	}
 	jas_free(pxformseq);
 }
 
@@ -623,11 +723,16 @@
 static int jas_cmpxformseq_appendcnvt(jas_cmpxformseq_t *pxformseq,
   unsigned dstclrspc, unsigned srcclrspc)
 {
-	if (dstclrspc == srcclrspc)
+	JAS_UNUSED(pxformseq);
+	if (dstclrspc == srcclrspc) {
 		return 0;
+	}
+	/*
+	I think that this function should not be called if the source and
+	destination color spaces are of different types.
+	That is, it is considered a programmer error, not a run-time error.
+	*/
 	abort();
-	/* Avoid compiler warnings about unused parameters. */
-	USED(pxformseq);
 	return -1;
 }
 
@@ -638,13 +743,14 @@
 	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))
+		if (jas_cmpxformseq_resize(pxformseq, pxformseq->numpxforms + 16)) {
 			goto error;
+		}
 	}
 	assert(pxformseq->numpxforms < pxformseq->maxpxforms);
-	if (!(tmppxform = jas_cmpxform_copy(pxform)))
+	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],
@@ -664,13 +770,15 @@
 	jas_cmpxform_t *othpxform;
 	const unsigned n = pxformseq->numpxforms + othpxformseq->numpxforms;
 	if (n > pxformseq->maxpxforms) {
-		if (jas_cmpxformseq_resize(pxformseq, n))
+		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)))
+		if (!(pxform = jas_cmpxform_copy(othpxform))) {
 			goto error;
+		}
 		pxformseq->pxforms[pxformseq->numpxforms] = pxform;
 		++pxformseq->numpxforms;
 	}
@@ -700,8 +808,9 @@
 static jas_cmpxform_t *jas_cmpxform_create0()
 {
 	jas_cmpxform_t *pxform;
-	if (!(pxform = jas_malloc(sizeof(jas_cmpxform_t))))
+	if (!(pxform = jas_malloc(sizeof(jas_cmpxform_t)))) {
 		return 0;
+	}
 	memset(pxform, 0, sizeof(jas_cmpxform_t));
 	pxform->refcnt = 0;
 	pxform->ops = 0;
@@ -730,8 +839,9 @@
 {
 	jas_cmpxform_t *pxform;
 	jas_cmshapmat_t *shapmat;
-	if (!(pxform = jas_cmpxform_create0()))
+	if (!(pxform = jas_cmpxform_create0())) {
 		return 0;
+	}
 	pxform->ops = &shapmat_ops;
 	shapmat = &pxform->data.shapmat;
 	shapmat->mono = 0;
@@ -738,11 +848,13 @@
 	shapmat->order = 0;
 	shapmat->useluts = 0;
 	shapmat->usemat = 0;
-	for (unsigned i = 0; i < 3; ++i)
+	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)
+		for (unsigned j = 0; j < 4; ++j) {
 			shapmat->mat[i][j] = 0.0;
+		}
 	}
 	++pxform->refcnt;
 	return pxform;
@@ -751,8 +863,9 @@
 static void jas_cmshapmat_destroy(jas_cmpxform_t *pxform)
 {
 	jas_cmshapmat_t *shapmat = &pxform->data.shapmat;
-	for (unsigned i = 0; i < 3; ++i)
+	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,
@@ -808,8 +921,9 @@
 		if (!shapmat->order) {
 			while (cnt-- > 0) {
 				a0 = *src++;
-				if (shapmat->useluts)
+				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];
@@ -824,8 +938,9 @@
 				src++;
 				src++;
 				a0 = a0 * shapmat->mat[0][0];
-				if (shapmat->useluts)
+				if (shapmat->useluts) {
 					a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+				}
 				*dst++ = a0;
 			}
 		}
@@ -851,8 +966,9 @@
 
 static double gammafn(double x, double gamma)
 {
-	if (x == 0.0)
+	if (x == 0.0) {
 		return 0.0;
+	}
 	return pow(x, gamma);
 }
 
@@ -862,14 +978,16 @@
 	jas_cmshapmatlut_cleanup(lut);
 	if (curv->numents == 0) {
 		lut->size = 2;
-		if (!(lut->data = jas_alloc2(lut->size, sizeof(jas_cmreal_t))))
+		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))))
+		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);
@@ -876,8 +994,9 @@
 		}
 	} else {
 		lut->size = curv->numents;
-		if (!(lut->data = jas_alloc2(lut->size, sizeof(jas_cmreal_t))))
+		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;
 		}
@@ -884,6 +1003,7 @@
 	}
 	return 0;
 error:
+	jas_cmshapmatlut_cleanup(lut);
 	return -1;
 }
 
@@ -892,11 +1012,13 @@
 	jas_cmreal_t t;
 	t = x * (lut->size - 1);
 	const int lo = (int)floor(t);
-	if (lo < 0)
+	if (lo < 0) {
 		return lut->data[0];
+	}
 	const unsigned hi = (unsigned)ceil(t);
-	if (hi >= lut->size)
+	if (hi >= lut->size) {
 		return lut->data[lut->size - 1];
+	}
 	return lut->data[lo] + (t - lo) * (lut->data[hi] - lut->data[lo]);
 }
 
@@ -921,8 +1043,9 @@
 			return -1;
 		}
 	}
-	if (!(invlut->data = jas_alloc2(n, sizeof(jas_cmreal_t))))
+	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);
@@ -933,11 +1056,9 @@
 				unsigned k;
 				for (k = j + 1; k < lut->size; ++k) {
 					by = lut->data[k];
-					if (by != sy)
+					if (by != sy) {
 						break;
-#if 0
-assert(0);
-#endif
+					}
 				}
 				if (k < lut->size) {
 					--k;
@@ -961,10 +1082,12 @@
 		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]);
+	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;
 }
@@ -975,11 +1098,11 @@
 	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)
+	if (JAS_ABS(d) < 1e-6) {
+		jas_logerrorf("jas_cmshapmat_invmat: matrix is not invertible "
+		  "(determinant %a)\n", d);
 		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;
@@ -993,14 +1116,14 @@
 	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]);
+	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;
 }
@@ -1009,30 +1132,34 @@
 *
 \******************************************************************************/
 
-static jas_clrspc_t icctoclrspc(jas_iccsig_t iccclrspc, int refflag)
+static int icctoclrspc(jas_iccsig_t iccclrspc, jas_clrspc_t* clrspc, int refflag)
 {
 	if (refflag) {
 		switch (iccclrspc) {
 		case JAS_ICC_COLORSPC_XYZ:
-			return JAS_CLRSPC_CIEXYZ;
+			*clrspc = JAS_CLRSPC_CIEXYZ;
+			return 0;
 		case JAS_ICC_COLORSPC_LAB:
-			return JAS_CLRSPC_CIELAB;
+			*clrspc = JAS_CLRSPC_CIELAB;
+			return 0;
 		default:
-			abort();
+			return -1;
 		}
 	} else {
 		switch (iccclrspc) {
 		case JAS_ICC_COLORSPC_YCBCR:
-			return JAS_CLRSPC_GENYCBCR;
+			*clrspc = JAS_CLRSPC_GENYCBCR;
+			return 0;
 		case JAS_ICC_COLORSPC_RGB:
-			return JAS_CLRSPC_GENRGB;
+			*clrspc = JAS_CLRSPC_GENRGB;
+			return 0;
 		case JAS_ICC_COLORSPC_GRAY:
-			return JAS_CLRSPC_GENGRAY;
+			*clrspc = JAS_CLRSPC_GENGRAY;
+			return 0;
 		default:
-			abort();
+			return -1;
 		}
 	}
-	return -1;
 }
 
 static int mono(const jas_iccprof_t *iccprof, int op, jas_cmpxformseq_t **retpxformseq)
@@ -1045,15 +1172,19 @@
 
 	jas_cmshapmatlut_init(&lut);
 	if (!(graytrc = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRYTRC)) ||
-	  graytrc->type != JAS_ICC_TYPE_CURV)
+	  graytrc->type != JAS_ICC_TYPE_CURV) {
 		goto error;
-	if (!(pxform = jas_cmpxform_createshapmat()))
+	}
+	if (!(pxform = jas_cmpxform_createshapmat())) {
 		goto error;
+	}
 	shapmat = &pxform->data.shapmat;
-	if (!(pxformseq = jas_cmpxformseq_create()))
+	if (!(pxformseq = jas_cmpxformseq_create())) {
 		goto error;
-	if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform))
+	}
+	if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform)) {
 		goto error;
+	}
 
 	pxform->numinchans = 1;
 	pxform->numoutchans = 3;
@@ -1066,8 +1197,9 @@
 		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))
+		if (jas_cmshapmatlut_set(&shapmat->luts[0], &graytrc->data.curv)) {
 			goto error;
+		}
 	} else {
 		shapmat->order = 1;
 		shapmat->mat[0][0] = 1.0 / 0.9642;
@@ -1074,10 +1206,12 @@
 		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))
+		if (jas_cmshapmatlut_set(&lut, &graytrc->data.curv)) {
 			goto error;
-		if (jas_cmshapmatlut_invert(&shapmat->luts[0], &lut, lut.size))
+		}
+		if (jas_cmshapmatlut_invert(&shapmat->luts[0], &lut, lut.size)) {
 			goto error;
+		}
 		jas_cmshapmatlut_cleanup(&lut);
 	}
 	jas_iccattrval_destroy(graytrc);
@@ -1085,16 +1219,21 @@
 	*retpxformseq = pxformseq;
 	return 0;
 error:
-	if (graytrc)
+	jas_cmshapmatlut_cleanup(&lut);
+	if (graytrc) {
 		jas_iccattrval_destroy(graytrc);
-	if (pxform)
+	}
+	if (pxform) {
 		jas_cmpxform_destroy(pxform);
-	if (pxformseq)
+	}
+	if (pxformseq) {
 		jas_cmpxformseq_destroy(pxformseq);
+	}
 	return -1;
 }
 
-static int triclr(const jas_iccprof_t *iccprof, int op, jas_cmpxformseq_t **retpxformseq)
+static int triclr(const jas_iccprof_t *iccprof, int op,
+  jas_cmpxformseq_t **retpxformseq)
 {
 	jas_iccattrval_t *trcs[3];
 	jas_iccattrval_t *cols[3];
@@ -1103,6 +1242,7 @@
 	jas_cmpxformseq_t *pxformseq;
 	jas_cmreal_t mat[3][4];
 	jas_cmshapmatlut_t lut;
+	jas_cmshapmatlut_init(&lut);
 
 	pxform = 0;
 	pxformseq = 0;
@@ -1117,22 +1257,32 @@
 	  !(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)))
+	  !(cols[2] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_BLUMATCOL))) {
+		jas_logerrorf("error: unexpected attribute value\n");
 		goto error;
+	}
 	for (unsigned i = 0; i < 3; ++i) {
 		if (trcs[i]->type != JAS_ICC_TYPE_CURV ||
-		  cols[i]->type != JAS_ICC_TYPE_XYZ)
+		  cols[i]->type != JAS_ICC_TYPE_XYZ) {
+			jas_logerrorf("error: unexpected ICC profile type\n");
 			goto error;
+		}
 	}
-	if (!(pxform = jas_cmpxform_createshapmat()))
+	if (!(pxform = jas_cmpxform_createshapmat())) {
+		jas_logerrorf("error: jas_cmpxform_createshapmat failed\n");
 		goto error;
+	}
 	pxform->numinchans = 3;
 	pxform->numoutchans = 3;
 	shapmat = &pxform->data.shapmat;
-	if (!(pxformseq = jas_cmpxformseq_create()))
+	if (!(pxformseq = jas_cmpxformseq_create())) {
+		jas_logerrorf("error: jas_cmpxformseq_create failed\n");
 		goto error;
-	if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform))
+	}
+	if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform)) {
+		jas_logerrorf("error: jas_cmpxformseq_insertpxform failed\n");
 		goto error;
+	}
 	shapmat->mono = 0;
 	shapmat->useluts = 1;
 	shapmat->usemat = 1;
@@ -1143,11 +1293,14 @@
 			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)
+		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))
+			if (jas_cmshapmatlut_set(&shapmat->luts[i], &trcs[i]->data.curv)) {
+				jas_logerrorf("error: jas_cmshapmatlut_set failed\n");
 				goto error;
+			}
 		}
 	} else {
 		shapmat->order = 1;
@@ -1156,16 +1309,23 @@
 			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)
+		for (unsigned i = 0; i < 3; ++i) {
 			mat[i][3] = 0.0;
-		if (jas_cmshapmat_invmat(shapmat->mat, mat))
+		}
+		if (jas_cmshapmat_invmat(shapmat->mat, mat)) {
+			jas_logerrorf("error: jas_cmshapmat_invmat failed\n");
 			goto error;
+		}
 		for (unsigned i = 0; i < 3; ++i) {
 			jas_cmshapmatlut_init(&lut);
-			if (jas_cmshapmatlut_set(&lut, &trcs[i]->data.curv))
+			if (jas_cmshapmatlut_set(&lut, &trcs[i]->data.curv)) {
+				jas_logerrorf("error: jas_cmshapmatlut_set failed\n");
 				goto error;
-			if (jas_cmshapmatlut_invert(&shapmat->luts[i], &lut, lut.size))
+			}
+			if (jas_cmshapmatlut_invert(&shapmat->luts[i], &lut, lut.size)) {
+				jas_logerrorf("error: jas_cmshapmatlut_invert failed\n");
 				goto error;
+			}
 			jas_cmshapmatlut_cleanup(&lut);
 		}
 	}
@@ -1179,6 +1339,7 @@
 
 error:
 
+	jas_cmshapmatlut_cleanup(&lut);
 	for (unsigned i = 0; i < 3; ++i) {
 		if (trcs[i]) {
 			jas_iccattrval_destroy(trcs[i]);
@@ -1204,11 +1365,13 @@
 	v = **bufptr;
 	if (sgnd) {
 		m = (1 << (prec - 1));
-		if (v < -m || v >= m)
+		if (v < -m || v >= m) {
 			return -1;
+		}
 	} else {
-		if (v < 0 || v >= (1 << prec))
+		if (v < 0 || v >= (1 << prec)) {
 			return -1;
+		}
 	}
 	++(*bufptr);
 	*val = v;
@@ -1220,11 +1383,13 @@
 	int m;
 	if (sgnd) {
 		m = (1 << (prec - 1));
-		if (val < -m || val >= m)
+		if (val < -m || val >= m) {
 			return -1;
+		}
 	} else {
-		if (val < 0 || val >= (1 << prec))
+		if (val < 0 || val >= (1 << prec)) {
 			return -1;
+		}
 	}
 	**bufptr = val;
 	++(*bufptr);
@@ -1243,8 +1408,8 @@
 		return 1;
 	default:
 		abort();
+		return 0;
 	}
-	return -1;
 }
 
 jas_iccprof_t *jas_iccprof_createfromcmprof(const jas_cmprof_t *prof)
--- a/jas_debug.c
+++ b/jas_debug.c
@@ -63,53 +63,214 @@
 * Includes.
 \******************************************************************************/
 
+#define JAS_FOR_INTERNAL_USE_ONLY
+
+#include "jasper/jas_init.h"
+#include "jasper/jas_compiler.h"
 #include "jasper/jas_debug.h"
 #include "jasper/jas_types.h"
+#include "jasper/jas_log.h"
 
 /******************************************************************************\
-* Local data.
+* Code for getting/setting the debug level.
 \******************************************************************************/
 
-static int jas_dbglevel = 0;
-/* The debug level. */
+/* Set the library debug level. */
+JAS_DEPRECATED
+int jas_setdbglevel(int level)
+{
+	jas_deprecated("jas_setdbglevel is deprecated\n");
+	int old_level = jas_get_debug_level();
+	jas_set_debug_level(level);
+	return old_level;
+}
 
 /******************************************************************************\
-* Code for getting/setting the debug level.
+* Code.
 \******************************************************************************/
 
-/* Set the library debug level. */
-int jas_setdbglevel(int dbglevel)
+/* Perform formatted output to standard error. */
+int jas_eprintf(const char *fmt, ...)
 {
-	int olddbglevel;
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vfprintf(stderr, fmt, ap);
+	va_end(ap);
+	return ret;
+}
 
-	/* Save the old debug level. */
-	olddbglevel = jas_dbglevel;
+/* Generate formatted error log message. */
+int jas_logprintf(const char *fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = jas_vlogmsgf(jas_logtype_init(JAS_LOGTYPE_CLASS_NULL, 0), fmt,
+	  ap);
+	va_end(ap);
+	return ret;
+}
 
-	/* Change the debug level. */
-	jas_dbglevel = dbglevel;
+/* Generate formatted error log message. */
+int jas_logerrorf(const char *fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = jas_vlogmsgf(jas_logtype_init(JAS_LOGTYPE_CLASS_ERROR, 0), fmt,
+	  ap);
+	va_end(ap);
+	return ret;
+}
 
-	/* Return the old debug level. */
-	return olddbglevel;
+/* Generate formatted warning log message. */
+int jas_logwarnf(const char *fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = jas_vlogmsgf(jas_logtype_init(JAS_LOGTYPE_CLASS_WARN, 0), fmt,
+	  ap);
+	va_end(ap);
+	return ret;
 }
 
-/* Get the library debug level. */
-int jas_getdbglevel()
+/* Generate formatted informational log message. */
+int jas_loginfof(const char *fmt, ...)
 {
-	return jas_dbglevel;
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = jas_vlogmsgf(jas_logtype_init(JAS_LOGTYPE_CLASS_INFO, 0), fmt,
+	  ap);
+	va_end(ap);
+	return ret;
 }
 
+/* Generate formatted debugging log message. */
+int jas_logdebugf(int priority, const char *fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = jas_vlogmsgf(jas_logtype_init(JAS_LOGTYPE_CLASS_DEBUG, priority),
+	  fmt, ap);
+	va_end(ap);
+	return ret;
+}
+
+/*!
+@brief
+@details
+*/
+JAS_EXPORT
+int jas_vlogmsgf(jas_logtype_t type, const char *fmt, va_list ap)
+{
+	int ret;
+	jas_vlogmsgf_t *func = jas_get_vlogmsgf();
+	ret = func(type, fmt, ap);
+	return ret;
+}
+
+/* Perform formatted output to standard error. */
+JAS_EXPORT
+int jas_vlogmsgf_stderr(jas_logtype_t type, const char *fmt, va_list ap)
+{
+#if 1
+	JAS_UNUSED(type);
+	int result = vfprintf(stderr, fmt, ap);
+	return result;
+#else
+	const char *s = "INVALID";
+	switch (jas_logtype_getclass(type)) {
+	case JAS_LOGTYPE_CLASS_NULL:
+		s = "OTHER";
+		break;
+	case JAS_LOGTYPE_CLASS_ERROR:
+		s = "ERROR";
+		break;
+	case JAS_LOGTYPE_CLASS_WARN:
+		s = "WARNING";
+		break;
+	case JAS_LOGTYPE_CLASS_INFO:
+		s = "INFO";
+		break;
+	case JAS_LOGTYPE_CLASS_DEBUG:
+		s = "DEBUG";
+		break;
+	}
+	int r1 = fprintf(stderr, "%s: ", s);
+	int r2 = vfprintf(stderr, fmt, ap);
+	int result = -1;
+	if (r1 > 0 && r2 > 0) {
+		result = r1 + r2;
+	}
+	return result;
+#endif
+}
+
+/* Perform formatted output to standard error. */
+JAS_EXPORT
+int jas_vlogmsgf_discard(jas_logtype_t type, const char *fmt, va_list ap)
+{
+	JAS_UNUSED(type);
+	JAS_CAST(void, fmt);
+	JAS_CAST(void, ap);
+	return 0;
+}
+
+/* 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;
+}
+
+/* Dump memory to a stream. */
+int jas_logmemdump(const void *data, size_t len)
+{
+	size_t i;
+	size_t j;
+	const jas_uchar *dp = data;
+	for (i = 0; i < len; i += 16) {
+		jas_logprintf("%04zx:", i);
+		for (j = 0; j < 16; ++j) {
+			if (i + j < len) {
+				jas_logprintf(" %02x", dp[i + j]);
+			}
+		}
+		jas_logprintf("\n");
+	}
+	return 0;
+}
+
 /******************************************************************************\
 * Code.
 \******************************************************************************/
 
-/* Perform formatted output to standard error. */
-int jas_eprintf(const char *fmt, ...)
+void jas_deprecated(const char *fmt, ...)
 {
-	int ret;
+	static const char message[] =
+	"WARNING: YOUR CODE IS RELYING ON DEPRECATED FUNCTIONALITY IN THE JASPER\n"
+	"LIBRARY.  THIS FUNCTIONALITY WILL BE REMOVED IN THE NEAR FUTURE. PLEASE\n"
+	"FIX THIS PROBLEM BEFORE YOUR CODE STOPS WORKING.\n"
+	;
+	fprintf(stderr, "%s", message);
+	fprintf(stderr, "deprecation warning: ");
 	va_list ap;
-
 	va_start(ap, fmt);
-	ret = vfprint(2, fmt, ap);
+	vfprintf(stderr, fmt, ap);
 	va_end(ap);
-	return ret;
 }
--- a/jas_icc.c
+++ b/jas_icc.c
@@ -59,6 +59,12 @@
  * __END_OF_JASPER_LICENSE__
  */
 
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#define JAS_FOR_INTERNAL_USE_ONLY
+
 #include "jasper/jas_icc.h"
 #include "jasper/jas_types.h"
 #include "jasper/jas_malloc.h"
@@ -65,7 +71,12 @@
 #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)
@@ -80,15 +91,11 @@
 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);
@@ -104,9 +111,8 @@
 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,
@@ -114,9 +120,8 @@
 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,
@@ -124,16 +129,14 @@
 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);
@@ -143,12 +146,10 @@
 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,
@@ -156,9 +157,8 @@
 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,
@@ -166,19 +166,19 @@
 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);
 
+/******************************************************************************\
+* Data.
+\******************************************************************************/
 
 static const jas_iccattrvalinfo_t jas_iccattrvalinfos[] = {
 	{
@@ -186,10 +186,9 @@
 			jas_icccurv_destroy,
 			jas_icccurv_copy,
 			jas_icccurv_input,
-//#ifdef JAS_ENABLE_ENCODER
 			jas_icccurv_output,
-//#endif
 			jas_icccurv_getsize,
+			jas_icccurv_dump,
 		},
 	},
 	{
@@ -198,10 +197,9 @@
 			0,
 			0,
 			jas_iccxyz_input,
-//#ifdef JAS_ENABLE_ENCODER
 			jas_iccxyz_output,
-//#endif
 			jas_iccxyz_getsize,
+			jas_iccxyz_dump,
 		},
 	},
 	{
@@ -210,10 +208,9 @@
 			jas_icctxtdesc_destroy,
 			jas_icctxtdesc_copy,
 			jas_icctxtdesc_input,
-//#ifdef JAS_ENABLE_ENCODER
 			jas_icctxtdesc_output,
-//#endif
 			jas_icctxtdesc_getsize,
+			jas_icctxtdesc_dump,
 		},
 	},
 	{
@@ -222,10 +219,9 @@
 			jas_icctxt_destroy,
 			jas_icctxt_copy,
 			jas_icctxt_input,
-//#ifdef JAS_ENABLE_ENCODER
 			jas_icctxt_output,
-//#endif
 			jas_icctxt_getsize,
+			jas_icctxt_dump,
 		},
 	},
 	{
@@ -234,10 +230,9 @@
 			jas_icclut8_destroy,
 			jas_icclut8_copy,
 			jas_icclut8_input,
-//#ifdef JAS_ENABLE_ENCODER
 			jas_icclut8_output,
-//#endif
 			jas_icclut8_getsize,
+			jas_icclut8_dump,
 		},
 	},
 	{
@@ -245,10 +240,9 @@
 			jas_icclut16_destroy,
 			jas_icclut16_copy,
 			jas_icclut16_input,
-//#ifdef JAS_ENABLE_ENCODER
 			jas_icclut16_output,
-//#endif
 			jas_icclut16_getsize,
+			jas_icclut16_dump,
 		},
 	},
 	{
@@ -257,10 +251,9 @@
 			0,
 			0,
 			0,
-//#ifdef JAS_ENABLE_ENCODER
 			0,
-//#endif
 			0,
+			0,
 		},
 	}
 };
@@ -275,15 +268,17 @@
 	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;
+	if (!(prof->attrtab = jas_iccattrtab_create())) {
+		goto error;
+	}
+	memset(&prof->hdr, 0, sizeof(jas_icchdr_t));
 	return prof;
 error:
-	if (prof)
+	if (prof) {
 		jas_iccprof_destroy(prof);
+	}
 	return 0;
 }
 
@@ -290,31 +285,41 @@
 jas_iccprof_t *jas_iccprof_copy(const jas_iccprof_t *prof)
 {
 	jas_iccprof_t *newprof;
-	if (!(newprof = jas_iccprof_create()))
+	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)))
+	if (!(newprof->attrtab = jas_iccattrtab_copy(prof->attrtab))) {
 		goto error;
+	}
 	return newprof;
 error:
-	if (newprof)
+	if (newprof) {
 		jas_iccprof_destroy(newprof);
+	}
 	return 0;
 }
 
 void jas_iccprof_destroy(jas_iccprof_t *prof)
 {
-	if (prof->attrtab)
+	if (prof->attrtab) {
 		jas_iccattrtab_destroy(prof->attrtab);
-	if (prof->tagtab.ents)
+	}
+	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;
@@ -332,11 +337,11 @@
 	}
 
 	if (jas_iccprof_readhdr(in, &prof->hdr)) {
-		jas_eprintf("cannot get header\n");
+		jas_logerrorf("cannot get header\n");
 		goto error;
 	}
 	if (jas_iccprof_gettagtab(in, &prof->tagtab)) {
-		jas_eprintf("cannot get tab table\n");
+		jas_logerrorf("cannot get tab table\n");
 		goto error;
 	}
 	jas_iccprof_sorttagtab(&prof->tagtab);
@@ -349,23 +354,24 @@
 		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)))
+				if (!(attrval = jas_iccattrval_clone(prevattrval))) {
 					goto error;
-				if (jas_iccprof_setattr(prof, tagtabent->tag, attrval))
+				}
+				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
+				jas_logwarnf("warning: skipping unknown tag type\n");
 			}
 			continue;
 		}
 		reloff = tagtabent->off - curoff;
 		if (reloff > 0) {
-			if (jas_stream_gobble(in, reloff) != reloff)
+			if (jas_stream_gobble(in, reloff) != reloff) {
 				goto error;
+			}
 			curoff += reloff;
 		} else if (reloff < 0) {
 			goto error;
@@ -379,9 +385,7 @@
 		}
 		curoff += 8;
 		if (!jas_iccattrvalinfo_lookup(type)) {
-#if 0
-			jas_eprintf("warning: skipping unknown tag type\n");
-#endif
+			jas_logwarnf("warning: skipping unknown tag type\n");
 			prevattrval = 0;
 			continue;
 		}
@@ -404,16 +408,17 @@
 	return prof;
 
 error:
-	if (prof)
+	if (prof) {
 		jas_iccprof_destroy(prof);
-	if (attrval)
+	}
+	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;
@@ -426,14 +431,16 @@
 
 	tagtab = &prof->tagtab;
 	if (!(tagtab->ents = jas_alloc2(prof->attrtab->numattrs,
-	  sizeof(jas_icctagtabent_t))))
+	  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))
+		if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval)) {
 			goto error;
+		}
 		assert(attrval->ops->output);
 		tagtabent->tag = attrname;
 		tagtabent->data = &attrval->data;
@@ -462,34 +469,40 @@
 		jas_iccattrval_destroy(attrval);
 	}
 	prof->hdr.size = curoff;
-	if (jas_iccprof_writehdr(out, &prof->hdr))
+	if (jas_iccprof_writehdr(out, &prof->hdr)) {
 		goto error;
-	if (jas_iccprof_puttagtab(out, &prof->tagtab))
+	}
+	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))
+		if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval)) {
 			goto error;
+		}
 		if (jas_iccputuint32(out, attrval->type) || jas_stream_pad(out,
-		  4, 0) != 4)
+		  4, 0) != 4) {
 			goto error;
-		if ((*attrval->ops->output)(attrval, out))
+		}
+		if ((*attrval->ops->output)(attrval, out)) {
 			goto error;
+		}
 		jas_iccattrval_destroy(attrval);
 		curoff += tagtabent->len;
 		++i;
-		while (i < tagtab->numents &&
-		  tagtab->ents[i].first)
+		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)
+			if (jas_stream_pad(out, reloff, 0) != reloff) {
 				goto error;
+			}
 			curoff += reloff;
 		}
 	}	
@@ -496,15 +509,9 @@
 	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) ||
@@ -523,8 +530,9 @@
 	  jas_iccputuint32(out, hdr->intent) ||
 	  jas_iccputxyz(out, &hdr->illum) ||
 	  jas_iccputuint32(out, hdr->creator) ||
-	  jas_stream_pad(out, 44, 0) != 44)
+	  jas_stream_pad(out, 44, 0) != 44) {
 		return -1;
+	}
 	return 0;
 }
 
@@ -531,14 +539,16 @@
 static int jas_iccprof_puttagtab(jas_stream_t *out, const jas_icctagtab_t *tagtab)
 {
 	jas_icctagtabent_t *tagtabent;
-	if (jas_iccputuint32(out, tagtab->numents))
+	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))
+		  jas_iccputuint32(out, tagtabent->len)) {
 			goto error;
+		}
 	}
 	return 0;
 error:
@@ -545,8 +555,6 @@
 	return -1;
 }
 
-//#endif
-
 static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr)
 {
 	if (jas_iccgetuint32(in, &hdr->size) ||
@@ -565,8 +573,9 @@
 	  jas_iccgetuint32(in, &hdr->intent) ||
 	  jas_iccgetxyz(in, &hdr->illum) ||
 	  jas_iccgetuint32(in, &hdr->creator) ||
-	  jas_stream_gobble(in, 44) != 44)
+	  jas_stream_gobble(in, 44) != 44) {
 		return -1;
+	}
 	return 0;
 }
 
@@ -578,17 +587,20 @@
 		jas_free(tagtab->ents);
 		tagtab->ents = 0;
 	}
-	if (jas_iccgetuint32(in, &tagtab->numents))
+	if (jas_iccgetuint32(in, &tagtab->numents)) {
 		goto error;
+	}
 	if (!(tagtab->ents = jas_alloc2(tagtab->numents,
-	  sizeof(jas_icctagtabent_t))))
+	  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))
+		jas_iccgetuint32(in, &tagtabent->len)) {
 			goto error;
+		}
 		++tagtabent;
 	}
 	return 0;
@@ -605,10 +617,12 @@
 {
 	int i;
 	jas_iccattrval_t *attrval;
-	if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) < 0)
+	if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) < 0) {
 		goto error;
-	if (!(attrval = jas_iccattrval_clone(prof->attrtab->attrs[i].val)))
+	}
+	if (!(attrval = jas_iccattrval_clone(prof->attrtab->attrs[i].val))) {
 		goto error;
+	}
 	return attrval;
 error:
 	return 0;
@@ -620,15 +634,17 @@
 	int i;
 	if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) >= 0) {
 		if (val) {
-			if (jas_iccattrtab_replace(prof->attrtab, i, name, 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))
+			if (jas_iccattrtab_add(prof->attrtab, -1, name, val)) {
 				goto error;
+			}
 		} else {
 			/* NOP */
 		}
@@ -658,8 +674,10 @@
 
 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);
+	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) {
@@ -702,29 +720,29 @@
 	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);
+	if (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 -1;
+	}
 	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);
+	if (jas_iccputuint32(out, xyz->x) ||
+	  jas_iccputuint32(out, xyz->y) ||
+	  jas_iccputuint32(out, xyz->z)) {
+		return -1;
+	}
 	return 0;
 }
 
-//#endif /* JAS_ENABLE_ENCODER */
-
 /******************************************************************************\
 * attribute table class
 \******************************************************************************/
@@ -732,17 +750,20 @@
 static jas_iccattrtab_t *jas_iccattrtab_create()
 {
 	jas_iccattrtab_t *tab;
-	if (!(tab = jas_malloc(sizeof(jas_iccattrtab_t))))
+	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))
+	if (jas_iccattrtab_resize(tab, 32)) {
 		goto error;
+	}
 	return tab;
 error:
-	if (tab)
+	if (tab) {
 		jas_iccattrtab_destroy(tab);
+	}
 	return 0;
 }
 
@@ -749,12 +770,14 @@
 static jas_iccattrtab_t *jas_iccattrtab_copy(const jas_iccattrtab_t *attrtab)
 {
 	jas_iccattrtab_t *newattrtab;
-	if (!(newattrtab = jas_iccattrtab_create()))
+	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))
+		  attrtab->attrs[i].val)) {
 			goto error;
+		}
 	}
 	return newattrtab;
  error:
@@ -773,6 +796,29 @@
 	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);
+		JAS_UNUSED(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;
@@ -801,12 +847,14 @@
 			return -1;
 		}
 	}
-	if (!(tmpattrval = jas_iccattrval_clone(val)))
+	if (!(tmpattrval = jas_iccattrval_clone(val))) {
 		return -1;
+	}
 	const unsigned n = attrtab->numattrs - i;
-	if (n > 0)
+	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;
@@ -819,8 +867,9 @@
 {
 	jas_iccattrval_t *newval;
 	jas_iccattr_t *attr;
-	if (!(newval = jas_iccattrval_clone(val)))
+	if (!(newval = jas_iccattrval_clone(val))) {
 		goto error;
+	}
 	attr = &attrtab->attrs[i];
 	jas_iccattrval_destroy(attr->val);
 	attr->name = name;
@@ -834,28 +883,29 @@
 {
 	unsigned n;
 	jas_iccattrval_destroy(attrtab->attrs[i].val);
-	if ((n = attrtab->numattrs - i - 1) > 0)
+	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)
+	if (i >= attrtab->numattrs) {
 		goto error;
+	}
 	attr = &attrtab->attrs[i];
 	*name = attr->name;
-	if (!(*val = jas_iccattrval_clone(attr->val)))
+	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)
@@ -863,8 +913,9 @@
 	jas_iccattr_t *attr;
 	for (unsigned i = 0; i < attrtab->numattrs; ++i) {
 		attr = &attrtab->attrs[i];
-		if (attr->name == name)
+		if (attr->name == name) {
 			return i;
+		}
 	}
 	return -1;
 }
@@ -878,10 +929,12 @@
 	jas_iccattrval_t *attrval;
 	const jas_iccattrvalinfo_t *info;
 
-	if (!(info = jas_iccattrvalinfo_lookup(type)))
+	if (!(info = jas_iccattrvalinfo_lookup(type))) {
 		goto error;
-	if (!(attrval = jas_iccattrval_create0()))
+	}
+	if (!(attrval = jas_iccattrval_create0())) {
 		goto error;
+	}
 	attrval->ops = &info->ops;
 	attrval->type = type;
 	++attrval->refcnt;
@@ -903,25 +956,39 @@
 jas_eprintf("refcnt=%d\n", attrval->refcnt);
 #endif
 	if (--attrval->refcnt <= 0) {
-		if (attrval->ops->destroy)
+		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()))
+		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))
+			if ((*newattrval->ops->copy)(newattrval, attrval)) {
 				goto error;
+			}
 		} else {
 			memcpy(&newattrval->data, &attrval->data,
 			  sizeof(newattrval->data));
@@ -939,8 +1006,9 @@
 static jas_iccattrval_t *jas_iccattrval_create0()
 {
 	jas_iccattrval_t *attrval;
-	if (!(attrval = jas_malloc(sizeof(jas_iccattrval_t))))
+	if (!(attrval = jas_malloc(sizeof(jas_iccattrval_t)))) {
 		return 0;
+	}
 	memset(attrval, 0, sizeof(jas_iccattrval_t));
 	attrval->refcnt = 0;
 	attrval->ops = 0;
@@ -955,31 +1023,36 @@
 static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in,
   unsigned len)
 {
-	assert(len == 4 * 3);
-	(void)len;
+	if (len != 4 * 3) {
+		return -1;
+	}
 	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))
+	  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);
-
+	JAS_UNUSED(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
 \******************************************************************************/
@@ -996,9 +1069,8 @@
 static int jas_icccurv_copy(jas_iccattrval_t *attrval,
   const jas_iccattrval_t *othattrval)
 {
-	/* Avoid compiler warnings about unused parameters. */
-	USED(attrval);
-	USED(othattrval);
+	JAS_UNUSED(attrval);
+	JAS_UNUSED(othattrval);
 
 	/* Not yet implemented. */
 	abort();
@@ -1013,17 +1085,21 @@
 	curv->numents = 0;
 	curv->ents = 0;
 
-	if (jas_iccgetuint32(in, &curv->numents))
+	if (jas_iccgetuint32(in, &curv->numents)) {
 		goto error;
-	if (!(curv->ents = jas_alloc2(curv->numents, sizeof(jas_iccuint16_t))))
+	}
+	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]))
+		if (jas_iccgetuint16(in, &curv->ents[i])) {
 			goto error;
+		}
 	}
 
-	if (4 + 2 * curv->numents != cnt)
+	if (4 + 2 * curv->numents != cnt) {
 		goto error;
+	}
 	return 0;
 
 error:
@@ -1037,23 +1113,38 @@
 	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))
+	if (jas_iccputuint32(out, curv->numents)) {
 		goto error;
+	}
 	for (unsigned i = 0; i < curv->numents; ++i) {
-		if (jas_iccputuint16(out, curv->ents[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);
+			}
+		}
+	}
+}
+
 /******************************************************************************\
 *
 \******************************************************************************/
@@ -1076,10 +1167,9 @@
 {
 	jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
 
-	/* Avoid compiler warnings about unused parameters. */
-	USED(attrval);
-	USED(othattrval);
-	USED(txtdesc);
+	JAS_UNUSED(attrval);
+	JAS_UNUSED(othattrval);
+	JAS_UNUSED(txtdesc);
 
 	/* Not yet implemented. */
 	abort();
@@ -1093,31 +1183,41 @@
 	jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
 	txtdesc->ascdata = 0;
 	txtdesc->ucdata = 0;
-	if (jas_iccgetuint32(in, &txtdesc->asclen))
+	if (jas_iccgetuint32(in, &txtdesc->asclen)) {
 		goto error;
-	if (txtdesc->asclen < 1)
+	}
+	if (txtdesc->asclen < 1) {
 		goto error;
-	if (!(txtdesc->ascdata = jas_malloc(txtdesc->asclen)))
+	}
+	if (!(txtdesc->ascdata = jas_malloc(txtdesc->asclen))) {
 		goto error;
+	}
 	if (jas_stream_read(in, txtdesc->ascdata, txtdesc->asclen) !=
-	  txtdesc->asclen)
+	  txtdesc->asclen) {
 		goto error;
+	}
 	txtdesc->ascdata[txtdesc->asclen - 1] = '\0';
 	if (jas_iccgetuint32(in, &txtdesc->uclangcode) ||
-	  jas_iccgetuint32(in, &txtdesc->uclen))
+	  jas_iccgetuint32(in, &txtdesc->uclen)) {
 		goto error;
-	if (!(txtdesc->ucdata = jas_alloc2(txtdesc->uclen, 2)))
+	}
+	if (!(txtdesc->ucdata = jas_alloc2(txtdesc->uclen, 2))) {
 		goto error;
+	}
 	if (jas_stream_read(in, txtdesc->ucdata, txtdesc->uclen * 2) !=
-	  txtdesc->uclen * 2)
+	  txtdesc->uclen * 2) {
 		goto error;
-	if (jas_iccgetuint16(in, &txtdesc->sccode))
+	}
+	if (jas_iccgetuint16(in, &txtdesc->sccode)) {
 		goto error;
-	if ((c = jas_stream_getc(in)) == EOF)
+	}
+	if ((c = jas_stream_getc(in)) == EOF) {
 		goto error;
+	}
 	txtdesc->maclen = c;
-	if (jas_stream_read(in, txtdesc->macdata, 67) != 67)
+	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
@@ -1126,12 +1226,14 @@
 		return -1;
 	}
 	if (n < cnt) {
-		if (jas_stream_gobble(in, cnt - n) != (int)(cnt - n))
+		if (jas_stream_gobble(in, cnt - n) != (int)(cnt - n)) {
 			goto error;
+		}
 	}
 #else
-	if (txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67 != cnt)
+	if (txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67 != cnt) {
 		return -1;
+	}
 #endif
 	return 0;
 error:
@@ -1145,7 +1247,6 @@
 	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;
@@ -1154,23 +1255,36 @@
 	  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_stream_write(out, txtdesc->ucdata, txtdesc->uclen * 2) !=
+	  txtdesc->uclen * 2 ||
 	  jas_iccputuint16(out, txtdesc->sccode) ||
-	  jas_stream_putc(out, txtdesc->maclen) == EOF)
+	  jas_stream_putc(out, txtdesc->maclen) == EOF) {
 		goto error;
+	}
 	if (txtdesc->maclen > 0) {
-		if (jas_stream_write(out, txtdesc->macdata, 67) != 67)
+		if (jas_stream_write(out, txtdesc->macdata, 67) != 67) {
 			goto error;
+		}
 	} else {
-		if (jas_stream_pad(out, 67, 0) != 67)
+		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);
+}
+
 /******************************************************************************\
 *
 \******************************************************************************/
@@ -1189,8 +1303,9 @@
 {
 	jas_icctxt_t *txt = &attrval->data.txt;
 	const jas_icctxt_t *othtxt = &othattrval->data.txt;
-	if (!(txt->string = strdup(othtxt->string)))
+	if (!(txt->string = jas_strdup(othtxt->string))) {
 		return -1;
+	}
 	return 0;
 }
 
@@ -1199,13 +1314,16 @@
 {
 	jas_icctxt_t *txt = &attrval->data.txt;
 	txt->string = 0;
-	if (!(txt->string = jas_malloc(cnt)))
+	if (!(txt->string = jas_malloc(cnt))) {
 		goto error;
-	if (jas_stream_read(in, txt->string, cnt) != cnt)
+	}
+	if (jas_stream_read(in, txt->string, cnt) != cnt) {
 		goto error;
+	}
 	txt->string[cnt - 1] = '\0';
-	if (strlen(txt->string) + 1 != cnt)
+	if (strlen(txt->string) + 1 != cnt) {
 		goto error;
+	}
 	return 0;
 error:
 	jas_icctxt_destroy(attrval);
@@ -1218,17 +1336,22 @@
 	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)
+	  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);
+}
+
 /******************************************************************************\
 *
 \******************************************************************************/
@@ -1261,9 +1384,8 @@
 static int jas_icclut8_copy(jas_iccattrval_t *attrval,
   const jas_iccattrval_t *othattrval)
 {
-	/* Avoid compiler warnings about unused parameters. */
-	USED(attrval);
-	USED(othattrval);
+	JAS_UNUSED(attrval);
+	JAS_UNUSED(othattrval);
 	abort();
 	return -1;
 }
@@ -1280,54 +1402,64 @@
 	if (jas_iccgetuint8(in, &lut8->numinchans) ||
 	  jas_iccgetuint8(in, &lut8->numoutchans) ||
 	  jas_iccgetuint8(in, &lut8->clutlen) ||
-	  jas_stream_getc(in) == EOF)
+	  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]))
+			if (jas_iccgetsint32(in, &lut8->e[i][j])) {
 				goto error;
+			}
 		}
 	}
 	if (jas_iccgetuint16(in, &lut8->numintabents) ||
-	  jas_iccgetuint16(in, &lut8->numouttabents))
+	  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 *))))
+	  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 *))))
+	  sizeof(jas_iccuint8_t *)))) {
 		goto error;
-	for (unsigned i = 0; i < lut8->numoutchans; ++i)
+	}
+	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]))
+			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]))
+			if (jas_iccgetuint8(in, &lut8->outtabs[i][j])) {
 				goto error;
+			}
 		}
 	}
 	for (unsigned i = 0; i < clutsize; ++i) {
-		if (jas_iccgetuint8(in, &lut8->clut[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)
+	  cnt) {
 		goto error;
+	}
 	return 0;
 error:
 	jas_icclut8_destroy(attrval);
@@ -1342,7 +1474,6 @@
 	  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;
@@ -1354,35 +1485,58 @@
 	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)
+	  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]))
+			if (jas_iccputsint32(out, lut8->e[i][j])) {
 				goto error;
+			}
 		}
 	}
 	if (jas_iccputuint16(out, lut8->numintabents) ||
-	  jas_iccputuint16(out, lut8->numouttabents))
+	  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]))
+	}
+	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]))
+	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]))
+	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);
+}
+
 /******************************************************************************\
 *
 \******************************************************************************/
@@ -1415,9 +1569,9 @@
 static int jas_icclut16_copy(jas_iccattrval_t *attrval,
   const jas_iccattrval_t *othattrval)
 {
-	/* Avoid compiler warnings about unused parameters. */
-	USED(attrval);
-	USED(othattrval);
+	JAS_UNUSED(attrval);
+	JAS_UNUSED(othattrval);
+
 	/* Not yet implemented. */
 	abort();
 	return -1;
@@ -1435,54 +1589,66 @@
 	if (jas_iccgetuint8(in, &lut16->numinchans) ||
 	  jas_iccgetuint8(in, &lut16->numoutchans) ||
 	  jas_iccgetuint8(in, &lut16->clutlen) ||
-	  jas_stream_getc(in) == EOF)
+	  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]))
+			if (jas_iccgetsint32(in, &lut16->e[i][j])) {
 				goto error;
+			}
 		}
 	}
 	if (jas_iccgetuint16(in, &lut16->numintabents) ||
-	  jas_iccgetuint16(in, &lut16->numouttabents))
+	  jas_iccgetuint16(in, &lut16->numouttabents)) {
 		goto error;
-	const unsigned clutsize = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans;
+	}
+	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 *))))
+	  sizeof(jas_iccuint16_t *)))) {
 		goto error;
-	for (unsigned i = 0; i < lut16->numinchans; ++i)
+	}
+	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 *))))
+	  sizeof(jas_iccuint16_t *)))) {
 		goto error;
-	for (unsigned i = 0; i < lut16->numoutchans; ++i)
+	}
+	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]))
+			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]))
+			if (jas_iccgetuint16(in, &lut16->outtabs[i][j])) {
 				goto error;
+			}
 		}
 	}
 	for (unsigned i = 0; i < clutsize; ++i) {
-		if (jas_iccgetuint16(in, &lut16->clut[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)
+	  lut16->numoutchans * lut16->numouttabents +
+	  jas_iccpowi(lut16->clutlen, lut16->numinchans) *
+	  lut16->numoutchans) != cnt) {
 		goto error;
+	}
 	return 0;
 error:
 	jas_icclut16_destroy(attrval);
@@ -1497,7 +1663,6 @@
 	  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;
@@ -1504,35 +1669,58 @@
 	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)
+	  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]))
+			if (jas_iccputsint32(out, lut16->e[i][j])) {
 				goto error;
+			}
 		}
 	}
 	if (jas_iccputuint16(out, lut16->numintabents) ||
-	  jas_iccputuint16(out, lut16->numouttabents))
+	  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]))
+	}
+	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]))
+	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]))
+	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);
+}
+
 /******************************************************************************\
 *
 \******************************************************************************/
@@ -1543,8 +1731,9 @@
 	jas_ulonglong v;
 	v = 0;
 	for (unsigned i = n; i > 0; --i) {
-		if ((c = jas_stream_getc(in)) == EOF)
+		if ((c = jas_stream_getc(in)) == EOF) {
 			return -1;
+		}
 		v = (v << 8) | c;
 	}
 	*val = v;
@@ -1554,8 +1743,9 @@
 static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val)
 {
 	int c;
-	if ((c = jas_stream_getc(in)) == EOF)
+	if ((c = jas_stream_getc(in)) == EOF) {
 		return -1;
+	}
 	*val = c;
 	return 0;
 }
@@ -1563,8 +1753,9 @@
 static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
 {
 	jas_ulonglong tmp;
-	if (jas_iccgetuint(in, 2, &tmp))
+	if (jas_iccgetuint(in, 2, &tmp)) {
 		return -1;
+	}
 	*val = (jas_iccuint16_t)tmp;
 	return 0;
 }
@@ -1572,8 +1763,9 @@
 static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val)
 {
 	jas_ulonglong tmp;
-	if (jas_iccgetuint(in, 4, &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;
@@ -1582,8 +1774,9 @@
 static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)
 {
 	jas_ulonglong tmp;
-	if (jas_iccgetuint(in, 4, &tmp))
+	if (jas_iccgetuint(in, 4, &tmp)) {
 		return -1;
+	}
 	*val = (jas_iccuint32_t)tmp;
 	return 0;
 }
@@ -1591,21 +1784,21 @@
 static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
 {
 	jas_ulonglong tmp;
-	if (jas_iccgetuint(in, 8, &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)
+		if (jas_stream_putc(out, c) == EOF) {
 			return -1;
+		}
 	}
 	return 0;
 }
@@ -1618,8 +1811,6 @@
 	return jas_iccputuint(out, n, tmp);
 }
 
-//#endif /* JAS_ENABLE_ENCODER */
-
 /******************************************************************************\
 *
 \******************************************************************************/
@@ -1631,7 +1822,8 @@
 	bufptr = buf;
 	for (unsigned n = 4; n > 0; --n) {
 		c = (sig >> 24) & 0xff;
-		if (isalpha(c) || isdigit(c)) {
+		if (isalpha(JAS_CAST(unsigned char, c)) ||
+		  isdigit(JAS_CAST(unsigned char, c))) {
 			*bufptr++ = c;
 		}
 		sig <<= 8;
@@ -1640,19 +1832,18 @@
 	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)
+	while (n-- > 0) {
 		y *= x;
+	}
 	return y;
 }
 
@@ -1659,17 +1850,22 @@
 
 jas_iccprof_t *jas_iccprof_createfrombuf(const jas_uchar *buf, unsigned len)
 {
+	assert(buf);
+	assert(len > 0);
 	jas_stream_t *in;
 	jas_iccprof_t *prof;
-	if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len)))
+	if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len))) {
 		goto error;
-	if (!(prof = jas_iccprof_load(in)))
+	}
+	if (!(prof = jas_iccprof_load(in))) {
 		goto error;
+	}
 	jas_stream_close(in);
 	return prof;
 error:
-	if (in)
+	if (in) {
 		jas_stream_close(in);
+	}
 	return 0;
 }
 
--- a/jas_iccdata.c
+++ b/jas_iccdata.c
@@ -59,8 +59,18 @@
  * __END_OF_JASPER_LICENSE__
  */
 
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+//#define JAS_FOR_INTERNAL_USE_ONLY
+
 #include <jasper/jas_config.h> /* IWYU pragma: keep */
 #include <jasper/jas_types.h>
+
+/******************************************************************************\
+* Data.
+\******************************************************************************/
 
 const jas_uchar jas_iccprofdata_srgb[] =
 {
--- a/jas_image.c
+++ b/jas_image.c
@@ -71,9 +71,13 @@
 * Includes.
 \******************************************************************************/
 
+#define JAS_FOR_INTERNAL_USE_ONLY
+
+#include "jasper/jas_init.h"
 #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"
 
 /******************************************************************************\
@@ -90,7 +94,8 @@
 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);
+  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);
@@ -102,22 +107,18 @@
 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);
+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);
+static void jas_image_fmtinfo_init(jas_image_fmtinfo_t *fmtinfo);
+static void jas_image_fmtinfo_cleanup(jas_image_fmtinfo_t *fmtinfo);
 
 /******************************************************************************\
-* 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 *jas_image_create(unsigned numcmpts,
+  const jas_image_cmptparm_t *cmptparms, jas_clrspc_t clrspc)
 {
 	jas_image_t *image;
 	size_t rawsize;
@@ -124,9 +125,10 @@
 	unsigned cmptno;
 	const jas_image_cmptparm_t *cmptparm;
 
-	JAS_DBGLOG(100, ("jas_image_create(%d, %p, %d)\n", numcmpts, cmptparms,
-	  clrspc));
 
+	JAS_LOGDEBUGF(100, "jas_image_create(%d, %p, %d)\n", numcmpts, cmptparms,
+	  clrspc);
+
 	if (!(image = jas_image_create0())) {
 		goto error;
 	}
@@ -133,6 +135,7 @@
 
 	image->clrspc_ = clrspc;
 	image->maxcmpts_ = numcmpts;
+//	image->inmem_ = true;
 
 	/* Allocate memory for the per-component information. */
 	if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_,
@@ -144,6 +147,19 @@
 		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) {
@@ -152,10 +168,11 @@
 			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))) {
+		  cmptparm->sgnd, inmem))) {
 			goto error;
 		}
 		++image->numcmpts_;
@@ -190,6 +207,7 @@
 	image->numcmpts_ = 0;
 	image->maxcmpts_ = 0;
 	image->cmpts_ = 0;
+//	image->inmem_ = true;
 	image->cmprof_ = 0;
 
 	return image;
@@ -207,7 +225,8 @@
 		goto error;
 	}
 	for (unsigned cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
-		if (!(newimage->cmpts_[cmptno] = jas_image_cmpt_copy(image->cmpts_[cmptno]))) {
+		if (!(newimage->cmpts_[cmptno] = jas_image_cmpt_copy(
+		  image->cmpts_[cmptno]))) {
 			goto error;
 		}
 		++newimage->numcmpts_;
@@ -216,8 +235,9 @@
 	jas_image_setbbox(newimage);
 
 	if (image->cmprof_) {
-		if (!(newimage->cmprof_ = jas_cmprof_copy(image->cmprof_)))
+		if (!(newimage->cmprof_ = jas_cmprof_copy(image->cmprof_))) {
 			goto error;
+		}
 	}
 
 	return newimage;
@@ -259,13 +279,13 @@
 	if (!(newcmpt->stream_ = jas_stream_memopen(0, 0))) {
 		goto error;
 	}
-	if (jas_stream_seek(cmpt->stream_, 0, 0)) {
+	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, 0)) {
+	if (jas_stream_seek(newcmpt->stream_, 0, SEEK_SET)) {
 		goto error;
 	}
 	return newcmpt;
@@ -283,20 +303,22 @@
 		}
 		jas_free(image->cmpts_);
 	}
-	if (image->cmprof_)
+	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)
+  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)\n",
+	JAS_LOGDEBUGF(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),
@@ -305,7 +327,8 @@
 	  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
@@ -340,13 +363,16 @@
 	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_;
+	/*
+	 * 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_ = jas_stream_memopen2(0, size);
+	cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :
+	  jas_stream_tmpfile();
 	if (!cmpt->stream_) {
 		goto error;
 	}
@@ -358,9 +384,9 @@
 		if (size - 1 > LONG_MAX) {
 			goto error;
 		}
-		if (jas_stream_seek(cmpt->stream_, size - 1, 0) < 0 ||
+		if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
 		  jas_stream_putc(cmpt->stream_, 0) == EOF ||
-		  jas_stream_seek(cmpt->stream_, 0, 0) < 0) {
+		  jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
 			goto error;
 		}
 	}
@@ -393,25 +419,24 @@
 
 	/* If possible, try to determine the format of the input data. */
 	if (fmt < 0) {
-		if ((fmt = jas_image_getfmt(in)) < 0){
-			werrstr("unknown format");
+		if ((fmt = jas_image_getfmt(in)) < 0) {
+			jas_logerrorf("jas_image_decode: cannot determine image format\n");
 			goto error;
 		}
 	}
 
 	/* Is it possible to decode an image represented in this format? */
-	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))){
-		werrstr("unsupported format");
+	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
 		goto error;
 	}
-	if (!fmtinfo->ops.decode){
-		werrstr("no decoder for the format");
+	if (!fmtinfo->ops.decode) {
+		jas_logerrorf("jas_image_decode: no decode operation available\n");
 		goto error;
 	}
 
 	/* Decode the image. */
-	if (!(image = (*fmtinfo->ops.decode)(in, optstr))){
-		werrstr("failed to decode");
+	if (!(image = (*fmtinfo->ops.decode)(in, optstr))) {
+		jas_logerrorf("jas_image_decode: decode operation failed\n");
 		goto error;
 	}
 
@@ -419,16 +444,18 @@
 	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");
+		  jas_cmprof_createfromclrspc(jas_image_clrspc(image)))) {
+			jas_logerrorf("jas_image_decode: cannot create CM profile\n");
 			goto error;
 		}
 	}
 
 	return image;
+
 error:
-	if (image)
+	if (image) {
 		jas_image_destroy(image);
+	}
 	return 0;
 }
 
@@ -437,7 +464,7 @@
 {
 	const jas_image_fmtinfo_t *fmtinfo;
 	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
-		jas_eprintf("format lookup failed\n");
+		jas_logerrorf("format lookup failed\n");
 		return -1;
 	}
 	return (fmtinfo->ops.encode) ? (*fmtinfo->ops.encode)(image, out,
@@ -460,9 +487,9 @@
 	jas_seqent_t *dr;
 	jas_seqent_t *d;
 
-	JAS_DBGLOG(100, ("jas_image_readcmpt(%p, %d, %ld, %ld, %ld, %ld, %p)\n",
+	JAS_LOGDEBUGF(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));
+	  JAS_CAST(long, width), JAS_CAST(long, height), data);
 
 	if(data == NULL) {
 		return -1;
@@ -483,7 +510,8 @@
 		return -1;
 	}
 
-	if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) {
+	if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) !=
+	  width) {
 		if (jas_matrix_resize(data, height, width)) {
 			return -1;
 		}
@@ -497,9 +525,13 @@
 
 	dr = jas_matrix_getref(data, 0, 0);
 	const uint_least32_t drs = jas_matrix_rowstep(data);
+
+	jas_uchar stack_buffer[16384];
+
 	for (i = 0; i < height; ++i, dr += drs) {
 		d = dr;
-		if (jas_stream_seek(stream, (cmpt_width * (y + i) + x) * cps, 0) < 0) {
+		if (jas_stream_seek(stream, (cmpt_width * (y + i) + x)
+		  * cps, SEEK_SET) < 0) {
 			return -1;
 		}
 
@@ -507,13 +539,15 @@
 			/* fast path for 1 byte per sample and
 			   unsigned with bulk reads */
 
-			jas_uchar buffer[16384];
+			jas_uchar *buffer = stack_buffer;
 
-			if (jas_stream_read(stream, buffer, width) != width)
+			if (jas_stream_read(stream, buffer, width) != width) {
 				return -1;
+			}
 
-			for (j = 0; j < width; ++j)
+			for (j = 0; j < width; ++j) {
 				d[j] = buffer[j];
+			}
 
 			continue;
 		}
@@ -533,9 +567,9 @@
 	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)
+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;
@@ -543,9 +577,9 @@
 	jas_seqent_t v;
 	int c;
 
-	JAS_DBGLOG(100, ("jas_image_writecmpt(%p, %d, %ld, %ld, %ld, %ld, %p)\n",
+	JAS_LOGDEBUGF(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));
+	  JAS_CAST(long, width), JAS_CAST(long, height), data);
 
 	if (cmptno >= image->numcmpts_) {
 		return -1;
@@ -575,9 +609,13 @@
 
 	const jas_seqent_t *dr = jas_matrix_getref(data, 0, 0);
 	const uint_least32_t drs = jas_matrix_rowstep(data);
+
+	jas_uchar stack_buffer[16384];
+
 	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, 0) < 0) {
+		if (jas_stream_seek(stream, (cmpt_width * (y + i) + x)
+		  * cps, SEEK_SET) < 0) {
 			return -1;
 		}
 
@@ -585,7 +623,7 @@
 			/* fast path for 1 byte per sample and
 			   unsigned with bulk writes */
 
-			jas_uchar buffer[16384];
+			jas_uchar *buffer = stack_buffer;
 
 			for (j = 0; j < width; ++j)
 				buffer[j] = d[j];
@@ -614,88 +652,139 @@
 * File format operations.
 \******************************************************************************/
 
-void jas_image_clearfmts()
+static void jas_image_fmtinfo_init(jas_image_fmtinfo_t *fmtinfo)
 {
-	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;
+	fmtinfo->id = -1;
+	fmtinfo->name = 0;
+	fmtinfo->ext = 0;
+	fmtinfo->exts = 0;
+	fmtinfo->max_exts = 0;
+	fmtinfo->num_exts = 0;
+	fmtinfo->enabled = 0;
+	fmtinfo->desc = 0;
+	memset(&fmtinfo->ops, 0, sizeof(jas_image_fmtops_t));
 }
 
-int jas_image_addfmt(int id, const char *name, const char *ext,
-  const char *desc, const jas_image_fmtops_t *ops)
+static void jas_image_fmtinfo_cleanup(jas_image_fmtinfo_t *fmtinfo)
 {
-	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 = strdup(name))) {
-		return -1;
-	}
-	if (!(fmtinfo->ext = strdup(ext))) {
+	if (fmtinfo->name) {
 		jas_free(fmtinfo->name);
-		return -1;
+		fmtinfo->name = 0;
 	}
-	if (!(fmtinfo->desc = strdup(desc))) {
-		jas_free(fmtinfo->name);
+	if (fmtinfo->ext) {
 		jas_free(fmtinfo->ext);
-		return -1;
+		fmtinfo->ext = 0;
 	}
-	fmtinfo->ops = *ops;
-	++jas_image_numfmts;
+	if (fmtinfo->exts) {
+		assert(fmtinfo->max_exts > 0);
+		for (int i = 0; i < fmtinfo->num_exts; ++i) {
+			jas_free(fmtinfo->exts[i]);
+		}
+		jas_free(fmtinfo->exts);
+		fmtinfo->exts = 0;
+	}
+	if (fmtinfo->desc) {
+		jas_free(fmtinfo->desc);
+		fmtinfo->desc = 0;
+	}
+}
+
+JAS_EXPORT
+const jas_image_fmtinfo_t *jas_image_getfmtbyind(int index)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	assert(index >= 0 && index < ctx->image_numfmts);
+	return &ctx->image_fmtinfos[index];
+}
+
+JAS_EXPORT
+int jas_image_getnumfmts(void)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	return ctx->image_numfmts;
+}
+
+JAS_EXPORT
+int jas_image_setfmtenable(int index, int enabled)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	ctx->image_fmtinfos[index].enabled = enabled;
 	return 0;
 }
 
-int jas_image_addcmpt(jas_image_t *image, int cmptno,
-  const jas_image_cmptparm_t *cmptparm)
+void jas_image_clearfmts_internal(jas_image_fmtinfo_t *image_fmtinfos,
+  size_t *image_numfmts)
 {
-	jas_image_cmpt_t *newcmpt;
-	if (cmptno < 0) {
-		cmptno = image->numcmpts_;
+	jas_image_fmtinfo_t *fmtinfo;
+	for (int fmtind = 0; fmtind < *image_numfmts; ++fmtind) {
+		fmtinfo = &image_fmtinfos[fmtind];
+		jas_image_fmtinfo_cleanup(fmtinfo);
 	}
-	assert(cmptno >= 0 && (unsigned)cmptno <= image->numcmpts_);
-	if (image->numcmpts_ >= image->maxcmpts_) {
-		if (jas_image_growcmpts(image, image->maxcmpts_ + 128)) {
-			return -1;
-		}
+	*image_numfmts = 0;
+}
+
+void jas_image_clearfmts()
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	jas_image_clearfmts_internal(ctx->image_fmtinfos, &ctx->image_numfmts);
+}
+
+int jas_image_addfmt_internal(jas_image_fmtinfo_t *image_fmtinfos,
+  size_t *image_numfmts, int id, const char *name, const char *ext,
+  const char *desc, const jas_image_fmtops_t *ops)
+{
+	const char delim[] = " \t";
+	int ret = 0;
+	jas_image_fmtinfo_t *fmtinfo = 0;
+
+	assert(id >= 0 && name && ext && ops);
+	if (*image_numfmts >= JAS_IMAGE_MAXFMTS) {
+		ret = -1;
+		goto done;
 	}
-	if (!(newcmpt = jas_image_cmpt_create(cmptparm->tlx,
-	  cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
-	  cmptparm->width, cmptparm->height, cmptparm->prec,
-	  cmptparm->sgnd))) {
-		return -1;
+	fmtinfo = &image_fmtinfos[*image_numfmts];
+	jas_image_fmtinfo_init(fmtinfo);
+	fmtinfo->id = id;
+	if (jas_stringtokenize(ext, delim, &fmtinfo->exts, &fmtinfo->max_exts,
+	  &fmtinfo->num_exts)) {
+		assert(!fmtinfo->exts && !fmtinfo->max_exts && !fmtinfo->num_exts);
+		ret = -1;
+		goto done;
 	}
-	if ((unsigned)cmptno < image->numcmpts_) {
-		memmove(&image->cmpts_[cmptno + 1], &image->cmpts_[cmptno],
-		  (image->numcmpts_ - (unsigned)cmptno) * sizeof(jas_image_cmpt_t *));
+	assert(fmtinfo->num_exts > 0);
+	char *primary_ext = fmtinfo->exts[0];
+	if (!(fmtinfo->name = jas_strdup(name))) {
+		ret = -1;
+		goto done;
 	}
-	image->cmpts_[cmptno] = newcmpt;
-	++image->numcmpts_;
+	if (!(fmtinfo->ext = jas_strdup(primary_ext))) {
+		ret = -1;
+		goto done;
+	}
+	if (!(fmtinfo->desc = jas_strdup(desc))) {
+		ret = -1;
+		goto done;
+	}
+	fmtinfo->ops = *ops;
+	++(*image_numfmts);
+done:
+	if (ret && fmtinfo) {
+		jas_image_fmtinfo_cleanup(fmtinfo);
+	}
+	return ret;
+}
 
-	jas_image_setbbox(image);
-
-	return 0;
+int jas_image_addfmt(int id, const char *name, const char *ext,
+  const char *desc, const jas_image_fmtops_t *ops)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	return jas_image_addfmt_internal(ctx->image_fmtinfos, &ctx->image_numfmts,
+	  id, name, ext, desc, ops);
 }
 
 /* This is for future consideration for addition to the library API. */
 #if 0
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_delfmt(int fmtid)
 {
 	if (fmtid < 0 || fmtid >= JAS_CAST(int, jas_image_numfmts)) {
@@ -734,20 +823,21 @@
 
 int jas_image_getfmt(jas_stream_t *in)
 {
+	jas_ctx_t *ctx = jas_get_ctx();
 	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,
+	for (i = 0, fmtinfo = ctx->image_fmtinfos; i < ctx->image_numfmts; ++i,
 	  ++fmtinfo) {
-		if (fmtinfo->ops.validate) {
+		if (fmtinfo->enabled && fmtinfo->ops.validate) {
 			/* Is the input data valid for this format? */
-			JAS_DBGLOG(20, ("testing for format %s ... ", fmtinfo->name));
+			JAS_LOGDEBUGF(20, "testing for format %s\n", fmtinfo->name);
 			if (!(*fmtinfo->ops.validate)(in)) {
-				JAS_DBGLOG(20, ("test succeeded\n"));
+				JAS_LOGDEBUGF(20, "test succeeded\n");
 				return fmtinfo->id;
 			}
-			JAS_DBGLOG(20, ("test failed\n"));
+			JAS_LOGDEBUGF(20, "test failed\n");
 		}
 	}
 	return -1;
@@ -755,6 +845,7 @@
 
 int jas_image_fmtfromname(const char *name)
 {
+	jas_ctx_t *ctx = jas_get_ctx();
 	const char *ext;
 	const jas_image_fmtinfo_t *fmtinfo;
 	/* Get the file name extension. */
@@ -764,10 +855,10 @@
 	++ext;
 	/* Try to find a format that uses this extension. */	
 	unsigned i;
-	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i,
+	for (i = 0, fmtinfo = ctx->image_fmtinfos; i < ctx->image_numfmts; ++i,
 	  ++fmtinfo) {
 		/* Do we have a match? */
-		if (!strcmp(ext, fmtinfo->ext)) {
+		if (fmtinfo->enabled && !strcmp(ext, fmtinfo->ext)) {
 			return fmtinfo->id;
 		}
 	}
@@ -824,12 +915,45 @@
 	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)
 {
+	jas_ctx_t *ctx = jas_get_ctx();
 	unsigned i;
 	const jas_image_fmtinfo_t *fmtinfo;
 
-	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
+	for (i = 0, fmtinfo = ctx->image_fmtinfos; i < ctx->image_numfmts;
+	  ++i, ++fmtinfo) {
 		if (fmtinfo->id == id) {
 			return fmtinfo;
 		}
@@ -839,10 +963,11 @@
 
 const jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name)
 {
+	jas_ctx_t *ctx = jas_get_ctx();
 	unsigned i;
 	const jas_image_fmtinfo_t *fmtinfo;
-
-	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
+	for (i = 0, fmtinfo = ctx->image_fmtinfos; i < ctx->image_numfmts;
+	  ++i, ++fmtinfo) {
 		if (!strcmp(fmtinfo->name, name)) {
 			return fmtinfo;
 		}
@@ -853,7 +978,9 @@
 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);
+	assert(v >= 0 || sgnd);
+	ret = ((sgnd && v < 0) ? (JAS_POW2_X(jas_seqent_t, prec) + v) : v) &
+	  JAS_ONES(prec);
 	return ret;
 }
 
@@ -945,9 +1072,40 @@
 	return 0;
 }
 
-int jas_image_depalettize(jas_image_t *image, unsigned cmptno, unsigned numlutents,
-  const int_fast32_t *lutents, unsigned dtype, unsigned newcmptno)
+int 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)) {
+			return -1;
+		}
+		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)) {
+			return -1;
+		}
+		for (unsigned i = 0; i < n; ++i) {
+			fprintf(out, " f(%d,%d)=%ld", width - n + i, height - 1, buf[i]);
+		}
+		fprintf(out, "\n");
+	}
+	return 0;
+}
+
+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];
 
@@ -994,7 +1152,8 @@
 
 	cmpt = image->cmpts_[cmptno];
 
-	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_, 0) < 0) {
+	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
+	  SEEK_SET) < 0) {
 		return -1;
 	}
 	v = 0;
@@ -1016,7 +1175,8 @@
 
 	cmpt = image->cmpts_[cmptno];
 
-	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_, 0) < 0) {
+	if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_,
+	  SEEK_SET) < 0) {
 		return;
 	}
 	t = inttobits(v, cmpt->prec_, cmpt->sgnd_);
@@ -1029,7 +1189,8 @@
 	}
 }
 
-int jas_image_getcmptbytype(const jas_image_t *image, jas_image_cmpttype_t ctype)
+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) {
@@ -1039,29 +1200,14 @@
 	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)
+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;
@@ -1069,21 +1215,26 @@
 	long v;
 	long *bufptr;
 
-	if (cmptno >= image->numcmpts_)
+	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_)
+	  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_, 0) < 0)
+		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))
+			if (getint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, &v)) {
 				goto error;
+			}
 			*bufptr++ = v;
 		}
 	}
@@ -1093,9 +1244,9 @@
 	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)
+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;
@@ -1102,22 +1253,27 @@
 	jas_image_coord_t j;
 	long v;
 
-	if (cmptno >= image->numcmpts_)
+	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_)
+	  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_, 0) < 0)
+		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))
+			if (putint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, v)) {
 				goto error;
+			}
 		}
 	}
 
@@ -1165,10 +1321,11 @@
 	cmptparm.height = height;
 	cmptparm.prec = prec;
 	cmptparm.sgnd = sgnd;
-	if (jas_image_addcmpt(image, newcmptno, &cmptparm))
+	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_;
+	}
+	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) {
@@ -1178,11 +1335,13 @@
 			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)
+			if (bx > cmptbrx) {
 				bx = cmptbrx;
+			}
 			by = uptomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_;
-			if (by > cmptbry)
+			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);
@@ -1202,11 +1361,14 @@
 			}
 			assert(oldx >= 0 && oldx < oldcmpt->width_ &&
 			  oldy >= 0 && oldy < oldcmpt->height_);
-			if (jas_stream_seek(oldcmpt->stream_, oldcmpt->cps_ * (oldy * oldcmpt->width_ + oldx), 0) < 0)
+			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))
+			  oldcmpt->prec_, &v)) {
 				goto error;
+			}
 			if (newcmpt->prec_ != oldcmpt->prec_ ||
 			  newcmpt->sgnd_ != oldcmpt->sgnd_) {
 				v = convert(v, oldcmpt->sgnd_, oldcmpt->prec_,
@@ -1213,8 +1375,9 @@
 				  newcmpt->sgnd_, newcmpt->prec_);
 			}
 			if (putint(newcmpt->stream_, newcmpt->sgnd_,
-			  newcmpt->prec_, v))
+			  newcmpt->prec_, v)) {
 				goto error;
+			}
 		}
 	}
 	return 0;
@@ -1241,8 +1404,9 @@
 }
 
 /* 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)
+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;
@@ -1257,16 +1421,20 @@
 		tmpbry = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1);
 		for (unsigned i = 0; i < image->numcmpts_; ++i) {
 			cmpt = image->cmpts_[i];
-			if (cmpt->tlx_ < tmptlx)
+			if (cmpt->tlx_ < tmptlx) {
 				tmptlx = cmpt->tlx_;
-			if (cmpt->tly_ < tmptly)
+			}
+			if (cmpt->tly_ < tmptly) {
 				tmptly = cmpt->tly_;
+			}
 			t = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1);
-			if (t > tmpbrx)
+			if (t > tmpbrx) {
 				tmpbrx = t;
+			}
 			t = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1);
-			if (t > tmpbry)
+			if (t > tmpbry) {
 				tmpbry = t;
+			}
 		}
 	} else {
 		tmptlx = 0;
@@ -1285,7 +1453,7 @@
 {
 	long result;
 	assert(prec >= 2);
-	jas_eprintf("warning: support for signed data is untested\n");
+	jas_logwarnf("warning: support for signed data is untested\n");
 	// NOTE: Is this correct?
 	result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1)));
 	return result;
@@ -1296,7 +1464,7 @@
 {
 	jas_ulong result;
 	assert(prec >= 2);
-	jas_eprintf("warning: support for signed data is untested\n");
+	jas_logwarnf("warning: support for signed data is untested\n");
 	// NOTE: Is this correct?
 	if (n < 0) {
 		result = -n;
@@ -1315,8 +1483,9 @@
 	assert((!sgnd && prec >= 1) || (sgnd && prec >= 2));
 	v = 0;
 	for (unsigned n = (prec + 7) / 8; n-- > 0;) {
-		if ((c = jas_stream_getc(in)) == EOF)
+		if ((c = jas_stream_getc(in)) == EOF) {
 			return -1;
+		}
 		v = (v << 8) | c;
 	}
 	v &= ((1 << prec) - 1);
@@ -1339,8 +1508,9 @@
 	val &= (1 << prec) - 1;
 	for (unsigned n = (prec + 7) / 8; n-- > 0;) {
 		c = (val >> (n * 8)) & 0xff;
-		if (jas_stream_putc(out, c) != c)
+		if (jas_stream_putc(out, c) != c) {
 			return -1;
+		}
 	}
 	return 0;
 }
@@ -1348,6 +1518,7 @@
 static long convert(long val, bool oldsgnd, unsigned oldprec, bool newsgnd,
   unsigned newprec)
 {
+	/* TODO: The following code looks suspicious (i.e., an empty if body). */
 	if (newsgnd != oldsgnd) {
 	}
 	if (newprec != oldprec) {
@@ -1372,8 +1543,8 @@
 	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 *jas_image_chclrspc(jas_image_t *image,
+  const jas_cmprof_t *outprof, jas_cmxform_intent_t intent)
 {
 	jas_image_t *inimage;
 	int k;
@@ -1387,16 +1558,25 @@
 	jas_cmcmptfmt_t *incmptfmts;
 	jas_cmcmptfmt_t *outcmptfmts;
 
-	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;
+#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 0;
+	}
+
 	outimage = 0;
 	xform = 0;
-	if (!(inimage = jas_image_copy(image)))
+	if (!(inimage = jas_image_copy(image))) {
 		goto error;
+	}
 
 	if (!jas_image_ishomosamp(inimage)) {
 		unsigned minhstep = jas_image_cmpthstep(inimage, 0);
@@ -1414,10 +1594,12 @@
 		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))) {
+			  jas_image_cmptsgnd(inimage, i), jas_image_cmptprec(inimage,
+			  i))) {
 				goto error;
 			}
-			const jas_image_cmpttype_t cmpttype = jas_image_cmpttype(inimage, i);
+			const jas_image_cmpttype_t cmpttype = jas_image_cmpttype(inimage,
+			  i);
 			jas_image_setcmpttype(inimage, i + 1, cmpttype);
 			jas_image_delcmpt(inimage, i);
 		}
@@ -1429,10 +1611,13 @@
 	const unsigned vstep = jas_image_cmptvstep(inimage, 0);
 
 	if (!(inprof = jas_image_cmprof(inimage))) {
-		abort();
+		// formerly call to abort()
+		goto error;
 	}
-	const unsigned numinclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(inprof));
-	const unsigned numoutclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(outprof));
+	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())) {
@@ -1449,8 +1634,9 @@
 		cmptparm.height = height;
 		cmptparm.prec = prec;
 		cmptparm.sgnd = 0;
-		if (jas_image_addcmpt(outimage, -1, &cmptparm))
+		if (jas_image_addcmpt(outimage, -1, &cmptparm)) {
 			goto error;
+		}
 		jas_image_setcmpttype(outimage, i, JAS_IMAGE_CT_COLOR(i));
 	}
 #if 0
@@ -1463,8 +1649,9 @@
 	}
 #endif
 
-	if (!(tmpprof = jas_cmprof_copy(outprof)))
+	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));
@@ -1476,7 +1663,8 @@
 
 	inpixmap.numcmpts = numinclrchans;
 	if (!(incmptfmts = jas_alloc2(numinclrchans, sizeof(jas_cmcmptfmt_t)))) {
-		abort();
+		// formerly call to abort()
+		goto error;
 	}
 	inpixmap.cmptfmts = incmptfmts;
 	for (unsigned i = 0; i < numinclrchans; ++i) {
@@ -1492,14 +1680,16 @@
 
 	outpixmap.numcmpts = numoutclrchans;
 	if (!(outcmptfmts = jas_alloc2(numoutclrchans, sizeof(jas_cmcmptfmt_t)))) {
-		abort();
+		// formerly call to abort()
+		goto error;
 	}
 	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))))
+		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;
@@ -1510,15 +1700,17 @@
 		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))
+			  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))
+			  outcmptfmts[j].buf)) {
 				goto error;
+			}
 		}
 	}
 
@@ -1533,13 +1725,22 @@
 	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)
+	if (xform) {
 		jas_cmxform_destroy(xform);
-	if (inimage)
+	}
+	if (inimage) {
 		jas_image_destroy(inimage);
-	if (outimage)
+	}
+	if (outimage) {
 		jas_image_destroy(outimage);
+	}
 	return 0;
 }
--- a/jas_init.c
+++ b/jas_init.c
@@ -63,45 +63,971 @@
 * Includes.
 \******************************************************************************/
 
+#define JAS_FOR_INTERNAL_USE_ONLY
+
 #include "jasper/jas_init.h"
 #include "jasper/jas_image.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_thread.h"
 
 /******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/*!
+@brief Entry in image format table.
+*/
+typedef struct {
+
+	/*!
+	A unique name identifying the format.
+	*/
+	const char *name;
+
+	/*!
+	A short description of the format.
+	*/
+	const char *desc;
+
+	/*!
+	A whitespace delimited list of file extensions associated with the format.
+	*/
+	const char *exts;
+
+	/*!
+	The operations for the format (e.g., encode, decode, and validate).
+	*/
+	const jas_image_fmtops_t ops;
+
+	/*!
+	A boolean flag indicating if the format is enabled.
+	*/
+	int enabled;
+
+} jas_image_fmt_t;
+
+/*
+User-configurable settings for library.
+This is for internal library use only.
+*/
+typedef struct {
+
+	/*
+	A boolean flag indicating if the library has been configured
+	by invoking the jas_conf_clear function.
+	*/
+	bool initialized;
+
+	/*
+	A boolean flag indicating if the library is potentially going to be
+	used by more than one thread.
+	*/
+	bool multithread;
+
+	/*
+	The allocator to be used by the library.
+	*/
+	jas_allocator_t *allocator;
+
+	/*
+	A boolean flag indicating if the allocator should be accessed through
+	a wrapper that allows memory usage to be tracked and limited.
+	*/
+	bool enable_allocator_wrapper;
+
+	/*
+	The maximum amount of memory to be used by the library if the
+	allocator wrapper is used.
+	*/
+	size_t max_mem;
+	bool max_mem_valid;
+
+	/*
+	The image format information to be used to populate the image format
+	table in newly created contexts.
+	*/
+	const jas_image_fmt_t *image_formats;
+	size_t num_image_formats;
+
+	/*
+	The maximum number of samples allowable in an image to be decoded to be
+	used in newly created contexts.
+	*/
+	size_t dec_default_max_samples;
+
+	/*
+	The level of debugging checks/output enabled by the library for newly
+	created contexts.
+	A larger value corresponds to a greater level of debugging checks/output.
+	*/
+	int debug_level;
+
+	/*
+	The function used to output error/warning/informational messages
+	for newly created contexts.
+	*/
+	int (*vlogmsgf)(jas_logtype_t type, const char *format, va_list ap);
+
+} jas_conf_t;
+
+typedef struct {
+
+	/* A copy of the run-time library configuration settings. */
+	jas_conf_t conf;
+
+	/* A flag indicating if the library is initialized.*/
+	bool initialized;
+
+	/* The number of threads currently using the library. */
+	size_t num_active_threads;
+
+	/*
+	If JAS_THREADS is not defined, this pointer is used for both the
+	global context and default context.
+	Otherwise, this pointer is only used for the global context.
+	*/
+	jas_ctx_t *ctx;
+
+	/*
+	The storage for the global context.
+	*/
+	jas_ctx_t ctx_buf;
+
+#if defined(JAS_THREADS)
+
+	/* A mutex to protect this data structure. */
+	jas_mutex_t lock;
+
+	/* The TSS for the current context pointer. */
+	jas_tss_t cur_ctx_tss;
+
+	/* The TSS for the default context pointer. */
+	jas_tss_t default_ctx_tss;
+
+#endif
+
+} jas_global_t;
+
+/******************************************************************************\
+* Function prototypes.
+\******************************************************************************/
+
+//static jas_conf_t *jas_get_conf_ptr(void);
+void jas_ctx_init(jas_ctx_t *ctx);
+static int jas_init_codecs(jas_ctx_t *ctx);
+void jas_ctx_cleanup(jas_ctx_t *ctx);
+void jas_set_ctx(jas_ctx_t *ctx);
+void jas_set_default_ctx(jas_ctx_t *ctx);
+jas_ctx_t *jas_ctx_create(void);
+void jas_ctx_destroy(jas_ctx_t *ctx);
+jas_ctx_t *jas_get_ctx_internal(void);
+jas_ctx_t *jas_get_default_ctx(void);
+
+/******************************************************************************\
+* Codec Table.
+\******************************************************************************/
+
+static const jas_image_fmt_t jas_image_fmts[] = {
+
+#if defined(JAS_INCLUDE_PNM_CODEC)
+	{
+		.name = "pnm",
+		.desc = "Portable Graymap/Pixmap (PNM)",
+		.exts = "pnm pbm pgm ppm",
+		.ops = {
+			.decode = pnm_decode,
+			.encode = pnm_encode,
+			.validate = pnm_validate
+		},
+		.enabled = JAS_ENABLE_PNM_CODEC,
+	},
+#endif
+
+#if defined(JAS_INCLUDE_BMP_CODEC)
+	{
+		.name = "bmp",
+		.desc = "Microsoft Bitmap (BMP)",
+		.exts = "bmp",
+		.ops = {
+			.decode = bmp_decode,
+			.encode = bmp_encode,
+			.validate = bmp_validate
+		},
+		.enabled = JAS_ENABLE_BMP_CODEC,
+	},
+#endif
+
+#if defined(JAS_INCLUDE_RAS_CODEC)
+	{
+		.name = "ras",
+		.desc = "Sun Rasterfile (RAS)",
+		.exts = "ras",
+		.ops = {
+			.decode = ras_decode,
+			.encode = ras_encode,
+			.validate = ras_validate
+		},
+		.enabled = JAS_ENABLE_RAS_CODEC,
+	},
+#endif
+
+#if defined(JAS_INCLUDE_PGX_CODEC)
+	{
+		.name = "pgx",
+		.desc = "JPEG-2000 VM Format (PGX)",
+		.exts = "pgx",
+		.ops = {
+			.decode = pgx_decode,
+			.encode = pgx_encode,
+			.validate = pgx_validate
+		},
+		.enabled = JAS_ENABLE_PGX_CODEC,
+	},
+#endif
+
+#if defined(JAS_INCLUDE_JPC_CODEC) || defined(JAS_INCLUDE_JP2_CODEC)
+	{
+		.name = "jpc",
+		.desc = "JPEG-2000 Code Stream Syntax (ISO/IEC 15444-1)",
+		.exts = "jpc",
+		.ops = {
+			.decode = jpc_decode,
+			.encode = jpc_encode,
+			.validate = jpc_validate
+		},
+		.enabled = JAS_ENABLE_JPC_CODEC,
+	},
+#endif
+
+#if defined(JAS_INCLUDE_JP2_CODEC)
+	{
+		.name = "jp2",
+		.desc = "JPEG-2000 JP2 File Format Syntax (ISO/IEC 15444-1)",
+		.exts = "jp2",
+		.ops = {
+			.decode = jp2_decode,
+			.encode = jp2_encode,
+			.validate = jp2_validate
+		},
+		.enabled = JAS_ENABLE_JP2_CODEC,
+	},
+#endif
+
+#if defined(JAS_INCLUDE_MIF_CODEC) && defined(JAS_ENABLE_MIF_CODEC)
+	{
+		.name = "mif",
+		.desc = "My Image Format (MIF)",
+		.exts = "mif",
+		.ops = {
+			.decode = mif_decode,
+			.encode = mif_encode,
+			.validate = mif_validate
+		},
+		.enabled = JAS_ENABLE_MIF_CODEC,
+	},
+#endif
+
+#if defined(JAS_INCLUDE_JPG_CODEC)
+	{
+		.name = "jpg",
+		.desc = "JPEG (ISO/IEC 10918-1)",
+		.exts = "jpg",
+		.ops = {
+			.decode = jpg_decode,
+			.encode = jpg_encode,
+			.validate = jpg_validate
+		},
+		.enabled = JAS_ENABLE_JPG_CODEC,
+	},
+#endif
+
+#if defined(JAS_INCLUDE_HEIC_CODEC)
+	{
+		.name = "heic",
+		.desc = "HEIC (ISO/IEC 23008-12)",
+		.exts = "heic heif",
+		.ops = {
+			.decode = jas_heic_decode,
+			.encode = jas_heic_encode,
+			.validate = jas_heic_validate
+		},
+		.enabled = JAS_ENABLE_HEIC_CODEC,
+	},
+#endif
+
+};
+
+/******************************************************************************\
+* Configuration and Library Data.
+\******************************************************************************/
+
+/* MUTABLE_SHARED_STATE_TAG: This is mutable shared state. */
+/*
+Various user-configurable settings.
+*/
+jas_conf_t jas_conf = {
+	.initialized = 0,
+};
+
+/* MUTABLE_SHARED_STATE_TAG: This is mutable shared state. */
+jas_global_t jas_global = {
+	.initialized = 0,
+#if defined(JAS_THREADS)
+	.lock = JAS_MUTEX_INITIALIZER,
+#endif
+};
+
+#if defined(JAS_HAVE_THREAD_LOCAL)
+_Thread_local jas_ctx_t *jas_cur_ctx = 0;
+_Thread_local jas_ctx_t *jas_default_ctx = 0;
+#endif
+
+/******************************************************************************\
+* Library Configuration.
+\******************************************************************************/
+
+JAS_EXPORT
+void jas_conf_clear()
+{
+	jas_conf.multithread = 0;
+	jas_conf.allocator = 0;
+	jas_conf.enable_allocator_wrapper = 1;
+	jas_conf.max_mem = 0;
+	jas_conf.max_mem_valid = 0;
+	jas_conf.num_image_formats = sizeof(jas_image_fmts) /
+	  sizeof(jas_image_fmt_t);
+	jas_conf.image_formats = jas_image_fmts;
+#if defined(JAS_LEGACY_MODE)
+	jas_conf.dec_default_max_samples = JAS_DEC_DEFAULT_MAX_SAMPLES;
+#else
+	jas_conf.dec_default_max_samples = 0;
+#endif
+	jas_conf.debug_level = 0;
+	jas_conf.vlogmsgf = jas_vlogmsgf_stderr;
+	//jas_conf.vlogmsgf = jas_vlogmsgf_discard;
+	jas_conf.initialized = 1;
+}
+
+JAS_EXPORT
+void jas_conf_set_multithread(int multithread)
+{
+	jas_conf.multithread = multithread;
+}
+
+JAS_EXPORT
+void jas_conf_set_allocator(jas_allocator_t *allocator)
+{
+	jas_conf.allocator = allocator;
+}
+
+#ifdef JAS_COMMENT
+JAS_EXPORT
+void jas_conf_set_allocator_wrapper(int enabled)
+{
+	jas_conf.enable_allocator_wrapper = enabled;
+}
+#endif
+
+JAS_EXPORT
+void jas_conf_set_debug_level(int debug_level)
+{
+	jas_conf.debug_level = debug_level;
+}
+
+JAS_EXPORT
+void jas_conf_set_max_mem_usage(size_t max_mem)
+{
+	jas_conf.max_mem = max_mem;
+	jas_conf.max_mem_valid = 1;
+}
+
+JAS_EXPORT
+void jas_conf_set_dec_default_max_samples(size_t n)
+{
+	jas_conf.dec_default_max_samples = n;
+}
+
+JAS_EXPORT
+void jas_conf_set_vlogmsgf(int (*func)(jas_logtype_t type, const char *,
+  va_list))
+{
+	jas_conf.vlogmsgf = func;
+}
+
+/******************************************************************************\
+* Library Initialization and Cleanup.
+\******************************************************************************/
+
+/*
+Note: I think that it should actually be okay for jas_init_library and
+jas_cleanup_library to be called from different threads, since:
+the mutex ensures synchronization and also guarantees that only one
+thread can use the global context at once.
+*/
+JAS_EXPORT
+int jas_init_library()
+{
+	int ret = 0;
+#if defined(JAS_THREADS)
+	bool has_lock = false;
+#endif
+
+#if defined(JAS_THREADS)
+	jas_mutex_lock(&jas_global.lock);
+	has_lock = true;
+#endif
+
+	/*
+	The following check requires that library configuration be performed on
+	the same thread as library initialization.
+	*/
+	if (!jas_conf.initialized) {
+		jas_eprintf("FATAL ERROR: "
+		  "jas_init_library called before JasPer library configured\n");
+		abort();
+	}
+
+	/*
+	The following check requires that library configuration be performed on
+	the same thread as library initialization.
+	*/
+	assert(jas_conf.initialized);
+	assert(!jas_global.initialized);
+
+	jas_global.conf = jas_conf;
+	assert(jas_global.conf.initialized);
+
+	size_t max_mem;
+	size_t total_mem_size = jas_get_total_mem_size();
+	/*
+	NOTE: The values of jas_global.conf.max_mem_valid and max_mem are
+	used later in a deferred warning message.  So, their values should be
+	kept for later.
+	*/
+	if (!jas_global.conf.max_mem_valid) {
+		max_mem = total_mem_size / 2;
+		if (!max_mem) {
+			max_mem = JAS_DEFAULT_MAX_MEM_USAGE;
+		}
+		assert(max_mem);
+		jas_global.conf.max_mem = max_mem;
+	} else {
+		max_mem = jas_global.conf.max_mem;
+	}
+	if (max_mem > total_mem_size && total_mem_size > 0) {
+		jas_eprintf("WARNING: JasPer memory limit set to EXCESSIVELY "
+		  "LARGE value (i.e., limit exceeds system memory size (%lld > %lld)\n",
+		  (long long)max_mem, (long long)total_mem_size);
+	}
+
+#if !defined(JAS_THREADS)
+	if (jas_global.conf.multithread) {
+		jas_eprintf("library not built with multithreading support\n");
+		ret = -1;
+		goto done;
+	}
+#endif
+
+#if defined(JAS_THREADS) && !defined(JAS_HAVE_THREAD_LOCAL)
+	memset(&jas_global.cur_ctx_tss, 0, sizeof(jas_tss_t));
+	memset(&jas_global.default_ctx_tss, 0, sizeof(jas_tss_t));
+#endif
+
+	/*
+	The initialization of the global context must be performed first.
+	The memory allocator uses information from the context in order to
+	handle log messages.
+	*/
+	jas_ctx_init(&jas_global.ctx_buf);
+	jas_global.ctx = &jas_global.ctx_buf;
+
+	if (jas_global.conf.enable_allocator_wrapper) {
+		jas_allocator_t *delegate;
+		if (!jas_global.conf.allocator) {
+			jas_std_allocator_init(&jas_std_allocator);
+			delegate = &jas_std_allocator.base;
+		} else {
+			delegate = jas_global.conf.allocator;
+		}
+		jas_basic_allocator_init(&jas_basic_allocator, delegate,
+		  jas_global.conf.max_mem);
+		jas_allocator = &jas_basic_allocator.base;
+	} else {
+		if (!jas_global.conf.allocator) {
+			jas_std_allocator_init(&jas_std_allocator);
+			jas_allocator = &jas_std_allocator.base;
+		} else {
+			jas_allocator = jas_global.conf.allocator;
+		}
+	}
+
+#if defined(JAS_THREADS) && !defined(JAS_HAVE_THREAD_LOCAL)
+	if ((status = jas_tss_create(&jas_global.cur_ctx_tss, 0))) {
+		jas_eprintf("cannot create thread-specific storage %d\n", status);
+		ret = -1;
+		goto done;
+	}
+	if ((status = jas_tss_create(&jas_global.default_ctx_tss, 0))) {
+		jas_eprintf("cannot create thread-specific storage %d\n", status);
+		ret = -1;
+		goto done;
+	}
+#endif
+
+	jas_global.ctx->dec_default_max_samples =
+	  jas_global.conf.dec_default_max_samples;
+	jas_global.ctx->debug_level = jas_global.conf.debug_level;
+	jas_global.ctx->image_numfmts = 0;
+
+	jas_global.initialized = 1;
+
+#if defined(JAS_THREADS)
+	jas_mutex_unlock(&jas_global.lock);
+	has_lock = false;
+#endif
+
+	JAS_LOGDEBUGF(1, "JasPer library version: %s (%d.%d.%d)\n", JAS_VERSION,
+	  JAS_VERSION_MAJOR, JAS_VERSION_MINOR, JAS_VERSION_PATCH);
+
+	if (!jas_global.conf.max_mem_valid) {
+		jas_eprintf(
+		  "warning: The application program did not set the memory limit "
+		  "for the JasPer library.\n"
+		  );
+		jas_eprintf(
+		  "warning: The JasPer memory limit is being defaulted to a "
+		  "value that may be inappropriate for the system.  If the default "
+		  "is too small, some reasonable encoding/decoding operations will "
+		  "fail.  If the default is too large, security vulnerabilities "
+		  "will result (e.g., decoding a malicious image could exhaust all "
+		  "memory and crash the system.\n"
+		  );
+		jas_eprintf("warning: setting JasPer memory limit to %lld bytes\n",
+		  (long long)max_mem);
+	}
+
+	JAS_LOGDEBUGF(1, "JasPer library initialization complete\n");
+	JAS_LOGDEBUGF(1, "total memory size: %zu\n", jas_get_total_mem_size());
+	JAS_LOGDEBUGF(1, "JasPer library memory limit: %zu\n", max_mem);
+
+#if !defined(JAS_THREADS) || (defined(JAS_THREADS) && !defined(JAS_HAVE_THREAD_LOCAL))
+done:
+#endif
+#if defined(JAS_THREADS)
+	if (has_lock) {
+		jas_mutex_unlock(&jas_global.lock);
+	}
+#endif
+
+	return ret;
+}
+
+JAS_EXPORT
+int jas_cleanup_library()
+{
+	jas_ctx_t *ctx;
+#if defined(JAS_THREADS)
+	bool has_lock = false;
+#endif
+
+#if defined(JAS_THREADS)
+	jas_mutex_lock(&jas_global.lock);
+	has_lock = true;
+#endif
+
+	if (!jas_global.initialized) {
+		jas_eprintf("FATAL ERROR: "
+		  "jas_cleanup_library called before JasPer library initialized\n");
+		abort();
+	}
+	if (jas_global.num_active_threads) {
+		jas_eprintf("FATAL ERROR: "
+		  "jas_cleanup_library called with active JasPer threads\n");
+		abort();
+	}
+
+	assert(jas_global.initialized);
+	assert(!jas_global.num_active_threads);
+
+	JAS_LOGDEBUGF(10, "jas_cleanup_library invoked\n");
+
+	ctx = &jas_global.ctx_buf;
+	jas_ctx_cleanup(ctx);
+	//jas_context_set_debug_level(ctx, 0);
+
+#if defined(JAS_THREADS) && !defined(JAS_HAVE_THREAD_LOCAL)
+	jas_tss_delete(jas_global.cur_ctx_tss);
+	jas_tss_delete(jas_global.default_ctx_tss);
+#endif
+
+	assert(jas_allocator);
+	jas_allocator_cleanup(jas_allocator);
+	jas_allocator = 0;
+
+	JAS_LOGDEBUGF(10, "jas_cleanup_library returning\n");
+
+	jas_global.initialized = 0;
+	jas_conf.initialized = 0;
+
+#if defined(JAS_THREADS)
+	if (has_lock) {
+		jas_mutex_unlock(&jas_global.lock);
+	}
+#endif
+
+	return 0;
+}
+
+/******************************************************************************\
+* Thread Initialization and Cleanup.
+\******************************************************************************/
+
+JAS_EXPORT
+int jas_init_thread()
+{
+	int ret = 0;
+	jas_ctx_t *ctx;
+#if defined(JAS_THREADS)
+	bool has_lock = false;
+#endif
+
+	/*
+	The default context must be established as soon as possible.
+	Prior to the default context being initialized the global state in
+	jas_global.conf is used for some settings (e.g., debug level
+	and logging function).
+	Due to the use of this global state, we must hold the lock on
+	this state until the default context is initialized.	
+	*/
+#if defined(JAS_THREADS)
+	jas_mutex_lock(&jas_global.lock);
+	has_lock = true;
+#endif
+
+	if (!jas_global.initialized) {
+		jas_eprintf("FATAL ERROR: "
+		  "jas_init_thread called before JasPer library initialized\n");
+		abort();
+	}
+	assert(jas_global.initialized);
+#if !defined(JAS_THREADS)
+	assert(jas_global.num_active_threads == 0);
+#endif
+	assert(jas_get_ctx() == jas_global.ctx);
+	assert(!jas_get_default_ctx() || jas_get_default_ctx() ==
+	  &jas_global.ctx_buf);
+
+	if (!(ctx = jas_ctx_create())) {
+		ret = -1;
+		goto done;
+	}
+	jas_set_ctx(ctx);
+	/* As of this point, shared use of jas_global.conf is no longer needed. */
+	jas_set_default_ctx(ctx);
+	++jas_global.num_active_threads;
+
+#if defined(JAS_THREADS)
+	jas_mutex_unlock(&jas_global.lock);
+	has_lock = false;
+#endif
+
+done:
+#if defined(JAS_THREADS)
+	if (has_lock) {
+		jas_mutex_unlock(&jas_global.lock);
+	}
+#endif
+	if (ret && ctx) {
+		jas_ctx_cleanup(ctx);
+	}
+	return ret;
+}
+
+JAS_EXPORT
+int jas_cleanup_thread()
+{
+	jas_ctx_t *ctx;
+#if defined(JAS_THREADS)
+	bool has_lock = false;
+#endif
+
+#if defined(JAS_THREADS)
+	jas_mutex_lock(&jas_global.lock);
+	has_lock = true;
+#endif
+
+	if (!jas_get_default_ctx()) {
+		jas_eprintf("FATAL ERROR: "
+		  "jas_cleanup_thread called before JasPer thread initialized\n");
+		abort();
+	}
+
+	assert(jas_get_default_ctx());
+	assert(jas_get_ctx());
+
+	/* Ensure that the library user is not doing something insane. */
+	assert(jas_get_ctx() == jas_get_default_ctx());
+
+	ctx = jas_get_default_ctx();
+	jas_set_default_ctx(0);
+	jas_set_ctx(0);
+	/*
+	As soon as we clear the current context, the global shared state
+	jas_conf.conf is used for various settings (e.g., debug level and
+	logging function).
+	*/
+
+	jas_ctx_destroy(ctx);
+	--jas_global.num_active_threads;
+
+#if defined(JAS_THREADS)
+	if (has_lock) {
+		jas_mutex_unlock(&jas_global.lock);
+	}
+#endif
+
+	return 0;
+}
+
+/******************************************************************************\
+* Legacy Library Initialization and Cleanup.
+\******************************************************************************/
+
+JAS_EXPORT
+int jas_init()
+{
+	jas_deprecated("use of jas_init is deprecated\n");
+	jas_conf_clear();
+	if (jas_init_library()) {
+		return -1;
+	}
+	if (jas_init_thread()) {
+		jas_cleanup_library();
+		return -1;
+	}
+	return 0;
+}
+
+JAS_EXPORT
+void jas_cleanup()
+{
+	jas_deprecated("use of jas_cleanup is deprecated\n");
+	if (jas_cleanup_thread()) {
+		jas_eprintf("jas_cleanup_thread failed\n");
+	}
+	if (jas_cleanup_library()) {
+		jas_eprintf("jas_cleanup_library failed\n");
+	}
+}
+
+/******************************************************************************\
 * Code.
 \******************************************************************************/
 
 /* Initialize the image format table. */
-JAS_DLLEXPORT
-int jas_init(void)
+static int jas_init_codecs(jas_ctx_t *ctx)
 {
-	jas_image_fmtops_t fmtops;
-	int fmtid = 0;
+	int ret = 0;
+	int i;
+	const jas_image_fmt_t *fmt;
+	for (fmt = jas_global.conf.image_formats, i = 0;
+	  i < jas_global.conf.num_image_formats; ++fmt, ++i) {
+		JAS_LOGDEBUGF(10, "adding image format %s %s\n", fmt->name, fmt->exts);
+		if (jas_image_addfmt_internal(ctx->image_fmtinfos, &ctx->image_numfmts,
+		  i, fmt->name, fmt->exts, fmt->desc, &fmt->ops)) {
+			ret = -1;
+			break;
+		}
+		assert(ctx->image_fmtinfos[i].id == i);
+		ctx->image_fmtinfos[i].enabled = fmt->enabled;
+	}
+	if (ret) {
+		jas_image_clearfmts_internal(ctx->image_fmtinfos, &ctx->image_numfmts);
+	}
+	return ret;
+}
 
-#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);
+/******************************************************************************\
+* Context management (e.g., creation and destruction).
+\******************************************************************************/
+
+void jas_ctx_init(jas_ctx_t *ctx)
+{
+	ctx->dec_default_max_samples = jas_conf.dec_default_max_samples;
+	ctx->debug_level = jas_conf.debug_level;
+	ctx->vlogmsgf = jas_conf.vlogmsgf;
+	ctx->image_numfmts = 0;
+	memset(ctx->image_fmtinfos, 0, sizeof(ctx->image_fmtinfos));
+}
+
+jas_ctx_t *jas_ctx_create()
+{
+	jas_ctx_t *ctx;
+	if (!(ctx = jas_malloc(sizeof(jas_ctx_t)))) {
+		return 0;
+	}
+	jas_ctx_init(ctx);
+	jas_init_codecs(ctx);
+	return ctx;
+}
+
+JAS_EXPORT
+jas_context_t jas_context_create()
+{
+	return JAS_CAST(jas_context_t, jas_ctx_create());
+}
+
+void jas_ctx_cleanup(jas_ctx_t *ctx)
+{
+	jas_image_clearfmts_internal(ctx->image_fmtinfos, &ctx->image_numfmts);
+}
+
+void jas_ctx_destroy(jas_ctx_t *ctx)
+{
+	jas_ctx_cleanup(ctx);
+	jas_free(ctx);
+}
+
+JAS_EXPORT
+void jas_context_destroy(jas_context_t context)
+{
+	jas_ctx_destroy(JAS_CAST(jas_ctx_t *, context));
+}
+
+jas_ctx_t *jas_get_ctx_internal()
+{
+#if defined(JAS_THREADS)
+	jas_ctx_t *ctx;
+#if defined(JAS_HAVE_THREAD_LOCAL)
+	ctx = JAS_CAST(jas_ctx_t *, jas_cur_ctx);
+#else
+	ctx = JAS_CAST(jas_ctx_t *, jas_tss_get(jas_global.cur_ctx_tss));
 #endif
+	if (!ctx) {
+		ctx = jas_global.ctx;
+	}
+	assert(ctx);
+	return ctx;
+#else
+	return (jas_global.ctx) ? jas_global.ctx : &jas_global.ctx_buf;
+#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);
+JAS_EXPORT
+jas_context_t jas_get_context()
+{
+	return JAS_CAST(jas_context_t, jas_get_ctx());
+}
+
+JAS_EXPORT
+jas_context_t jas_get_default_context()
+{
+	return JAS_CAST(jas_context_t, jas_get_default_ctx());
+}
+
+JAS_EXPORT
+void jas_set_context(jas_context_t context)
+{
+	jas_set_ctx(JAS_CAST(jas_ctx_t *, context));
+}
+
+void jas_set_ctx(jas_ctx_t *ctx)
+{
+#if defined(JAS_THREADS)
+#if defined(JAS_HAVE_THREAD_LOCAL)
+	jas_cur_ctx = ctx;
+#else
+	if (jas_tss_set(jas_global.cur_ctx_tss, ctx)) {
+		assert(0);
+		abort();
+	}
 #endif
+#else
+	jas_global.ctx = JAS_CAST(jas_ctx_t *, ctx);
+#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);
+jas_ctx_t *jas_get_default_ctx()
+{
+	jas_ctx_t *ctx;
 
-	return 0;
+#if defined(JAS_THREADS)
+#	if defined(JAS_HAVE_THREAD_LOCAL)
+	ctx = jas_default_ctx;
+#	else
+	ctx = JAS_CAST(jas_ctx_t *, jas_tss_get(jas_global.default_ctx_tss));
+#	endif
+	if (!ctx) {
+		ctx = jas_global.ctx;
+	}
+#else
+	ctx = (jas_global.ctx) ? jas_global.ctx : &jas_global.ctx_buf;
+#endif
+	//JAS_LOGDEBUGF(100, "jas_get_ctx() returning %p", JAS_CAST(void *, ctx));
+
+	return ctx;
 }
 
-JAS_DLLEXPORT
-void jas_cleanup(void)
+void jas_set_default_ctx(jas_ctx_t *ctx)
 {
-	jas_image_clearfmts();
+#if defined(JAS_THREADS)
+#if defined(JAS_HAVE_THREAD_LOCAL)
+	jas_default_ctx = ctx;
+#else
+	if (jas_tss_set(jas_global.default_ctx_tss, ctx)) {
+		assert(0);
+		abort();
+	}
+#endif
+#else
+	jas_global.ctx = JAS_CAST(jas_ctx_t *, ctx);
+#endif
+}
+
+/******************************************************************************\
+* Context state management.
+\******************************************************************************/
+
+JAS_EXPORT
+void jas_set_debug_level(int debug_level)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	ctx->debug_level = debug_level;
+}
+
+JAS_EXPORT
+int jas_get_debug_level_internal(void)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	return ctx->debug_level;
+}
+
+JAS_EXPORT
+void jas_set_dec_default_max_samples(size_t max_samples)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	ctx->dec_default_max_samples = max_samples;
+}
+
+JAS_EXPORT
+size_t jas_get_dec_default_max_samples_internal(void)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	return ctx->dec_default_max_samples;
+}
+
+JAS_EXPORT
+void jas_set_vlogmsgf(int (*func)(jas_logtype_t, const char *, va_list))
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	ctx->vlogmsgf = func;
+}
+
+JAS_EXPORT
+jas_vlogmsgf_t *jas_get_vlogmsgf_internal(void)
+{
+	jas_ctx_t *ctx = jas_get_ctx();
+	return ctx->vlogmsgf;
 }
--- /dev/null
+++ b/jas_malloc.c
@@ -1,0 +1,651 @@
+/*
+ * 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.
+\******************************************************************************/
+
+#define JAS_FOR_INTERNAL_USE_ONLY
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+#include "jasper/jas_math.h"
+
+#if defined(__linux__)
+#	include <sys/sysinfo.h>
+#elif defined(__APPLE__)
+#	include <sys/types.h>
+#	include <sys/sysctl.h>
+#elif defined(__unix__) && (!defined(__linux__) && !defined(__APPLE__))
+#	include <unistd.h>
+#elif defined(_WIN32)
+#	include <windows.h>
+#	include <sysinfoapi.h>
+#endif
+
+/******************************************************************************\
+* Data.
+\******************************************************************************/
+
+/* MUTABLE_SHARED_STATE_TAG: This is mutable shared state. */
+/* The memory allocator object to be used for all memory allocation. */
+jas_allocator_t *jas_allocator = 0;
+
+/* MUTABLE_SHARED_STATE_TAG: This is mutable shared state. */
+jas_std_allocator_t jas_std_allocator = {
+	.base = {
+		.cleanup = 0,
+		.alloc = 0,
+		.free = 0,
+		.realloc = 0,
+	},
+};
+
+/* MUTABLE_SHARED_STATE_TAG: This is mutable shared state. */
+jas_basic_allocator_t jas_basic_allocator = {
+	.base = {
+		.cleanup = 0,
+		.alloc = 0,
+		.free = 0,
+		.realloc = 0,
+	},
+	.delegate = 0,
+	.mem = 0,
+	.max_mem = 0,
+};
+
+/******************************************************************************\
+* Basic memory allocation and deallocation primitives.
+\******************************************************************************/
+
+JAS_EXPORT
+void *jas_malloc(size_t size)
+{
+	assert(jas_allocator);
+	void *result;
+	JAS_LOGDEBUGF(101, "jas_malloc(%zu)\n", size);
+#if defined(JAS_MALLOC_RETURN_NULL_PTR_FOR_ZERO_SIZE)
+	result = size ? (jas_allocator->alloc)(jas_allocator, size) : 0;
+#else
+	result = (jas_allocator->alloc)(jas_allocator, size ? size : 1);
+#endif
+	JAS_LOGDEBUGF(100, "jas_malloc(%zu) -> %p\n", size, result);
+	return result;
+}
+
+JAS_EXPORT
+void *jas_realloc(void *ptr, size_t size)
+{
+	assert(jas_allocator);
+	void *result;
+	JAS_LOGDEBUGF(101, "jas_realloc(%p, %zu)\n", ptr, size);
+	if (!size) {
+		jas_logwarnf("warning: zero size reallocations are unwise "
+		  "(and have undefined behavior as of C23)\n");
+	}
+	if (!ptr) {
+		if (size) {
+			/* Handle a new allocation of nonzero size. */
+			result = (jas_allocator->alloc)(jas_allocator, size);
+			JAS_LOGDEBUGF(101, "jas_realloc: alloc(%p, %zu) -> %p\n",
+			  jas_allocator, size, result);
+		} else {
+			/* Handle a new allocation of zero size. */
+#if defined(JAS_MALLOC_RETURN_NULL_PTR_FOR_ZERO_SIZE)
+			result = 0;
+			JAS_LOGDEBUGF(101, "jas_realloc: no-op -> %p\n", result);
+#else
+			result = (jas_allocator->alloc)(jas_allocator, 1);
+			JAS_LOGDEBUGF(101, "jas_realloc: alloc(%p, %p, %zu) -> %p\n",
+			  jas_allocator, ptr, size, result);
+#endif
+		}
+	} else {
+		result = (jas_allocator->realloc)(jas_allocator, ptr, size);
+		JAS_LOGDEBUGF(100, "jas_realloc: realloc(%p, %p, %zu) -> %p\n",
+		  jas_allocator, ptr, size, result);
+	}
+	return result;
+}
+
+JAS_EXPORT
+void jas_free(void *ptr)
+{
+	assert(jas_allocator);
+	JAS_LOGDEBUGF(100, "jas_free(%p)\n", ptr);
+	(jas_allocator->free)(jas_allocator, ptr);
+}
+
+/******************************************************************************\
+* Additional memory allocation and deallocation primitives
+* (mainly for overflow checking).
+\******************************************************************************/
+
+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;
+}
+
+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);
+}
+
+/******************************************************************************\
+\******************************************************************************/
+
+JAS_EXPORT
+void jas_allocator_cleanup(jas_allocator_t *allocator)
+{
+	if (allocator->cleanup) {
+		(allocator->cleanup)(allocator);
+	}
+}
+
+/******************************************************************************\
+\******************************************************************************/
+
+JAS_EXPORT
+void *jas_std_alloc(jas_allocator_t *allocator, size_t size);
+JAS_EXPORT
+void *jas_std_realloc(jas_allocator_t *allocator, void *ptr, size_t size);
+JAS_EXPORT
+void jas_std_free(jas_allocator_t *allocator, void *ptr);
+
+JAS_EXPORT
+void jas_std_allocator_init(jas_std_allocator_t *allocator)
+{
+	JAS_CAST(void, allocator);
+	allocator->base.cleanup = 0;
+	allocator->base.alloc = jas_std_alloc;
+	allocator->base.free = jas_std_free;
+	allocator->base.realloc = jas_std_realloc;
+}
+
+JAS_EXPORT
+void *jas_std_alloc(jas_allocator_t *allocator, size_t size)
+{
+	JAS_UNUSED(allocator);
+	JAS_LOGDEBUGF(111, "jas_std_alloc(%zu)\n", size);
+	void* result = malloc(size);
+	JAS_LOGDEBUGF(110, "jas_std_alloc(%zu) -> %p\n", size, result);
+	return result;
+}
+
+JAS_EXPORT
+void *jas_std_realloc(jas_allocator_t *allocator, void *ptr, size_t size)
+{
+	JAS_UNUSED(allocator);
+	JAS_LOGDEBUGF(111, "jas_std_realloc(%p, %zu)\n", allocator, size);
+	void *result = realloc(ptr, size);
+	JAS_LOGDEBUGF(110, "jas_std_realloc(%zu) -> %p\n", size, result);
+	return result;
+}
+
+JAS_EXPORT
+void jas_std_free(jas_allocator_t *allocator, void *ptr)
+{
+	JAS_UNUSED(allocator);
+	JAS_LOGDEBUGF(111, "jas_std_free(%p, %p)\n", allocator, ptr);
+	free(ptr);
+}
+
+/******************************************************************************\
+\******************************************************************************/
+
+JAS_EXPORT
+void *jas_basic_alloc(jas_allocator_t *allocator, size_t size);
+JAS_EXPORT
+void *jas_basic_realloc(jas_allocator_t *allocator, void *ptr, size_t size);
+JAS_EXPORT
+void jas_basic_free(jas_allocator_t *allocator, void *ptr);
+JAS_EXPORT
+void jas_basic_cleanup(jas_allocator_t *allocator);
+
+#define JAS_BMA_MAGIC 0xdeadbeefULL
+
+typedef struct {
+	unsigned long long magic;
+	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))
+
+static void jas_mb_init(jas_mb_t *mb, size_t size)
+{
+	mb->magic = JAS_BMA_MAGIC;
+	mb->size = size;
+}
+
+static void jas_mb_destroy(jas_mb_t *mb)
+{
+	mb->magic = 0;
+	mb->size = 0;
+}
+
+static void *jas_mb_get_data(jas_mb_t *mb)
+{
+	assert(mb->magic == JAS_BMA_MAGIC);
+	return JAS_CAST(void *, JAS_CAST(max_align_t *, mb) + JAS_MB_ADJUST);
+}
+
+static jas_mb_t *jas_get_mb(void *ptr)
+{
+	assert(ptr);
+	jas_mb_t *mb = JAS_CAST(jas_mb_t *,
+	  JAS_CAST(max_align_t *, ptr) - JAS_MB_ADJUST);
+	assert(mb->magic == JAS_BMA_MAGIC);
+	/* This is one check that I do not want disabled with NDEBUG. */
+	if (mb->magic != JAS_BMA_MAGIC) {
+		/* This line of code should never be reached. */
+		assert(0);
+		abort();
+	}
+	return mb;
+}
+
+void jas_set_max_mem_usage(size_t max_mem)
+{
+	assert(jas_allocator == JAS_CAST(jas_allocator_t*, &jas_basic_allocator));
+	jas_basic_allocator_t *allocator = JAS_CAST(jas_basic_allocator_t *,
+	  jas_allocator);
+#if defined(JAS_THREADS)
+	jas_mutex_lock(&allocator->mutex);
+#endif
+	allocator->max_mem = (!max_mem || allocator->mem <= max_mem) ? max_mem :
+	  allocator->mem;
+#if defined(JAS_THREADS)
+	jas_mutex_unlock(&allocator->mutex);
+#endif
+}
+
+size_t jas_get_mem_usage()
+{
+	assert(jas_allocator == JAS_CAST(jas_allocator_t*, &jas_basic_allocator));
+	jas_basic_allocator_t *allocator = JAS_CAST(jas_basic_allocator_t *,
+	  jas_allocator);
+#if defined(JAS_THREADS)
+	jas_mutex_lock(&allocator->mutex);
+#endif
+	size_t result = allocator->mem;
+#if defined(JAS_THREADS)
+	jas_mutex_unlock(&allocator->mutex);
+#endif
+	return result;
+}
+
+void jas_basic_allocator_init(jas_basic_allocator_t *allocator,
+  jas_allocator_t *delegate, size_t max_mem)
+{
+	allocator->base.cleanup = jas_basic_cleanup;
+	allocator->base.alloc = jas_basic_alloc;
+	allocator->base.free = jas_basic_free;
+	allocator->base.realloc = jas_basic_realloc;
+	allocator->delegate = delegate;
+	assert(allocator->base.cleanup != delegate->cleanup);
+	assert(allocator->base.alloc != delegate->alloc);
+	assert(allocator->base.free != delegate->free);
+	assert(allocator->base.realloc != delegate->realloc);
+	allocator->max_mem = max_mem;
+	allocator->mem = 0;
+#if defined(JAS_THREADS)
+	if (jas_mutex_init(&allocator->mutex)) {
+		/* This line of code should never be reached. */
+		assert(0);
+		abort();
+	}
+#endif
+}
+
+JAS_EXPORT
+void jas_basic_cleanup(jas_allocator_t *allocator)
+{
+	jas_basic_allocator_t *a = JAS_CAST(jas_basic_allocator_t *,
+	  allocator);
+	if (a->delegate->cleanup) {
+		(a->delegate->cleanup)(allocator);
+	}
+#if defined(JAS_THREADS)
+	jas_mutex_cleanup(&a->mutex);
+#endif
+}
+
+JAS_EXPORT
+void *jas_basic_alloc(jas_allocator_t *allocator, size_t size)
+{
+	void *result;
+	jas_mb_t *mb;
+	size_t ext_size;
+	size_t mem;
+	jas_basic_allocator_t *a = JAS_CAST(jas_basic_allocator_t *, allocator);
+
+	JAS_LOGDEBUGF(100, "jas_basic_alloc(%p, %zu)\n", allocator, size);
+	JAS_LOGDEBUGF(102, "max_mem=%zu; mem=%zu\n", a->max_mem, a->mem);
+#if defined(JAS_MALLOC_RETURN_NULL_PTR_FOR_ZERO_SIZE)
+	if (!size) {
+		result = 0;
+		goto done;
+	}
+#endif
+	if (!jas_safe_size_add(size, JAS_MB_SIZE, &ext_size)) {
+		jas_logerrorf("requested memory size is too large (%zu)\n", size);
+		result = 0;
+		goto done;
+	}
+
+#if defined(JAS_THREADS)
+	jas_mutex_lock(&a->mutex);
+	has_lock = true;
+#endif
+
+	/*
+	Calculate the amount of memory that would be allocated after the requested
+	allocation is performed, being careful to ensure that this computation
+	does not cause overflow.  Then, ensure that the computed value does not
+	exceed the memory usage limit.
+	*/
+	if (!jas_safe_size_add(a->mem, ext_size, &mem) || mem > a->max_mem) {
+		jas_logerrorf("maximum memory limit (%lld) would be exceeded\n",
+		  (long long)a->max_mem);
+		result = 0;
+		goto done;
+	}
+
+	/*
+	Perform the requested allocation using the delegated-to allocator.
+	*/
+	JAS_LOGDEBUGF(100, "jas_basic_alloc: alloc(%p, %zu)\n", a->delegate,
+	  ext_size);
+	if ((mb = (a->delegate->alloc)(a->delegate, ext_size))) {
+		jas_mb_init(mb, ext_size);
+		result = jas_mb_get_data(mb);
+		a->mem = mem;
+	} else {
+		result = 0;
+	}
+
+done:
+#if defined(JAS_THREADS)
+	if (has_lock) {
+		jas_mutex_unlock(&a->mutex);
+	}
+#endif
+
+	JAS_LOGDEBUGF(99, "jas_basic_alloc(%p, %zu) -> %p (mb=%p)\n", allocator,
+	  size, result, mb);
+	JAS_LOGDEBUGF(102, "max_mem=%zu; mem=%zu\n", a->max_mem, a->mem);
+
+	return result;
+}
+
+JAS_EXPORT
+void *jas_basic_realloc(jas_allocator_t *allocator, void *ptr, size_t size)
+{
+	void *result;
+	jas_mb_t *old_mb;
+	size_t old_ext_size;
+	jas_mb_t *mb;
+	size_t ext_size;
+	size_t mem;
+	jas_basic_allocator_t *a = JAS_CAST(jas_basic_allocator_t *, allocator);
+
+	JAS_LOGDEBUGF(100, "jas_basic_realloc(%p, %p, %zu)\n", allocator, ptr,
+	  size);
+	/*
+	Check for a realloc operation that is equivalent to an alloc operation.
+	*/
+	if (!ptr) {
+		result = jas_basic_alloc(allocator, size);
+		goto done;
+	}
+	/*
+	Check for a realloc operation that is equivalent to a zero-sized
+	allocation/reallocation.
+	*/
+	if (ptr && !size) {
+#if defined(JAS_MALLOC_RETURN_NULL_PTR_FOR_ZERO_SIZE)
+		jas_basic_free(allocator, ptr);
+		result = 0;
+#else
+        if ((result = jas_basic_alloc(allocator, 1))) {
+			jas_basic_free(allocator, ptr);
+		}
+#endif
+		goto done;
+	}
+
+	if (!jas_safe_size_add(size, JAS_MB_SIZE, &ext_size)) {
+		jas_logerrorf("requested memory size is too large (%zu)\n", size);
+		result = 0;
+		goto done;
+	}
+
+#if defined(JAS_THREADS)
+	jas_mutex_lock(&a->mutex);
+	has_lock = true;
+#endif
+
+	old_mb = jas_get_mb(ptr);
+	old_ext_size = old_mb->size;
+	JAS_LOGDEBUGF(101, "jas_basic_realloc: old_mb=%p; old_ext_size=%zu\n",
+	  old_mb, old_ext_size);
+	/*
+	Skip performing any allocation if the currently-allocated block is
+	sufficiently large to accommodate the allocation request.
+	*/
+	if (ext_size <= old_ext_size) {
+		result = jas_mb_get_data(old_mb);
+		goto done;
+	}
+
+	if (!jas_safe_size_add(a->mem, ext_size - old_ext_size, &mem) ||
+	  mem > a->max_mem) {
+		jas_logerrorf("maximum memory limit (%zu) would be exceeded\n",
+		  a->max_mem);
+		result = 0;
+		goto done;
+	}
+
+	JAS_LOGDEBUGF(100, "jas_basic_realloc: realloc(%p, %p, %zu)\n",
+	  a->delegate, old_mb, ext_size);
+	jas_mb_destroy(old_mb);
+	if ((mb = (a->delegate->realloc)(a->delegate, old_mb, ext_size))) {
+		jas_mb_init(mb, ext_size);
+		result = jas_mb_get_data(mb);
+		a->mem = mem;
+	} else {
+		jas_mb_init(old_mb, old_ext_size);
+		result = 0;
+	}
+
+done:
+#if defined(JAS_THREADS)
+	if (has_lock) {
+		jas_mutex_unlock(&a->mutex);
+	}
+#endif
+
+	JAS_LOGDEBUGF(100, "jas_basic_realloc(%p, %p, %zu) -> %p (%p)\n", allocator,
+	  ptr, size, result, mb);
+	JAS_LOGDEBUGF(102, "max_mem=%zu; mem=%zu\n", a->max_mem, a->mem);
+
+	return result;
+}
+
+JAS_EXPORT
+void jas_basic_free(jas_allocator_t *allocator, void *ptr)
+{
+	jas_mb_t *mb;
+	size_t ext_size;
+	jas_basic_allocator_t *a = JAS_CAST(jas_basic_allocator_t *, allocator);
+
+
+	JAS_LOGDEBUGF(100, "jas_basic_free(%p)\n", ptr);
+	if (ptr) {
+#if defined(JAS_THREADS)
+		jas_mutex_lock(&a->mutex);
+#endif
+		mb = jas_get_mb(ptr);
+		ext_size = mb->size;
+		JAS_LOGDEBUGF(101, "jas_basic_free(%p, %p) (mb=%p; ext_size=%zu)\n",
+		  allocator, ptr, mb, ext_size);
+		if (!jas_safe_size_sub(a->mem, ext_size, &a->mem)) {
+			jas_logerrorf("heap corruption detected (%zu exceeds %zu)\n",
+			  ext_size, a->mem);
+			/* This line of code should never be reached. */
+			assert(0);
+			abort();
+		}
+		JAS_LOGDEBUGF(100, "jas_basic_free: free(%p, %p)\n", a->delegate, mb);
+		jas_mb_destroy(mb);
+		(a->delegate->free)(a->delegate, mb);
+#if defined(JAS_THREADS)
+		jas_mutex_unlock(&a->mutex);
+#endif
+	}
+	JAS_LOGDEBUGF(102, "max_mem=%zu; mem=%zu\n", a->max_mem, a->mem);
+
+}
+
+/******************************************************************************\
+\******************************************************************************/
+
+size_t jas_get_total_mem_size()
+{
+#if defined(__linux__)
+	struct sysinfo buf;
+	if (sysinfo(&buf)) {
+		return 0;
+	}
+	return buf.totalram * buf.mem_unit;
+#elif defined(__APPLE__)
+	int mib[] = {CTL_HW, HW_MEMSIZE};
+	uint64_t value = 0;
+	size_t length = sizeof(value);
+	if (sysctl(mib, 2, &value, &length, 0, 0)) {
+		return 0;
+	}
+	return JAS_CAST(size_t, value);
+#elif defined(__unix__) && (!defined(__linux__) && !defined(__APPLE__))
+	/*
+	Reference:
+	https://stackoverflow.com/questions/2513505/how-to-get-available-memory-c-g
+	*/
+	long pages = sysconf(_SC_PHYS_PAGES);
+	long page_size = sysconf(_SC_PAGE_SIZE);
+	return pages * page_size;
+#elif defined(_WIN32)
+	/*
+	Reference:
+	https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getphysicallyinstalledsystemmemory
+	*/
+	ULONGLONG size;
+	if (!GetPhysicallyInstalledSystemMemory(&size)) {
+		return 0;
+	}
+	return 1024 * size;
+#else
+	return 0;
+#endif
+}
--- a/jas_seq.c
+++ b/jas_seq.c
@@ -71,9 +71,12 @@
 * Includes.
 \******************************************************************************/
 
+#define JAS_FOR_INTERNAL_USE_ONLY
+
 #include "jasper/jas_seq.h"
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
 
 /******************************************************************************\
 * Constructors and destructors.
@@ -100,6 +103,7 @@
 	jas_matind_t i;
 	size_t size;
 
+
 	if (numrows < 0 || numcols < 0) {
 		return NULL;
 	}
@@ -132,9 +136,7 @@
 		  sizeof(jas_seqent_t)))) {
 			goto error;
 		}
-
-		memset(matrix->data_, 0,
-		       matrix->datasize_ * sizeof(jas_seqent_t));
+		memset(matrix->data_, 0, matrix->datasize_ * sizeof(jas_seqent_t));
 	}
 
 	for (i = 0; i < numrows; ++i) {
@@ -201,11 +203,11 @@
   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_)
+	    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);
+	}
+	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,
--- a/jas_stream.c
+++ b/jas_stream.c
@@ -71,6 +71,15 @@
 * Includes.
 \******************************************************************************/
 
+#include "jasper/jas_config.h"
+
+/* The following must come before any direct/indirect inclusion of stdlib.h. */
+#if defined(JAS_HAVE_MKOSTEMP)
+#define _GNU_SOURCE
+#endif
+
+#define JAS_FOR_INTERNAL_USE_ONLY
+
 #include "jasper/jas_stream.h"
 #include "jasper/jas_debug.h"
 #include "jasper/jas_types.h"
@@ -77,6 +86,16 @@
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_math.h"
 
+/*
+O_CLOEXEC is a Linux-specific flag which helps avoid leaking file descriptors
+to child processes created by another thread; for simplicity, we always
+specify it, and this definition is a fallback for systems where this feature
+is not available
+*/
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+
 /******************************************************************************\
 * Local function prototypes.
 \******************************************************************************/
@@ -87,13 +106,21 @@
 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 ssize_t mem_read(jas_stream_obj_t *obj, char *buf, size_t cnt);
+static ssize_t mem_write(jas_stream_obj_t *obj, const char *buf,
+  size_t 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 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 ssize_t sfile_read(jas_stream_obj_t *obj, char *buf, size_t cnt);
+static ssize_t sfile_write(jas_stream_obj_t *obj, const char *buf,
+  size_t cnt);
+static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin);
+static int sfile_close(jas_stream_obj_t *obj);
+
+static ssize_t file_read(jas_stream_obj_t *obj, char *buf, size_t cnt);
+static ssize_t file_write(jas_stream_obj_t *obj, const char *buf,
+  size_t cnt);
 static long file_seek(jas_stream_obj_t *obj, long offset, int origin);
 static int file_close(jas_stream_obj_t *obj);
 
@@ -108,6 +135,13 @@
 	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,
@@ -142,17 +176,12 @@
 	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 *jas_stream_memopen(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));
+	JAS_LOGDEBUGF(100, "jas_stream_memopen(%p, %zu)\n", buf, bufsize);
 
 	assert((buf && bufsize > 0) || (!buf));
 
@@ -201,8 +230,8 @@
 		jas_stream_close(stream);
 		return 0;
 	}
-	JAS_DBGLOG(100, ("jas_stream_memopen2 buffer buf=%p myalloc=%d\n",
-	  obj->buf_, obj->myalloc_));
+	JAS_LOGDEBUGF(100, "jas_stream_memopen 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,
@@ -218,40 +247,13 @@
 }
 
 /*
-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).
+This function is deprecated.
+It will be removed eventually.
 */
-jas_stream_t *jas_stream_memopen(char *buf, int bufsize)
+jas_stream_t *jas_stream_memopen2(char *buf, size_t bufsize)
 {
-	char *new_buf;
-	size_t new_bufsize;
-
-	JAS_DBGLOG(100, ("jas_stream_memopen(%p, %d)\n", buf, bufsize));
-	if (bufsize < 0 || (buf && bufsize <= 0)) {
-		jas_eprintf("Invalid use of jas_stream_memopen detected.\n");
-		return nil;
-	}
-	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_deprecated("jas_stream_memopen2 is deprecated\n");
+	return jas_stream_memopen(buf, bufsize);
 }
 
 jas_stream_t *jas_stream_fopen(const char *filename, const char *mode)
@@ -260,7 +262,7 @@
 	jas_stream_fileobj_t *obj;
 	int openflags;
 
-	JAS_DBGLOG(100, ("jas_stream_fopen(\"%s\", \"%s\")\n", filename, mode));
+	JAS_LOGDEBUGF(100, "jas_stream_fopen(\"%s\", \"%s\")\n", filename, mode);
 
 	/* Allocate a stream object. */
 	if (!(stream = jas_stream_create())) {
@@ -273,19 +275,25 @@
 	/* Determine the correct flags to use for opening the file. */
 	if ((stream->openmode_ & JAS_STREAM_READ) &&
 	  (stream->openmode_ & JAS_STREAM_WRITE)) {
-		openflags = ORDWR;
+		openflags = O_RDWR;
 	} else if (stream->openmode_ & JAS_STREAM_READ) {
-		openflags = OREAD;
+		openflags = O_RDONLY;
 	} else if (stream->openmode_ & JAS_STREAM_WRITE) {
-		openflags = OWRITE;
+		openflags = O_WRONLY;
 	} else {
 		openflags = 0;
 	}
+	if (stream->openmode_ & JAS_STREAM_APPEND) {
+		openflags |= O_APPEND;
+	}
+	if (stream->openmode_ & JAS_STREAM_BINARY) {
+		openflags |= O_BINARY;
+	}
 	if (stream->openmode_ & JAS_STREAM_CREATE) {
-		openflags |= OTRUNC;
+		openflags |= O_CREAT | O_TRUNC;
 	}
 
-	openflags |= OCEXEC;
+	openflags |= O_CLOEXEC;
 
 	/* Allocate space for the underlying file stream object. */
 	if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) {
@@ -294,19 +302,14 @@
 	}
 	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) {
+	if ((obj->fd = open(filename, openflags/*, JAS_STREAM_PERMS*/)) < 0) {
 		// Free the underlying file object, since it will not otherwise
 		// be freed.
 		jas_free(obj);
@@ -313,10 +316,34 @@
 		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_LOGDEBUGF(100, "jas_stream_freopen(\"%s\", \"%s\", %p)\n", path, mode, fp);
+
+	JAS_UNUSED(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);
 
@@ -323,12 +350,129 @@
 	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;
+	}
+	JAS_UNUSED(size);
+	return GetTempFileNameA(temp_directory, "jasper", 0, buffer) > 0
+		? 0 : -1;
+#else
+	static const char base[] = "jasper.XXXXXX";
+	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)
+{
+	JAS_UNUSED(buffer);
+	JAS_UNUSED(size);
+	return -1;
+}
+
+jas_stream_t *jas_stream_tmpfile()
+{
+	jas_stream_t *stream;
+	jas_stream_fileobj_t *obj;
+
+	JAS_LOGDEBUGF(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 && unlink(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));
+	JAS_LOGDEBUGF(100, "jas_stream_fdopen(%d, \"%s\")\n", fd, mode);
 
 	/* Allocate a stream object. */
 	if (!(stream = jas_stream_create())) {
@@ -338,7 +482,7 @@
 	/* Parse the mode string. */
 	stream->openmode_ = jas_strtoopenmode(mode);
 
-#if defined(WIN32)
+#if defined(_WIN32) || defined(JAS_HAVE_IO_H)
 	/* 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
@@ -362,6 +506,7 @@
 	}
 	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
@@ -379,13 +524,13 @@
 
 static void jas_stream_destroy(jas_stream_t *stream)
 {
-	JAS_DBGLOG(100, ("jas_stream_destroy(%p)\n", stream));
+	JAS_LOGDEBUGF(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_LOGDEBUGF(100, "jas_stream_destroy freeing buffer %p\n",
+		  stream->bufbase_);
 		jas_free(stream->bufbase_);
 		stream->bufbase_ = 0;
 	}
@@ -394,7 +539,7 @@
 
 int jas_stream_close(jas_stream_t *stream)
 {
-	JAS_DBGLOG(100, ("jas_stream_close(%p)\n", stream));
+	JAS_LOGDEBUGF(100, "jas_stream_close(%p)\n", stream);
 
 	/* Flush buffer if necessary. */
 	jas_stream_flush(stream);
@@ -451,16 +596,16 @@
 	return 0;
 }
 
-/* FIXME integral type */
-unsigned jas_stream_read(jas_stream_t *stream, void *buf, unsigned cnt)
+size_t jas_stream_read(jas_stream_t *stream, void *buf, size_t cnt)
 {
 	int c;
 	char *bufptr;
 
-	JAS_DBGLOG(100, ("jas_stream_read(%p, %p, %u)\n", stream, buf, cnt));
+	JAS_LOGDEBUGF(100, "jas_stream_read(%p, %p, %zu)\n", stream, buf, cnt);
 
-	if (cnt == 0)
+	if (cnt == 0) {
 		return 0;
+	}
 
 	bufptr = buf;
 
@@ -468,11 +613,13 @@
 	    jas_stream_is_input_buffer_empty(stream)) {
 		/* fast path for unbuffered streams */
 
-		if ((stream->flags_ & JAS_STREAM_ERRMASK) != 0)
+		if ((stream->flags_ & JAS_STREAM_ERRMASK) != 0) {
 			return 0;
+		}
 
-		if ((stream->openmode_ & JAS_STREAM_READ) == 0)
+		if ((stream->openmode_ & JAS_STREAM_READ) == 0) {
 			return 0;
+		}
 
 		assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0);
 
@@ -502,29 +649,32 @@
 	return n;
 }
 
+/* TODO: The return type should probably be changed to size_t. */
 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);
+	const size_t 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)
+	for (size_t 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)
+size_t jas_stream_write(jas_stream_t *stream, const void *buf, size_t cnt)
 {
 	const char *bufptr;
 
-	JAS_DBGLOG(100, ("jas_stream_write(%p, %p, %d)\n", stream, buf, cnt));
+	JAS_LOGDEBUGF(100, "jas_stream_write(%p, %p, %zu)\n", stream, buf, cnt);
 
-	if (cnt == 0)
+	if (cnt == 0) {
 		return 0;
+	}
 
 	bufptr = buf;
 
@@ -533,8 +683,9 @@
 
 		/* need to flush the output buffer before we do a raw
 		   write */
-		if (jas_stream_flushbuf(stream, EOF))
+		if (jas_stream_flushbuf(stream, EOF)) {
 			return 0;
+		}
 
 		stream->bufmode_ |= JAS_STREAM_WRBUF;
 
@@ -570,7 +721,7 @@
 	int ret;
 
 	va_start(ap, fmt);
-	ret = vsnprint(buf, sizeof buf, fmt, ap);
+	ret = vsnprintf(buf, sizeof buf, fmt, ap);
 	jas_stream_puts(stream, buf);
 	va_end(ap);
 	return ret;
@@ -595,7 +746,7 @@
 	char *bufptr;
 	assert(bufsize > 0);
 
-	JAS_DBGLOG(100, ("jas_stream_gets(%p, %p, %d)\n", stream, buf, bufsize));
+	JAS_LOGDEBUGF(100, "jas_stream_gets(%p, %p, %d)\n", stream, buf, bufsize);
 
 	bufptr = buf;
 	while (bufsize > 1) {
@@ -612,17 +763,10 @@
 	return buf;
 }
 
-/* FIXME integral type */
-int jas_stream_gobble(jas_stream_t *stream, int n)
+ssize_t jas_stream_gobble(jas_stream_t *stream, size_t n)
 {
-	int m;
-
-	JAS_DBGLOG(100, ("jas_stream_gobble(%p, %d)\n", stream, n));
-
-	if (n < 0) {
-		jas_eprintf("negative count for jas_stream_gobble\n");
-		return 0;
-	}
+	size_t m;
+	JAS_LOGDEBUGF(100, "jas_stream_gobble(%p, %zu)\n", stream, n);
 	for (m = n; m > 0; --m) {
 		if (jas_stream_getc(stream) == EOF) {
 			return n - m;
@@ -631,20 +775,14 @@
 	return n;
 }
 
-/* FIXME integral type */
-int jas_stream_pad(jas_stream_t *stream, int n, int c)
+ssize_t jas_stream_pad(jas_stream_t *stream, size_t n, int c)
 {
-	int m;
-
-	JAS_DBGLOG(100, ("jas_stream_pad(%p, %d, %d)\n", stream, n, c));
-
-	if (n < 0) {
-		jas_eprintf("negative count for jas_stream_pad\n");
-		return 0;
-	}
+	size_t m;
+	JAS_LOGDEBUGF(100, "jas_stream_pad(%p, %zu, %d)\n", stream, n, c);
 	for (m = n; m > 0; --m) {
-		if (jas_stream_putc(stream, c) == EOF)
+		if (jas_stream_putc(stream, c) == EOF) {
 			return n - m;
+		}
 	}
 	return n;
 }
@@ -658,7 +796,7 @@
 	if (stream->ops_ == &jas_stream_memops) {
 		return 1;
 	} else if (stream->ops_ == &jas_stream_fileops) {
-		if ((*stream->ops_->seek_)(stream->obj_, 0, 1) < 0) {
+		if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) {
 			return 0;
 		}
 		return 1;
@@ -669,8 +807,8 @@
 
 int jas_stream_rewind(jas_stream_t *stream)
 {
-	JAS_DBGLOG(100, ("jas_stream_rewind(%p)\n", stream));
-	return jas_stream_seek(stream, 0, 0);
+	JAS_LOGDEBUGF(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)
@@ -677,8 +815,7 @@
 {
 	long newpos;
 
-	JAS_DBGLOG(100, ("jas_stream_seek(%p, %ld, %d)\n", stream, offset,
-	  origin));
+	JAS_LOGDEBUGF(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_ &
@@ -688,7 +825,7 @@
 	stream->flags_ &= ~JAS_STREAM_EOF;
 
 	if (stream->bufmode_ & JAS_STREAM_RDBUF) {
-		if (origin == 1) {
+		if (origin == SEEK_CUR) {
 			offset -= stream->cnt_;
 		}
 	} else if (stream->bufmode_ & JAS_STREAM_WRBUF) {
@@ -713,7 +850,7 @@
 	int adjust;
 	int offset;
 
-	JAS_DBGLOG(100, ("jas_stream_tell(%p)\n", stream));
+	JAS_LOGDEBUGF(100, "jas_stream_tell(%p)\n", stream);
 
 	if (stream->bufmode_ & JAS_STREAM_RDBUF) {
 		adjust = -stream->cnt_;
@@ -723,7 +860,7 @@
 		adjust = 0;
 	}
 
-	if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, 1)) < 0) {
+	if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR)) < 0) {
 		return -1;
 	}
 
@@ -910,10 +1047,9 @@
 	return openmode;
 }
 
-/* FIXME integral type */
-int jas_stream_copy(jas_stream_t *out, jas_stream_t *in, int n)
+int jas_stream_copy(jas_stream_t *out, jas_stream_t *in, ssize_t n)
 {
-	int m;
+	ssize_t m;
 
 	const bool all = n < 0;
 
@@ -921,14 +1057,14 @@
 
 	m = n;
 	while (all || m > 0) {
-		unsigned nbytes = jas_stream_read(in, buffer,
-						  JAS_MIN((size_t)m, sizeof(buffer)));
-		if (nbytes == 0)
+		size_t 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)
+		}
+		if (jas_stream_write(out, buffer, nbytes) != nbytes) {
 			return -1;
-
+		}
 		m -= nbytes;
 	}
 
@@ -945,7 +1081,7 @@
 	return old;
 }
 
-JAS_DLLEXPORT
+JAS_EXPORT
 long jas_stream_setrwlimit(jas_stream_t *stream, long rwlimit)
 {
 	long old;
@@ -955,6 +1091,57 @@
 	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) {
+				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;
@@ -962,13 +1149,13 @@
 	if ((oldpos = jas_stream_tell(stream)) < 0) {
 		return -1;
 	}
-	if (jas_stream_seek(stream, 0, 2) < 0) {
+	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, 0) < 0) {
+	if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) {
 		return -1;
 	}
 	return pos;
@@ -978,13 +1165,12 @@
 * Memory stream object.
 \******************************************************************************/
 
-/* FIXME integral type */
-static int mem_read(jas_stream_obj_t *obj, char *buf, unsigned cnt)
+static ssize_t mem_read(jas_stream_obj_t *obj, char *buf, size_t cnt)
 {
 	jas_stream_memobj_t *m;
 	assert(buf);
 
-	JAS_DBGLOG(100, ("mem_read(%p, %p, %u)\n", obj, buf, cnt));
+	JAS_LOGDEBUGF(100, "mem_read(%p, %p, %zu)\n", obj, buf, cnt);
 	m = (jas_stream_memobj_t *)obj;
 	size_t n = m->len_ - m->pos_;
 	cnt = JAS_MIN(n, cnt);
@@ -997,11 +1183,9 @@
 {
 	unsigned char *buf;
 
-	//assert(m->buf_);
-
-	JAS_DBGLOG(100, ("mem_resize(%p, %zu)\n", m, bufsize));
+	JAS_LOGDEBUGF(100, "mem_resize(%p, %zu)\n", m, bufsize);
 	if (!bufsize) {
-		jas_eprintf(
+		jas_logerrorf(
 		  "mem_resize was not really designed to handle a buffer of size 0\n"
 		  "This may not work.\n"
 		);
@@ -1009,17 +1193,17 @@
 
 	if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) &&
 	  bufsize) {
-		JAS_DBGLOG(100, ("mem_resize realloc failed\n"));
+		JAS_LOGDEBUGF(100, "mem_resize realloc failed\n");
 		return -1;
 	}
-	JAS_DBGLOG(100, ("mem_resize realloc succeeded\n"));
+	JAS_LOGDEBUGF(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)
+static ssize_t mem_write(jas_stream_obj_t *obj, const char *buf,
+  size_t cnt)
 {
 	size_t n;
 	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
@@ -1028,19 +1212,19 @@
 
 	assert(buf);
 
-	JAS_DBGLOG(100, ("mem_write(%p, %p, %u)\n", obj, buf, cnt));
+	JAS_LOGDEBUGF(100, "mem_write(%p, %p, %zu)\n", obj, buf, cnt);
 	newpos = m->pos_ + cnt;
 	if (newpos > m->bufsize_ && m->growable_) {
 		newbufsize = m->bufsize_;
 		while (newbufsize < newpos) {
-			//newbufsize <<= 1;
+			/* Attempt to double the buffer size. */
 			if (!jas_safe_size_mul(newbufsize, 2, &newbufsize)) {
-				JAS_DBGLOG(100, ("new buffer size would cause overflow\n"));
+				JAS_LOGDEBUGF(100, "new buffer size would cause overflow\n");
 				return -1;
 			}
 		}
-		JAS_DBGLOG(100, ("mem_write resizing from %d to %zu\n", m->bufsize_,
-		  newbufsize));
+		JAS_LOGDEBUGF(100, "mem_write resizing from %d to %zu\n", m->bufsize_,
+		  newbufsize);
 		assert(newbufsize > 0);
 		if (mem_resize(m, newbufsize)) {
 			return -1;
@@ -1078,15 +1262,15 @@
 	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
 	long newpos;
 
-	JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin));
+	JAS_LOGDEBUGF(100, "mem_seek(%p, %ld, %d)\n", obj, offset, origin);
 	switch (origin) {
-	case 0:
+	case SEEK_SET:
 		newpos = offset;
 		break;
-	case 2:
+	case SEEK_END:
 		newpos = m->len_ - offset;
 		break;
-	case 1:
+	case SEEK_CUR:
 		newpos = m->pos_ + offset;
 		break;
 	default:
@@ -1104,11 +1288,11 @@
 {
 	jas_stream_memobj_t *m;
 
-	JAS_DBGLOG(100, ("mem_close(%p)\n", obj));
+	JAS_LOGDEBUGF(100, "mem_close(%p)\n", obj);
 	m = (jas_stream_memobj_t *)obj;
-	JAS_DBGLOG(100, ("mem_close myalloc=%d\n", m->myalloc_));
+	JAS_LOGDEBUGF(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_LOGDEBUGF(100, "mem_close freeing buffer %p\n", m->buf_);
 		jas_free(m->buf_);
 		m->buf_ = 0;
 	}
@@ -1120,20 +1304,19 @@
 * File stream object.
 \******************************************************************************/
 
-/* FIXME integral type */
-static int file_read(jas_stream_obj_t *obj, char *buf, unsigned cnt)
+static ssize_t file_read(jas_stream_obj_t *obj, char *buf, size_t cnt)
 {
 	jas_stream_fileobj_t *fileobj;
-	JAS_DBGLOG(100, ("file_read(%p, %p, %u)\n", obj, buf, cnt));
+	JAS_LOGDEBUGF(100, "file_read(%p, %p, %zu)\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)
+static ssize_t file_write(jas_stream_obj_t *obj, const char *buf,
+  size_t cnt)
 {
 	jas_stream_fileobj_t *fileobj;
-	JAS_DBGLOG(100, ("file_write(%p, %p, %u)\n", obj, buf, cnt));
+	JAS_LOGDEBUGF(100, "file_write(%p, %p, %zu)\n", obj, buf, cnt);
 	fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
 	return write(fileobj->fd, buf, cnt);
 }
@@ -1142,18 +1325,91 @@
 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));
+	JAS_LOGDEBUGF(100, "file_seek(%p, %ld, %d)\n", obj, offset, origin);
 	fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
-	return seek(fileobj->fd, offset, origin);
+	return lseek(fileobj->fd, offset, origin);
 }
 
 static int file_close(jas_stream_obj_t *obj)
 {
-	int ret;
+	int ret = 0;
 	jas_stream_fileobj_t *fileobj;
-	JAS_DBGLOG(100, ("file_close(%p)\n", obj));
+	JAS_LOGDEBUGF(100, "file_close(%p)\n", obj);
 	fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
-	ret = close(fileobj->fd);
+	if (!(fileobj->flags & JAS_STREAM_FILEOBJ_NOCLOSE)) {
+		ret = close(fileobj->fd);
+		if (fileobj->flags & JAS_STREAM_FILEOBJ_DELONCLOSE) {
+			unlink(fileobj->pathname);
+		}
+	}
 	jas_free(fileobj);
 	return ret;
+}
+
+/******************************************************************************\
+* Stdio file stream object.
+\******************************************************************************/
+
+static ssize_t sfile_read(jas_stream_obj_t *obj, char *buf, size_t cnt)
+{
+	FILE *fp;
+	size_t n;
+	int result;
+	JAS_LOGDEBUGF(100, "sfile_read(%p, %p, %zu)\n", obj, buf, cnt);
+	fp = JAS_CAST(FILE *, obj);
+#if 0
+	n = fread(buf, 1, cnt, fp);
+	if (n != cnt) {
+		result = (!ferror(fp) && feof(fp)) ? n : -1;
+	} else {
+		result = n;
+	}
+#else
+	if (ferror(fp)) {
+		result = -1;
+	} else {
+		n = fread(buf, 1, cnt, fp);
+		return n;
+	}
+#endif
+	return result;
+}
+
+static ssize_t sfile_write(jas_stream_obj_t *obj, const char *buf,
+  size_t cnt)
+{
+	FILE *fp;
+	size_t n;
+	JAS_LOGDEBUGF(100, "sfile_write(%p, %p, %zu)\n", obj, buf, cnt);
+	fp = JAS_CAST(FILE *, obj);
+	ssize_t result;
+#if 0
+	n = fwrite(buf, 1, cnt, fp);
+	return (n != cnt) ? (-1) : cnt;
+#else
+	if (ferror(fp)) {
+		result = -1;
+	} else {
+		n = fwrite(buf, 1, cnt, fp);
+		result = n;
+	}
+	return result;
+#endif
+}
+
+/* FIXME integral type */
+static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin)
+{
+	FILE *fp;
+	JAS_LOGDEBUGF(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_LOGDEBUGF(100, "sfile_close(%p)\n", obj);
+	fp = JAS_CAST(FILE *, obj);
+	return fclose(fp);
 }
--- /dev/null
+++ b/jas_string.c
@@ -1,0 +1,216 @@
+/*
+ * 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
+\******************************************************************************/
+
+#define JAS_FOR_INTERNAL_USE_ONLY
+
+#include "jasper/jas_string.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.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;
+}
+
+char *jas_strtok(char *s, const char *delim, char **save_ptr)
+{
+#if 1
+	char *result;
+	char *end;
+	if (!s) {
+		s = *save_ptr;
+	}
+	if (*s != '\0') {
+		s += strspn(s, delim);
+		if (*s != '\0') {
+			end = s + strcspn(s, delim);
+			if (*end == '\0') {
+				*save_ptr = end;
+			} else {
+				*end = '\0';
+				*save_ptr = end + 1;
+			}
+			result = s;
+		} else {
+			*save_ptr = s;
+			result = 0;
+		}
+	} else {
+		*save_ptr = s;
+		result = 0;
+	}
+	return result;
+#else
+	return strtok_r(str, delim, save_ptr);
+#endif
+}
+
+JAS_EXPORT
+int jas_stringtokenize(const char *string, const char *delim,
+  char ***tokens_buf, size_t *max_tokens_buf, size_t *num_tokens_buf)
+{
+	char **tokens = 0;
+	size_t max_tokens = 0;
+	size_t num_tokens = 0;
+	char **new_tokens;
+	size_t new_max_tokens;
+	char *buffer;
+	int ret = 0;
+	char *token = 0;
+
+	if (!(buffer = jas_strdup(string))) {
+		ret = -1;
+		goto done;
+	}
+	//new_max_tokens = 1;
+	new_max_tokens = 0;
+	if (new_max_tokens > 0) {
+		if (!(tokens = jas_malloc(new_max_tokens * sizeof(char *)))) {
+			ret = -1;
+			goto done;
+		}
+		max_tokens = new_max_tokens;
+	}
+
+	bool first = true;
+	char *saveptr = 0;
+	for (;;) {
+		char *cp;
+		if (!(cp = jas_strtok(first ? buffer : 0, delim, &saveptr))) {
+			break;
+		}
+		first = false;
+		if (!(token = jas_strdup(cp))) {
+			ret = -1;
+			goto done;
+		}
+		if (num_tokens == max_tokens) {
+			new_max_tokens = max_tokens ? 2 * max_tokens : 1;
+			if (!(new_tokens = jas_realloc(tokens, new_max_tokens *
+			  sizeof(char *)))) {
+				ret = -1;
+				goto done;
+			}
+			tokens = new_tokens;
+			max_tokens = new_max_tokens;
+		}
+		assert(num_tokens < max_tokens);
+		tokens[num_tokens] = token;
+		token = 0;
+		++num_tokens;
+	}
+
+done:
+	if (buffer) {
+		jas_free(buffer);
+	}
+	if (ret && tokens) {
+		for (int i = 0; i < num_tokens; ++i) {
+			jas_free(tokens[i]);
+		}
+		jas_free(tokens);
+		tokens = 0;
+		max_tokens = 0;
+		num_tokens = 0;
+	}
+	if (token) {
+		jas_free(token);
+	}
+	if (!ret) {
+		*tokens_buf = tokens;
+		*max_tokens_buf = max_tokens;
+		*num_tokens_buf = num_tokens;
+	}
+	if (jas_get_debug_level() >= 100) {
+		jas_eprintf("tokens %p; max_tokens %zu; num_tokens %zu\n",
+		  JAS_CAST(void *, tokens), max_tokens, num_tokens);
+		for (int i = 0; i < num_tokens; ++i) {
+			jas_eprintf("[%d] = %s\n", i, tokens[i]);
+		}
+	}
+	return ret;
+}
--- /dev/null
+++ b/jas_tvp.c
@@ -1,0 +1,234 @@
+/*
+ * 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-Value Parser Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#define JAS_FOR_INTERNAL_USE_ONLY
+
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_string.h"
+
+/******************************************************************************\
+* Macros.
+\******************************************************************************/
+
+/* Is the specified character valid for a tag name? */
+#define	JAS_TVP_ISTAG(x) \
+	(isalpha(x) || (x) == '_' || isdigit(x))
+
+/******************************************************************************\
+* Code for creating and destroying a tag-value parser.
+\******************************************************************************/
+
+jas_tvparser_t *jas_tvparser_create(const char *s)
+{
+	jas_tvparser_t *tvp;
+	if (!(tvp = jas_malloc(sizeof(jas_tvparser_t)))) {
+		return 0;
+	}
+	if (!(tvp->buf = jas_strdup(s))) {
+		jas_tvparser_destroy(tvp);
+		return 0;
+	}
+	tvp->pos = tvp->buf;
+	tvp->tag = 0;
+	tvp->val = 0;
+	return tvp;
+}
+
+void jas_tvparser_destroy(jas_tvparser_t *tvp)
+{
+	if (tvp->buf) {
+		jas_free(tvp->buf);
+	}
+	jas_free(tvp);
+}
+
+/******************************************************************************\
+* Main parsing code.
+\******************************************************************************/
+
+/* Get the next tag-value pair. */
+int jas_tvparser_next(jas_tvparser_t *tvp)
+{
+	char *p;
+	char *tag;
+	char *val;
+
+	/* Skip any leading whitespace. */
+	p = tvp->pos;
+	while (*p != '\0' && isspace(JAS_CAST(unsigned char, *p))) {
+		++p;
+	}
+
+	/* Has the end of the input data been reached? */
+	if (*p == '\0') {
+		/* No more tags are present. */
+		tvp->pos = p;
+		return 1;
+	}
+
+	/* Does the tag name begin with a valid character? */
+	if (!JAS_TVP_ISTAG(JAS_CAST(unsigned char, *p))) {
+		return -1;
+	}
+
+	/* Remember where the tag name begins. */
+	tag = p;
+
+	/* Find the end of the tag name. */
+	while (*p != '\0' && JAS_TVP_ISTAG(JAS_CAST(unsigned char, *p))) {
+		++p;
+	}
+
+	/* Has the end of the input data been reached? */
+	if (*p == '\0') {
+		/* The value field is empty. */
+		tvp->tag = tag;
+		tvp->val = "";
+		tvp->pos = p;
+		return 0;
+	}
+
+	/* Is a value field not present? */
+	if (*p != '=') {
+		if (*p != '\0' && !isspace(JAS_CAST(unsigned char, *p))) {
+			return -1;
+		}
+		*p++ = '\0';
+		tvp->tag = tag;
+		tvp->val = "";
+		tvp->pos = p;
+		return 0;
+	}
+
+	*p++ = '\0';
+
+	val = p;
+	while (*p != '\0' && !isspace(JAS_CAST(unsigned char, *p))) {
+		++p;
+	}
+
+	if (*p != '\0') {
+		*p++ = '\0';
+	}
+
+	tvp->pos = p;
+	tvp->tag = tag;
+	tvp->val = val;
+
+	return 0;
+}
+
+/******************************************************************************\
+* Code for querying the current tag/value.
+\******************************************************************************/
+
+/* Get the current tag. */
+const char *jas_tvparser_gettag(const jas_tvparser_t *tvp)
+{
+	return tvp->tag;
+}
+
+/* Get the current value. */
+const char *jas_tvparser_getval(const jas_tvparser_t *tvp)
+{
+	return tvp->val;
+}
+
+/******************************************************************************\
+* Miscellaneous code.
+\******************************************************************************/
+
+/* Lookup a tag by name. */
+const jas_taginfo_t *jas_taginfos_lookup(const jas_taginfo_t *taginfos, const char *name)
+{
+	const jas_taginfo_t *taginfo;
+	taginfo = taginfos;
+	while (taginfo->id >= 0) {
+		if (!strcmp(taginfo->name, name)) {
+			return taginfo;
+		}
+		++taginfo;
+	}
+	return 0;
+}
+
+/* This function is simply for convenience. */
+/* One can avoid testing for the special case of a null pointer, by
+  using this function.   This function never returns a null pointer.  */
+const jas_taginfo_t *jas_taginfo_nonull(const jas_taginfo_t *taginfo)
+{
+	static const jas_taginfo_t invalidtaginfo = {
+		-1, 0
+	};
+	
+	return taginfo ? taginfo : &invalidtaginfo;
+}
--- /dev/null
+++ b/jas_version.c
@@ -1,0 +1,69 @@
+/*
+ * 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__
+ */
+
+#define JAS_FOR_INTERNAL_USE_ONLY
+
+#include "jasper/jas_version.h"
+
+const char *jas_getversion()
+{
+	return JAS_VERSION;
+}
--- a/jasper/jas_cm.h
+++ b/jasper/jas_cm.h
@@ -67,9 +67,14 @@
 #ifndef JAS_CM_H
 #define JAS_CM_H
 
+/******************************************************************************\
+*
+\******************************************************************************/
+
 /* The configuration header file should be included first. */
 #include <jasper/jas_config.h>
 
+#include <jasper/jas_types.h>
 #include <jasper/jas_icc.h>
 
 #ifdef __cplusplus
@@ -76,9 +81,25 @@
 extern "C" {
 #endif
 
+/*!
+ * @addtogroup module_cm
+ * @{
+ */
+
+/******************************************************************************\
+* Types and Macros.
+\******************************************************************************/
+
+/*!
+@brief
+Color space.
+*/
 typedef unsigned jas_clrspc_t;
 
-/* transform operations */
+/*!
+@brief
+Transform operations
+*/
 typedef enum {
 	JAS_CMXFORM_OP_FWD = 0,
 	JAS_CMXFORM_OP_REV = 1,
@@ -86,7 +107,10 @@
 	JAS_CMXFORM_OP_GAMUT = 3,
 } jas_cmxform_op_t;
 
-/* rendering intents */
+/*!
+@brief
+Rendering intents.
+*/
 typedef enum {
 	JAS_CMXFORM_INTENT_PER = 0,
 	JAS_CMXFORM_INTENT_RELCLR = 1,
@@ -94,8 +118,16 @@
 	JAS_CMXFORM_INTENT_SAT = 3,
 } jas_cmxform_intent_t;
 
+/*!
+@brief
+Number of rendering intents.
+*/
 #define	JAS_CMXFORM_NUMINTENTS		4
 
+/*!
+@brief
+Transform optimization.
+*/
 typedef enum {
 	JAS_CMXFORM_OPTM_SPEED = 0,
 	JAS_CMXFORM_OPTM_SIZE = 1,
@@ -102,16 +134,42 @@
 	JAS_CMXFORM_OPTM_ACC = 2,
 } jas_cmxform_optm_t;
 
-
+/*!
+@brief
+Create a color space.
+*/
 #define	jas_clrspc_create(fam, mbr)	(((fam) << 8) | (mbr))
+
+/*!
+@brief
+Get the family of a color space.
+*/
+
 #define	jas_clrspc_fam(clrspc)	((clrspc) >> 8)
+
+/*!
+@brief
+Get the (family) member of a color space.
+*/
 #define	jas_clrspc_mbr(clrspc)	((clrspc) & 0xff)
+
+/*!
+@brief
+Test if a color space is generic.
+*/
 #define	jas_clrspc_isgeneric(clrspc)	(!jas_clrspc_mbr(clrspc))
+
+/*!
+@brief
+Test if a color space is unknown.
+*/
 #define	jas_clrspc_isunknown(clrspc)	((clrspc) & JAS_CLRSPC_UNKNOWNMASK)
 
 #define	JAS_CLRSPC_UNKNOWNMASK	0x4000
 
-/* color space families */
+/*!
+@brief Color space families.
+*/
 #define	JAS_CLRSPC_FAM_UNKNOWN	0
 #define	JAS_CLRSPC_FAM_XYZ	1
 #define	JAS_CLRSPC_FAM_LAB	2
@@ -119,7 +177,9 @@
 #define	JAS_CLRSPC_FAM_RGB	4
 #define	JAS_CLRSPC_FAM_YCBCR	5
 
-/* specific color spaces */
+/*!
+@brief 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)
@@ -127,7 +187,9 @@
 #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 */
+/*!
+@brief 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)
@@ -142,10 +204,17 @@
 
 #define	JAS_CLRSPC_CHANIND_GRAY_Y	0
 
+/*!
+Real-number type.
+*/
 typedef double jas_cmreal_t;
 
 struct jas_cmpxform_s;
 
+/*!
+@brief
+Component format.
+*/
 typedef struct {
 	long *buf;
 	unsigned prec;
@@ -154,21 +223,38 @@
 	unsigned height;
 } jas_cmcmptfmt_t;
 
+/*!
+@brief
+Pixmap (i.e., multicomponent) format.
+*/
 typedef struct {
 	unsigned numcmpts;
 	jas_cmcmptfmt_t *cmptfmts;
 } jas_cmpixmap_t;
 
+/*!
+@brief
+Transform operations.
+*/
 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;
 
+/*!
+@brief
+Shaper matrix look-up table (LUT).
+*/
 typedef struct {
 	jas_cmreal_t *data;
 	unsigned size;
 } jas_cmshapmatlut_t;
 
+/*!
+@brief
+Shaper matrix.
+*/
 typedef struct {
 	int mono;
 	int order;
@@ -178,17 +264,27 @@
 	jas_cmreal_t mat[3][4];
 } jas_cmshapmat_t;
 
+/*!
+@brief
+Shaper look-up table (LUT).
+*/
 typedef struct {
 	int order;
 } jas_cmshaplut_t;
 
+/*!
+@brief
+Color space conversion.
+*/
 typedef struct {
 	unsigned inclrspc;
 	unsigned outclrspc;
 } jas_cmclrspcconv_t;
 
-#define	jas_align_t	double
-
+/*!
+@brief
+Transform class.
+*/
 typedef struct jas_cmpxform_s {
 	unsigned refcnt;
 	const jas_cmpxformops_t *ops;
@@ -195,7 +291,7 @@
 	unsigned numinchans;
 	unsigned numoutchans;
 	union {
-		jas_align_t dummy;
+		max_align_t dummy;
 		jas_cmshapmat_t shapmat;
 		jas_cmshaplut_t shaplut;
 		jas_cmclrspcconv_t clrspcconv;
@@ -202,6 +298,10 @@
 	} data;
 } jas_cmpxform_t;
 
+/*!
+@brief
+Primitive transform sequence class.
+*/
 typedef struct {
 	unsigned numpxforms;
 	unsigned maxpxforms;
@@ -208,6 +308,10 @@
 	jas_cmpxform_t **pxforms;
 } jas_cmpxformseq_t;
 
+/*!
+@brief
+Primitive transform class.
+*/
 typedef struct {
 	unsigned numinchans;
 	unsigned numoutchans;
@@ -219,6 +323,9 @@
 
 #define	JAS_CMPROF_NUMPXFORMSEQS	13
 
+/*!
+Color-management (CM) profile.
+*/
 typedef struct {
 	jas_clrspc_t clrspc;
 	unsigned numchans;
@@ -228,6 +335,10 @@
 	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;
@@ -242,27 +353,144 @@
 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);
+/******************************************************************************\
+* Color-management (CM) profile class.
+\******************************************************************************/
 
-JAS_DLLEXPORT void jas_cmxform_destroy(jas_cmxform_t *xform);
+/*!
+@brief
+Create a color-management profile from an ICC profile.
 
-/* Apply a transform to data. */
-JAS_DLLEXPORT int jas_cmxform_apply(const jas_cmxform_t *xform, const jas_cmpixmap_t *in,
+@details
+This function creates a CM profile from an ICC profile.
+
+@returns
+If successful, a pointer to the created CM profile is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_EXPORT
+jas_cmprof_t *jas_cmprof_createfromiccprof(const jas_iccprof_t *iccprof);
+
+/*!
+@brief
+Create a color-management profile from a color space.
+
+@details
+The function creates a CM profile from a color space.
+
+@returns
+If successful, a pointer to the created CM profile is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_EXPORT
+jas_cmprof_t *jas_cmprof_createfromclrspc(jas_clrspc_t clrspc);
+
+/*!
+@brief Destroy a color-management profile.
+
+@details
+*/
+JAS_EXPORT
+void jas_cmprof_destroy(jas_cmprof_t *prof);
+
+/*!
+@brief
+Copy a color-management profile.
+
+@details
+This function creates a clone (i.e., copy) of a CM profile.
+
+@returns
+If successful, a pointer to the newly created CM profile is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_EXPORT
+jas_cmprof_t *jas_cmprof_copy(const jas_cmprof_t *prof);
+
+/*!
+@brief
+Create a ICC profile from a CM profile.
+
+@details
+This function creates an ICC profile from a CM profile.
+
+@returns
+If successful, a pointer to the created ICC profile is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_EXPORT
+jas_iccprof_t *jas_iccprof_createfromcmprof(const jas_cmprof_t *prof);
+
+/******************************************************************************\
+* Color-Management (CM) Transform.
+\******************************************************************************/
+
+/*!
+@brief
+Create a transform from a CM profile.
+
+@details
+
+@returns
+If successful, a pointer to the created transform is returned.
+Otherwise, a null pointer is returned.
+*/
+JAS_EXPORT
+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);
+
+/*!
+@brief
+Destroy a transform.
+
+@details
+*/
+JAS_EXPORT
+void jas_cmxform_destroy(jas_cmxform_t *xform);
+
+/*!
+@brief
+Apply a transform to data.
+
+@details
+
+@returns
+If successful, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+JAS_EXPORT
+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);
+/******************************************************************************\
+* Miscellany.
+\******************************************************************************/
 
-/* Destroy a profile. */
-JAS_DLLEXPORT void jas_cmprof_destroy(jas_cmprof_t *prof);
+/*!
+@brief
+Get the number of channels associated with a particular color space.
 
+@details
+
+@returns
+*/
 unsigned jas_clrspc_numchans(jas_clrspc_t clrspc);
-JAS_DLLEXPORT jas_iccprof_t *jas_iccprof_createfromcmprof(const jas_cmprof_t *prof);
 
+/*!
+@brief
+Get the color space associated with a color-management profile.
+
+@details
+
+@returns
+*/
 #define	jas_cmprof_clrspc(prof) ((prof)->clrspc)
-JAS_DLLEXPORT jas_cmprof_t *jas_cmprof_copy(const jas_cmprof_t *prof);
+
+/*!
+ * @}
+ */
 
 #ifdef __cplusplus
 }
--- a/jasper/jas_compiler.h
+++ b/jasper/jas_compiler.h
@@ -66,38 +66,82 @@
 #include <jasper/jas_config.h>
 
 #ifdef _MSC_VER
-#ifndef __cplusplus
-#undef inline
-#define inline __inline
+#	ifndef __cplusplus
+#		undef inline
+#		define inline __inline
+#	endif
 #endif
+
+#if defined(__GNUC__)
+#	define JAS_DEPRECATED __attribute__((deprecated))
+#else
+#	define JAS_DEPRECATED
 #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)
+#if defined(__GNUC__)
+#	define JAS_ATTRIBUTE_CONST __attribute__((const))
 #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)
+#	define JAS_ATTRIBUTE_CONST
 #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))
+#if defined(__GNUC__)
+#	define JAS_ATTRIBUTE_PURE __attribute__((pure))
 #else
-#define JAS_ATTRIBUTE_DISABLE_USAN
+#	define JAS_ATTRIBUTE_PURE
 #endif
+
+#if defined(__GNUC__)
+#	define JAS_FORCE_INLINE inline __attribute__((always_inline))
+#else
+#	define JAS_FORCE_INLINE inline
+#endif
+
+#if defined(__GNUC__)
+#	if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
+#		define JAS_UNREACHABLE() __builtin_unreachable()
+#	else
+#		define JAS_UNREACHABLE()
+#	endif
+#elif defined(__clang__)
+#		define JAS_UNREACHABLE() __builtin_unreachable()
+#elif defined(_MSC_VER)
+#	define JAS_UNREACHABLE() __assume(0)
+#else
+#	define JAS_UNREACHABLE()
+#endif
+
+#if defined(__GNUC__)
+#	define JAS_LIKELY(x) __builtin_expect (!!(x), 1)
+#else
+#	define JAS_LIKELY(x) (x)
+#endif
+
+#if defined(__GNUC__)
+#	define JAS_UNLIKELY(x) __builtin_expect (!!(x), 0)
+#else
+#	define JAS_UNLIKELY(x) (x)
+#endif
+
+#if defined(__GNUC__) && __GNUC__ >= 6
+#	define JAS_ATTRIBUTE_DISABLE_UBSAN \
+	  __attribute__((no_sanitize_undefined))
+#elif defined(__clang__)
+#	define JAS_ATTRIBUTE_DISABLE_UBSAN \
+	  __attribute__((no_sanitize("undefined")))
+#else
+#	define JAS_ATTRIBUTE_DISABLE_UBSAN
+#endif
+
+#ifdef __has_builtin
+#define jas_has_builtin(x) __has_builtin(x)
+#else
+#define jas_has_builtin(x) 0
+#endif
+
+/*!
+@brief
+Indicate that a variable may be unused (in order to avoid a compiler warning).
+*/
+#define JAS_UNUSED(x) USED(x)
 
 #endif
--- a/jasper/jas_config.h
+++ b/jasper/jas_config.h
@@ -4,17 +4,87 @@
 #include <u.h>
 #include <libc.h>
 #include <ctype.h>
+#include <stdio.h>
+
+#define bool  int
+#define false 0
+#define true  1
+
+#define PRIxFAST32 "x"
+#define PRIxFAST16 PRIxFAST32
+#define PRIuFAST32 "ud"
+#define PRIuFAST16 PRIuFAST32
+#define PRIiFAST32 "d"
+#define PRIdPTR "p"
+
+#define PRIuLEAST32 PRIuFAST32
+#define PRIiLEAST32 PRIiFAST32
+#define PRIxLEAST32 PRIxFAST32
+#define PRIxLEAST16 PRIxFAST16
+
+typedef u8int uint_least8_t;
+typedef s8int int_least8_t;
+typedef u16int uint_least16_t;
+typedef s16int int_least16_t;
+typedef u32int uint_least32_t;
+typedef s32int int_least32_t;
+typedef u64int uint_least64_t;
+
+typedef u8int uint_fast8_t;
+typedef u16int uint_fast16_t;
+typedef s16int int_fast16_t;
+typedef u32int uint_fast32_t;
+typedef s32int int_fast32_t;
+typedef u64int uint_fast64_t;
+typedef s64int int_least64_t;
+
+// FIXME
+typedef s64int intmax_t;
+typedef long ssize_t;
+typedef ulong size_t;
+
+#define SIZE_MAX 0xffffffffU
+#define LONG_MAX 0x7fffffffL
+#define INT_FAST32_MAX 0x7fffffff
+#define INT_FAST32_MIN (-INT_FAST32_MAX-1)
+#define UINT_FAST32_MAX 0xffffffffU
+#define INT_LEAST64_MAX 0x7fffffffffffffff
+#define INT_LEAST64_MIN ((s64int)0x8000000000000000ULL)
+#define UINT_LEAST64_MAX 0xffffffffffffffffULL
+
+#define INT_LEAST32_MIN INT_FAST32_MIN
+#define INT_LEAST32_MAX INT_FAST32_MAX
+#define UINT_LEAST32_MAX UINT_FAST32_MAX
+#define INT_MAX INT_FAST32_MAX
+
+#define DBL_MAX 1.7976931348623157E+308
+
+#define O_RDWR ORDWR
+#define O_RDONLY OREAD
+#define O_WRONLY OWRITE
+#define O_BINARY 0
+#define O_TRUNC OTRUNC
+#define O_CLOEXEC OCEXEC
+
+// FIXME
+#define O_APPEND 0
+#define O_CREAT 0
+
 #include <jasper/jas_compiler.h>
 #include <jasper/jas_dll.h>
 
 #define	JAS_VERSION "plan9"
+#define JAS_DEFAULT_MAX_MEM_USAGE (512*1024*1024)
 #define JAS_ENABLE_32BIT 1
-#define JAS_INCLUDE_JP2_CODEC 1
+#define JAS_ENABLE_JPC_CODEC 1
+#define JAS_ENABLE_JP2_CODEC 1
 #define JAS_INCLUDE_JPC_CODEC 1
+#define JAS_INCLUDE_JP2_CODEC 1
 #define JAS_DEC_DEFAULT_MAX_SAMPLES (64 * ((size_t) 1048576))
 #define NDEBUG
-#define NULL nil
+#define JAS_EXPORT
 
-typedef usize size_t;
+#define unlink remove
+#define lseek seek
 
 #endif
--- a/jasper/jas_debug.h
+++ b/jasper/jas_debug.h
@@ -74,6 +74,9 @@
 /* The configuration header file should be included first. */
 #include <jasper/jas_config.h>
 
+#include "jasper/jas_init.h"
+#include "jasper/jas_debug.h"
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -86,25 +89,112 @@
   level is set sufficiently high. */
 #if !defined(NDEBUG)
 #define	JAS_DBGLOG(n, x) \
-	((jas_getdbglevel() >= (n)) ? (jas_eprintf x) : 0)
+	((jas_get_debug_level() >= (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);
+#if !defined(NDEBUG)
+#define	JAS_LOGDEBUGF(n, ...) \
+	((jas_get_debug_level() >= (n)) ? jas_logdebugf((n), __VA_ARGS__) : 0)
+#else
+#define	JAS_LOGDEBUGF(n, ...)
+#endif
 
-/* Set the library debug level. */
-JAS_DLLEXPORT int jas_setdbglevel(int dbglevel);
+/*!
+@brief
+Warn about the use of deprecated functionality.
+*/
+JAS_EXPORT
+void jas_deprecated(const char *fmt, ...);
 
-/* Perform formatted output to standard error. */
-JAS_DLLEXPORT int jas_eprintf(const char *fmt, ...);
+/*!
+@brief
+Get the library debug level.
 
-/* Convert to a string literal */
+@deprecated
+This function is deprecated.
+*/
+JAS_DEPRECATED
+static inline
+int jas_getdbglevel(void)
+{
+	jas_deprecated("jas_getdbglevel is deprecated\n");
+	return jas_get_debug_level();
+}
+
+/*!
+@brief
+Set the library debug level.
+*/
+JAS_EXPORT
+int jas_setdbglevel(int dbglevel);
+
+/*!
+@brief
+Print formatted text for the standard error stream (i.e., stderr).
+*/
+JAS_EXPORT
+int jas_eprintf(const char *fmt, ...);
+
+/*!
+@brief
+Generate a generic log message.
+*/
+JAS_EXPORT
+int jas_logprintf(const char *fmt, ...);
+
+/*!
+@brief
+Generate an error log message.
+*/
+JAS_EXPORT
+int jas_logerrorf(const char *fmt, ...);
+
+/*!
+@brief
+Generate a warning log message.
+*/
+JAS_EXPORT
+int jas_logwarnf(const char *fmt, ...);
+
+/*!
+@brief
+Generate an informational log message.
+*/
+JAS_EXPORT
+int jas_loginfof(const char *fmt, ...);
+
+/*!
+@brief
+Generate a debugging log message.
+*/
+JAS_EXPORT
+int jas_logdebugf(int priority, const char *fmt, ...);
+
+/*!
+@brief
+Dump memory.
+*/
+int jas_logmemdump(const void *data, size_t len);
+
+/*!
+@brief
+Dump memory to a stream.
+*/
+JAS_EXPORT
+int jas_memdump(FILE *out, const void *data, size_t len);
+
+/*!
+@brief
+Convert to a string literal.
+*/
 #define JAS_STRINGIFY(x) #x
 
-/* Convert to a string literal after macro expansion */
+/*!
+@brief
+Convert to a string literal after macro expansion.
+*/
 #define JAS_STRINGIFYX(x) JAS_STRINGIFY(x)
 
 #ifdef __cplusplus
--- a/jasper/jas_dll.h
+++ b/jasper/jas_dll.h
@@ -65,29 +65,9 @@
 /* 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
+/* For backward compatibility only. */
+#define JAS_DLLEXPORT JAS_EXPORT
+/* For backward compatibility only. */
+#define JAS_DLLLOCAL JAS_LOCAL
 
 #endif
--- a/jasper/jas_fix.h
+++ b/jasper/jas_fix.h
@@ -82,19 +82,52 @@
 extern "C" {
 #endif
 
+/*!
+ * @addtogroup module_fixed
+ * @{
+ */
+
 /******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/*!
+Integral type used for fixed-point representations.
+*/
+#if defined(JAS_ENABLE_32BIT)
+typedef int_least32_t jas_fix_t;
+#define PRIjas_fix PRIiLEAST32
+#else
+typedef int_least64_t jas_fix_t;
+#define PRIjas_fix PRIiLEAST64
+#endif
+
+/*
+Integral type used for double-precision fixed-point representations.
+*/
+#if defined(JAS_ENABLE_32BIT)
+typedef int_least64_t jas_fix_big_t;
+#else
+#if defined(JAS_HAVE_INT128_T)
+typedef __int128_t jas_fix_big_t;
+#else
+typedef int_least64_t jas_fix_big_t;
+#endif
+#endif
+
+/******************************************************************************\
 * Constants.
 \******************************************************************************/
 
-/* The representation of the value zero. */
+/*! 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. */
+/*! 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. */
+/*! The representation of the value one half. */
 #define	JAS_FIX_HALF(fix_t, fracbits) \
 	(JAS_CAST(fix_t, 1) << ((fracbits) - 1))
 
@@ -102,19 +135,19 @@
 * Conversion operations.
 \******************************************************************************/
 
-/* Convert an int to a fixed-point number. */
+/*! 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. */
+/*! 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. */
+/*! 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. */
+/*! 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))))
 
@@ -128,7 +161,7 @@
 * Only the generic macros should be invoked directly by application code.
 \******************************************************************************/
 
-/* Calculate the sum of two fixed-point numbers. */
+/*! Calculate the sum of two fixed-point numbers. */
 #if !defined(DEBUG_OVERFLOW)
 #define JAS_FIX_ADD			JAS_FIX_ADD_FAST
 #else
@@ -135,10 +168,10 @@
 #define JAS_FIX_ADD			JAS_FIX_ADD_OFLOW
 #endif
 
-/* Calculate the sum of two fixed-point numbers without overflow checking. */
+/*! 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. */
+/*! 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)) : \
@@ -146,7 +179,7 @@
 	  (((y) >= 0) ? ((x) + (y)) : ((x) + (y) < 0 || JAS_FIX_OFLOW(), \
 	  (x) + (y)))
 
-/* Calculate the product of two fixed-point numbers. */
+/*! Calculate the product of two fixed-point numbers. */
 #if !defined(DEBUG_OVERFLOW)
 #define JAS_FIX_MUL			JAS_FIX_MUL_FAST
 #else
@@ -153,13 +186,13 @@
 #define JAS_FIX_MUL			JAS_FIX_MUL_OFLOW
 #endif
 
-/* Calculate the product of two fixed-point numbers without overflow
+/*! 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
+/*! 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)) == \
@@ -168,7 +201,7 @@
 	  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. */
+/*! Calculate the product of a fixed-point number and an int. */
 #if !defined(DEBUG_OVERFLOW)
 #define	JAS_FIX_MULBYINT	JAS_FIX_MULBYINT_FAST
 #else
@@ -175,17 +208,17 @@
 #define	JAS_FIX_MULBYINT	JAS_FIX_MULBYINT_OFLOW
 #endif
 
-/* Calculate the product of a fixed-point number and an int without overflow
+/*! 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
+/*! 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. */
+/*! Calculate the quotient of two fixed-point numbers. */
 #if !defined(DEBUG_OVERFLOW)
 #define JAS_FIX_DIV			JAS_FIX_DIV_FAST
 #else
@@ -192,17 +225,17 @@
 #define JAS_FIX_DIV			JAS_FIX_DIV_UFLOW
 #endif
 
-/* Calculate the quotient of two fixed-point numbers without underflow
+/*! 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
+/*! 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. */
+/*! Negate a fixed-point number. */
 #if !defined(DEBUG_OVERFLOW)
 #define	JAS_FIX_NEG			JAS_FIX_NEG_FAST
 #else
@@ -209,17 +242,17 @@
 #define	JAS_FIX_NEG			JAS_FIX_NEG_OFLOW
 #endif
 
-/* Negate a fixed-point number without overflow checking. */
+/*! 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. */
+/*! 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. */
+/*! Perform an arithmetic shift left of a fixed-point number. */
 #if !defined(DEBUG_OVERFLOW)
 #define	JAS_FIX_ASL			JAS_FIX_ASL_FAST
 #else
@@ -226,17 +259,17 @@
 #define	JAS_FIX_ASL			JAS_FIX_ASL_OFLOW
 #endif
 
-/* Perform an arithmetic shift left of a fixed-point number without overflow
+/*! 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
+/*! 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. */
+/*! Perform an arithmetic shift right of a fixed-point number. */
 #if !defined(DEBUG_OVERFLOW)
 #define	JAS_FIX_ASR			JAS_FIX_ASR_FAST
 #else
@@ -243,12 +276,12 @@
 #define	JAS_FIX_ASR			JAS_FIX_ASR_UFLOW
 #endif
 
-/* Perform an arithmetic shift right of a fixed-point number without underflow
+/*! 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
+/*! 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)
@@ -257,19 +290,19 @@
 * Other basic arithmetic operations.
 \******************************************************************************/
 
-/* Calculate the difference between two fixed-point numbers. */
+/*! 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. */
+/*! 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. */
+/*! 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. */
+/*! 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))
 
@@ -277,15 +310,15 @@
 * Miscellaneous operations.
 \******************************************************************************/
 
-/* Calculate the absolute value of a fixed-point number. */
+/*! 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? */
+/*! 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. */
+/*! Get the sign of a fixed-point number. */
 #define JAS_FIX_SGN(fix_t, fracbits, x) \
 	((x) >= 0 ? 1 : (-1))
 
@@ -293,23 +326,23 @@
 * Relational operations.
 \******************************************************************************/
 
-/* Compare two fixed-point numbers. */
+/*! Compare two fixed-point numbers. */
 #define JAS_FIX_CMP(fix_t, fracbits, x, y) \
 	((x) > (y) ? 1 : (((x) == (y)) ? 0 : (-1)))
 
-/* Less than. */
+/*! Less than. */
 #define	JAS_FIX_LT(fix_t, fracbits, x, y) \
 	((x) < (y))
 
-/* Less than or equal. */
+/*! Less than or equal. */
 #define	JAS_FIX_LTE(fix_t, fracbits, x, y) \
 	((x) <= (y))
 
-/* Greater than. */
+/*! Greater than. */
 #define	JAS_FIX_GT(fix_t, fracbits, x, y) \
 	((x) > (y))
 
-/* Greater than or equal. */
+/*! Greater than or equal. */
 #define	JAS_FIX_GTE(fix_t, fracbits, x, y) \
 	((x) >= (y))
 
@@ -317,7 +350,7 @@
 * Rounding functions.
 \******************************************************************************/
 
-/* Round a fixed-point number to the nearest integer. */
+/*! 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))) : \
@@ -324,7 +357,7 @@
 	  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
+/*! 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)))
@@ -336,11 +369,31 @@
 
 /* Handle overflow. */
 #define	JAS_FIX_OFLOW() \
-	jas_eprintf("overflow error: file %s, line %d\n", __FILE__, __LINE__)
+	jas_logerrorf("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__)
+	jas_logerrorf("underflow error: file %s, line %d\n", __FILE__, __LINE__)
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+JAS_ATTRIBUTE_DISABLE_UBSAN
+static inline jas_fix_t jas_fix_asl(jas_fix_t x, unsigned n)
+{
+	return JAS_FIX_ASL(jas_fix_t, 0, x, n);
+}
+
+JAS_ATTRIBUTE_DISABLE_UBSAN
+static inline jas_fix_t jas_fix_asr(jas_fix_t x, unsigned n)
+{
+	return JAS_FIX_ASR(jas_fix_t, 0, x, n);
+}
+
+/*!
+ * @}
+ */
 
 #ifdef __cplusplus
 }
--- a/jasper/jas_icc.h
+++ b/jasper/jas_icc.h
@@ -77,6 +77,11 @@
 extern "C" {
 #endif
 
+/*!
+ * @addtogroup module_cm
+ * @{
+ */
+
 /* Profile file signature. */
 #define	JAS_ICC_MAGIC		0x61637370
 
@@ -308,6 +313,7 @@
 	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). */
@@ -381,29 +387,145 @@
 	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);
+/*!
+@brief
+Read an ICC profile from a stream.
+*/
+JAS_EXPORT
+jas_iccprof_t *jas_iccprof_load(jas_stream_t *in);
+
+/*!
+@brief
+Write an ICC profile to a stream.
+*/
+JAS_EXPORT
+int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out);
+
+/*!
+@brief
+Destroy an ICC profile.
+*/
+JAS_EXPORT
+void jas_iccprof_destroy(jas_iccprof_t *prof);
+
+/*!
+@brief
+Get an attribute of an ICC profile.
+*/
 JAS_ATTRIBUTE_PURE
-JAS_DLLEXPORT jas_iccattrval_t *jas_iccprof_getattr(const jas_iccprof_t *prof,
+JAS_EXPORT
+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,
+
+/*!
+@brief
+Set an attribute of an ICC profile.
+*/
+JAS_EXPORT
+int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name,
   jas_iccattrval_t *val);
-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 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);
+/*!
+@brief
+Dump an ICC profile to a stream in human-readable format
+for debugging purposes.
+*/
+JAS_EXPORT
+void jas_iccprof_dump(const jas_iccprof_t *prof, 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);
-JAS_DLLEXPORT jas_iccprof_t *jas_iccprof_copy(const jas_iccprof_t *prof);
+/*!
+@brief
+Create a copy of an ICC profile.
+*/
+JAS_EXPORT
+jas_iccprof_t *jas_iccprof_copy(const jas_iccprof_t *prof);
+
+/*!
+@brief
+Get the header for an ICC profile.
+*/
+JAS_EXPORT
+int jas_iccprof_gethdr(const jas_iccprof_t *prof, jas_icchdr_t *hdr);
+
+/*!
+@brief
+Set the header for an ICC profile.
+*/
+JAS_EXPORT
+int jas_iccprof_sethdr(jas_iccprof_t *prof, const jas_icchdr_t *hdr);
+
+/*!
+@brief
+Destroy an ICC profile attribute.
+*/
+JAS_EXPORT
+void jas_iccattrval_destroy(jas_iccattrval_t *attrval);
+
+/*!
+@brief
+*/
+JAS_EXPORT
+void jas_iccattrval_dump(const jas_iccattrval_t *attrval, FILE *out);
+
+/*!
+@brief
+
+TODO/FIXME
+*/
+JAS_EXPORT
+int jas_iccattrval_allowmodify(jas_iccattrval_t **attrval);
+
+/*!
+@brief
+Create a copy of an ICC profile attribute.
+*/
+JAS_EXPORT
+jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval);
+
+/*!
+@brief
+Create an ICC profile attribute.
+*/
+JAS_EXPORT
+jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type);
+
+/*!
+@brief
+Dump an ICC profile attribute to a stream in human-readable format
+for debugging purposes.
+*/
+JAS_EXPORT
+void jas_iccattrtab_dump(const jas_iccattrtab_t *attrtab, FILE *out);
+
+/*!
+@brief
+Create an ICC profile from a buffer in memory.
+*/
+JAS_EXPORT
+jas_iccprof_t *jas_iccprof_createfrombuf(const jas_uchar *buf, unsigned len);
+
+/*!
+@brief
+Create an ICC profile from a color space.
+*/
+JAS_EXPORT
+jas_iccprof_t *jas_iccprof_createfromclrspc(unsigned clrspc);
+
+JAS_EXPORT
+extern const jas_uchar jas_iccprofdata_srgb[];
+
+JAS_EXPORT
+extern const unsigned jas_iccprofdata_srgblen;
+
+JAS_EXPORT
+extern const jas_uchar jas_iccprofdata_sgray[];
+
+JAS_EXPORT
+extern const unsigned jas_iccprofdata_sgraylen;
+
+/*!
+ * @}
+ */
 
 #ifdef __cplusplus
 }
--- a/jasper/jas_image.h
+++ b/jasper/jas_image.h
@@ -86,7 +86,7 @@
 #endif
 
 /*!
- * @addtogroup image
+ * @addtogroup module_images
  * @{
  */
 
@@ -128,7 +128,8 @@
 \******************************************************************************/
 
 /*!
-@brief Image coordinate. */
+@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
@@ -154,81 +155,95 @@
 \******************************************************************************/
 
 /*!
-@brief Image component class.
+@brief
+Image component class.
+
+@warning
+Library users should never directly access any of the members of this
+class.
+The functions/macros provided by the JasPer library API should always
+be used.
 */
 typedef struct {
 
-	jas_image_coord_t tlx_;
 	/* The x-coordinate of the top-left corner of the component. */
+	jas_image_coord_t tlx_;
 
-	jas_image_coord_t tly_;
 	/* The y-coordinate of the top-left corner of the component. */
+	jas_image_coord_t tly_;
 
-	jas_image_coord_t hstep_;
 	/* The horizontal sampling period in units of the reference grid. */
+	jas_image_coord_t hstep_;
 
-	jas_image_coord_t vstep_;
 	/* The vertical sampling period in units of the reference grid. */
+	jas_image_coord_t vstep_;
 
-	jas_image_coord_t width_;
 	/* The component width in samples. */
+	jas_image_coord_t width_;
 
-	jas_image_coord_t height_;
 	/* The component height in samples. */
+	jas_image_coord_t height_;
 
+	/* 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. */
 	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. */
+	int sgnd_;
 
-	jas_stream_t *stream_;
 	/* The stream containing the component data. */
+	jas_stream_t *stream_;
 
-	unsigned cps_;
 	/* The number of characters per sample in the stream. */
+	unsigned cps_;
 
-	jas_image_cmpttype_t type_;
 	/* The type of component (e.g., opacity, red, green, blue, luma). */
+	jas_image_cmpttype_t type_;
 
 } jas_image_cmpt_t;
 
 /*!
 @brief Image class.
+
+@warning
+Library users should never directly access any of the members of this
+class.
+The functions/macros provided by the JasPer library API should always
+be used.
 */
 typedef struct {
 
-	jas_image_coord_t tlx_;
 	/* The x-coordinate of the top-left corner of the image bounding box. */
+	jas_image_coord_t tlx_;
 
-	jas_image_coord_t tly_;
 	/* The y-coordinate of the top-left corner of the image bounding box. */
+	jas_image_coord_t tly_;
 
-	jas_image_coord_t brx_;
 	/* The x-coordinate of the bottom-right corner of the image bounding
 	  box (plus one). */
+	jas_image_coord_t brx_;
 
-	jas_image_coord_t bry_;
 	/* The y-coordinate of the bottom-right corner of the image bounding
 	  box (plus one). */
+	jas_image_coord_t bry_;
 
-	unsigned numcmpts_;
 	/* The number of components. */
+	unsigned numcmpts_;
 
-	unsigned maxcmpts_;
 	/* The maximum number of components that this image can have (i.e., the
 	  allocated size of the components array). */
+	unsigned maxcmpts_;
 
-	jas_image_cmpt_t **cmpts_;
 	/* Per-component information. */
+	jas_image_cmpt_t **cmpts_;
 
+	/* The color space. */
 	jas_clrspc_t clrspc_;
 
+	/* The CM profile. */
 	jas_cmprof_t *cmprof_;
 
-//	bool inmem_;
+	//bool inmem_;
 
 } jas_image_t;
 
@@ -241,29 +256,29 @@
 */
 typedef struct {
 
-	jas_image_coord_t tlx;
 	/* The x-coordinate of the top-left corner of the component. */
+	jas_image_coord_t tlx;
 
-	jas_image_coord_t tly;
 	/* The y-coordinate of the top-left corner of the component. */
+	jas_image_coord_t tly;
 
-	jas_image_coord_t hstep;
 	/* The horizontal sampling period in units of the reference grid. */
+	jas_image_coord_t hstep;
 
-	jas_image_coord_t vstep;
 	/* The vertical sampling period in units of the reference grid. */
+	jas_image_coord_t vstep;
 
-	jas_image_coord_t width;
 	/* The width of the component in samples. */
+	jas_image_coord_t width;
 
-	jas_image_coord_t height;
 	/* The height of the component in samples. */
+	jas_image_coord_t height;
 
-	unsigned prec;
 	/* The precision of the component sample data. */
+	unsigned prec;
 
-	int sgnd;
 	/* The signedness of the component sample data. */
+	int sgnd;
 
 } jas_image_cmptparm_t;
 
@@ -281,14 +296,14 @@
 */
 typedef struct {
 
+	/*! Decode image data from a stream. */
 	jas_image_t *(*decode)(jas_stream_t *in, const char *opts);
-	/* Decode image data from a stream. */
 
+	/*! Encode image data to a stream. */
 	int (*encode)(jas_image_t *image, jas_stream_t *out, const char *opts);
-	/* Encode image data to a stream. */
 
+	/*! Determine if stream data is in a particular format. */
 	int (*validate)(jas_stream_t *in);
-	/* Determine if stream data is in a particular format. */
 
 } jas_image_fmtops_t;
 
@@ -297,20 +312,29 @@
 */
 typedef struct {
 
+	/*! The ID for this format. */
 	int id;
-	/* The ID for this format. */
 
+	/*! The name by which this format is identified. */
 	char *name;
-	/* The name by which this format is identified. */
 
+	/* The primary file name extension associated with this format. */
+	/* This member only exists for backward compatibility. */
 	char *ext;
-	/* The file name extension associated with this format. */
 
+	/*! The table of file name extensions associated with this format. */
+	char **exts;
+	size_t max_exts;
+	size_t num_exts;
+
+	/*! A boolean flag indicating if this format is enabled. */
+	int enabled;
+
+	/*! A brief description of the format. */
 	char *desc;
-	/* A brief description of the format. */
 
+	/*! The operations for this format. */
 	jas_image_fmtops_t ops;
-	/* The operations for this format. */
 
 } jas_image_fmtinfo_t;
 
@@ -321,23 +345,27 @@
 /*!
 @brief Create an image.
 */
-JAS_DLLEXPORT jas_image_t *jas_image_create(unsigned numcmpts,
+JAS_EXPORT
+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);
+JAS_EXPORT
+jas_image_t *jas_image_create0(void);
 
 /*!
 @brief Clone an image.
 */
-JAS_DLLEXPORT jas_image_t *jas_image_copy(jas_image_t *image);
+JAS_EXPORT
+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);
+JAS_EXPORT
+void jas_image_destroy(jas_image_t *image);
 
 /*!
 @brief Get the width of the image in units of the image reference grid.
@@ -470,7 +498,8 @@
 @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);
+JAS_EXPORT
+bool jas_image_cmpt_domains_same(const jas_image_t *image);
 
 /*!
 @brief Get the raw size of an image
@@ -477,19 +506,19 @@
 (i.e., the nominal size of the image without any compression.
 */
 JAS_ATTRIBUTE_PURE
-JAS_DLLEXPORT
+JAS_EXPORT
 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_EXPORT
 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
+JAS_EXPORT
 int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt,
   const char *optstr);
 
@@ -500,7 +529,7 @@
 The position and size of the rectangular region to be read is specified
 relative to the component's coordinate system.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 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);
@@ -508,7 +537,7 @@
 /*!
 @brief Write a rectangular region of an image component.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 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);
@@ -516,18 +545,21 @@
 /*!
 @brief Delete a component from an image.
 */
-JAS_DLLEXPORT void jas_image_delcmpt(jas_image_t *image, unsigned cmptno);
+JAS_EXPORT
+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,
+JAS_EXPORT
+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_EXPORT
+int jas_image_copycmpt(jas_image_t *dstimage, unsigned dstcmptno,
   jas_image_t *srcimage, unsigned srccmptno);
 
 JAS_ATTRIBUTE_CONST
@@ -555,7 +587,8 @@
 }
 
 JAS_ATTRIBUTE_PURE
-static inline uint_least8_t jas_image_cmptdtype(const jas_image_t *image, unsigned cmptno)
+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_);
@@ -564,7 +597,7 @@
 /*!
 @brief Depalettize an image
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_depalettize(jas_image_t *image, unsigned cmptno,
   unsigned numlutents, const int_fast32_t *lutents, unsigned dtype,
   unsigned newcmptno);
@@ -572,7 +605,7 @@
 /*!
 @brief Read a component sample for an image.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_readcmptsample(jas_image_t *image, unsigned cmptno, unsigned x,
   unsigned y);
 
@@ -579,7 +612,7 @@
 /*!
 @brief Write a component sample for an image.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 void jas_image_writecmptsample(jas_image_t *image, unsigned cmptno,
   unsigned x, unsigned y, int_fast32_t v);
 
@@ -587,7 +620,7 @@
 @brief Get an image component by its type.
 */
 JAS_ATTRIBUTE_PURE
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_getcmptbytype(const jas_image_t *image, jas_image_cmpttype_t ctype);
 
 /******************************************************************************\
@@ -597,21 +630,65 @@
 /*!
 @brief Clear the table of image formats.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 void jas_image_clearfmts(void);
 
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+void jas_image_clearfmts_internal(jas_image_fmtinfo_t *image_fmtinfos,
+  size_t *image_numfmts);
+#endif
+
 /*!
+@brief Get a image format entry by its table index.
+*/
+JAS_EXPORT
+const jas_image_fmtinfo_t *jas_image_getfmtbyind(int index);
+
+/*!
+@brief Get the number of image format table entries.
+*/
+JAS_EXPORT
+int jas_image_getnumfmts(void);
+
+#if 0
+JAS_EXPORT
+int jas_image_delfmtbyid(int id);
+#endif
+
+/*!
+@brief Get the number of image format table entries.
+
+@warning
+This function may be removed in future versions of the library.
+Do not rely on it.
+*/
+JAS_EXPORT
+int jas_image_setfmtenable(int index, int enabled);
+
+#if 0
+// TODO: should this be added?
+JAS_EXPORT
+int jas_image_getfmtindbyname(const char* name);
+#endif
+
+/*!
 @brief Add entry to table of image formats.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_addfmt(int id, const char *name, const char *ext,
   const char *desc, const jas_image_fmtops_t *ops);
 
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+int jas_image_addfmt_internal(jas_image_fmtinfo_t *image_fmtinfos,
+  size_t *image_numfmts, int id, const char *name, const char *ext,
+  const char *desc, const jas_image_fmtops_t *ops);
+#endif
+
 /*!
 @brief Get the ID for the image format with the specified name.
 */
 JAS_ATTRIBUTE_PURE
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_strtofmt(const char *s);
 
 /*!
@@ -618,7 +695,7 @@
 @brief Get the name of the image format with the specified ID.
 */
 JAS_ATTRIBUTE_CONST
-JAS_DLLEXPORT
+JAS_EXPORT
 const char *jas_image_fmttostr(int fmt);
 
 /*!
@@ -625,7 +702,7 @@
 @brief Lookup image format information by the format ID.
 */
 JAS_ATTRIBUTE_CONST
-JAS_DLLEXPORT
+JAS_EXPORT
 const jas_image_fmtinfo_t *jas_image_lookupfmtbyid(int id);
 
 /*!
@@ -632,7 +709,7 @@
 @brief Lookup image format information by the format name.
 */
 JAS_ATTRIBUTE_PURE
-JAS_DLLEXPORT
+JAS_EXPORT
 const jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name);
 
 /*!
@@ -639,17 +716,19 @@
 @brief Guess the format of an image file based on its name.
 */
 JAS_ATTRIBUTE_PURE
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_fmtfromname(const char *filename);
 
 /*!
 @brief Get the format of image data in a stream.
+
+@details
+Note that only enabled codecs are used in determining the image format.
 */
 JAS_ATTRIBUTE_PURE
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_getfmt(jas_stream_t *in);
 
-
 /*!
 @brief Get the color management profile of an image.
 */
@@ -656,16 +735,17 @@
 #define	jas_image_cmprof(image)	((image)->cmprof_)
 
 /*!
-@brief ???
+@brief
+Test if the sampling of the image is homogeneous.
 */
 JAS_ATTRIBUTE_PURE
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_image_ishomosamp(const jas_image_t *image);
 
 /*!
 @brief ???
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 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);
@@ -673,14 +753,15 @@
 /*!
 @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);
+JAS_EXPORT
+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
+JAS_EXPORT
 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);
@@ -693,9 +774,16 @@
 /*!
 @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);
+JAS_EXPORT
+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_EXPORT
+int jas_image_dump(jas_image_t *image, FILE *out);
+
 /******************************************************************************\
 * Image format-dependent operations.
 \******************************************************************************/
@@ -702,58 +790,92 @@
 
 #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);
+//JAS_EXPORT
+jas_image_t *jpg_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int jpg_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+int jpg_validate(jas_stream_t *in);
 #endif
 
+#if defined(JAS_INCLUDE_HEIC_CODEC)
+/* Format-dependent operations for HEIC support. */
+//JAS_EXPORT
+jas_image_t *jas_heic_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int jas_heic_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+int jas_heic_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);
+//JAS_EXPORT
+jas_image_t *mif_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int mif_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+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);
+//JAS_EXPORT
+jas_image_t *pnm_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int pnm_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+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);
+//JAS_EXPORT
+jas_image_t *ras_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int ras_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+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);
+//JAS_EXPORT
+jas_image_t *bmp_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int bmp_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+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);
+//JAS_EXPORT
+jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+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);
+//JAS_EXPORT
+jas_image_t *jpc_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int jpc_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+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);
+//JAS_EXPORT
+jas_image_t *pgx_decode(jas_stream_t *in, const char *optstr);
+//JAS_EXPORT
+int pgx_encode(jas_image_t *image, jas_stream_t *out, const char *optstr);
+//JAS_EXPORT
+int pgx_validate(jas_stream_t *in);
 #endif
 
 /*!
--- a/jasper/jas_init.h
+++ b/jasper/jas_init.h
@@ -70,41 +70,422 @@
 /* The configuration header file should be included first. */
 #include <jasper/jas_config.h>
 
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_log.h"
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /*!
- * @addtogroup init
+ * @addtogroup module_init
  * @{
  */
 
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+/*
+Per-thread library context.
+*/
+typedef struct {
+
+	/*
+	The level of debugging checks/output enabled by the library.
+	A larger value corresponds to a greater level of debugging checks/output.
+	*/
+	int debug_level;
+
+	/*
+	The function used to output error/warning/informational messages.
+	int (*vlogmsgf)(jas_logtype_t type, const char *format, va_list ap);
+	*/
+	jas_vlogmsgf_t *vlogmsgf;
+
+	/*
+	The image format information to be used to populate the image format
+	table.
+	*/
+	size_t image_numfmts;
+	jas_image_fmtinfo_t image_fmtinfos[JAS_IMAGE_MAXFMTS];
+
+	/* The maximum number of samples allowable in an image to be decoded. */
+	size_t dec_default_max_samples;
+
+} jas_ctx_t;
+#endif
+
+/*!
+@brief
+An opaque handle type used to represent a JasPer library context.
+*/
+typedef void *jas_context_t;
+
 /******************************************************************************\
-* Functions.
+* Library Run-Time Configuration.
 \******************************************************************************/
 
 /*!
-@brief Initialize the JasPer library.
+@brief
+Configure the JasPer library with the default configuration settings.
 
 @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.
+This function configures the JasPer library with the default configuration
+settings.
+These settings may be change via the @c jas_conf_* family of function
+prior to invoking jas_init_library().
 
+@warning
+Configuration, initialization, and cleanup of the library must be performed
+on the same thread.
+*/
+JAS_EXPORT
+void jas_conf_clear(void);
+
+/*!
+@brief Set the multithreading flag for the library.
+
+@details
+*/
+JAS_EXPORT
+void jas_conf_set_multithread(int multithread);
+
+/*!
+@brief Set the memory allocator to be used by the library.
+
+@details
+The object referenced by @c allocator must have a live at least
+until jas_cleanup() is invoked.
+How the memory in which @c *allocator reside is allocated is the
+responsibility of the caller.
+*/
+JAS_EXPORT
+void jas_conf_set_allocator(jas_allocator_t *allocator);
+
+/*!
+@brief Set the initial debug level for the library.
+
+@details
+*/
+JAS_EXPORT
+void jas_conf_set_debug_level(int debug_level);
+
+/*!
+@brief
+Set the maximum amount of memory that can be used by the library
+(assuming the allocator wrapper is not disabled).
+
+@details
+
+@warning
+It is strongly recommended that the memory usage limit not be set to an
+excessively large value, as this poses security risks (e.g., decoding a
+malicious image file could exhaust all virtual memory and effectively
+crash the system).
+*/
+JAS_EXPORT
+void jas_conf_set_max_mem_usage(size_t max_mem);
+
+/*!
+@brief
+Set the default value for the maximum number of samples that is
+allowed in an image to be decoded.
+
+@details
+*/
+JAS_EXPORT
+void jas_conf_set_dec_default_max_samples(size_t max_samples);
+
+/*!
+@brief
+Set the function used by the library to output error, warning, and
+informational messages.
+
+@details
+*/
+JAS_EXPORT
+void jas_conf_set_vlogmsgf(jas_vlogmsgf_t *func);
+
+/******************************************************************************\
+* Library Initialization and Cleanup.
+\******************************************************************************/
+
+/*!
+@brief
+Initialize the JasPer library with the current configuration settings.
+
+@details
+The library must be configured by invoking the jas_conf_clear() function
+prior to calling jas_init_library().
+
 @returns
-If successful, zero is returned; otherwise, a nonzero value is returned.
+If the initialization of the library is successful, zero is returned;
+otherwise, a nonzero value is returned.
+
+@warning
+The jas_init_library() function does NOT synchronize with the
+jas_conf_clear() function.
+Configuration, initialization, and cleanup of the library must be
+performed on the same thread.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
+int jas_init_library(void);
+
+/*!
+@brief
+Perform clean up for the JasPer library.
+
+@details
+At the point when this function is called, all threads that have called
+jas_init_thread() must have called jas_cleanup_thread().
+
+@returns
+If the operation is successful, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+JAS_EXPORT
+int jas_cleanup_library(void);
+
+/******************************************************************************\
+* Thread Initialization and Cleanup.
+\******************************************************************************/
+
+/*!
+@brief
+Perform per-thread initialization for the JasPer library.
+
+@details
+The library must be initialized by invoking the jas_init_library() function
+prior to calling jas_init_thread().
+
+@warning
+The jas_init_thread() function can only be invoked in a single thread
+unless the run-time configuration has enabled multithreading via
+jas_set_multithread().
+*/
+JAS_EXPORT
+int jas_init_thread(void);
+
+/*!
+@brief
+Perform per-thread cleanup for the JasPer library.
+
+@details
+*/
+JAS_EXPORT
+int jas_cleanup_thread(void);
+
+/******************************************************************************\
+* Legacy Initialization and Cleanup Functions.
+\******************************************************************************/
+
+/*!
+@brief
+Configure and initialize the JasPer library using the default
+configuration settings.
+
+@details
+The jas_init() function initializes the JasPer library.
+The library must be initialized before most code in the library can be used.
+
+The jas_init() function exists only for reasons of backward compatibility
+with earlier versions of the library.
+It is recommended that this function not be used.
+Instead, the jas_conf_clear() and jas_init_library() functions should be used
+to configure and initialize the library.
+
+@returns
+If the library is successfully initialized, zero is returned;
+otherwise, a nonzero value is returned.
+
+@warning
+Configuration, initialization, and cleanup of the library must be performed
+on the same thread.
+
+@deprecated
+This function is deprecated.
+*/
+JAS_EXPORT
 int jas_init(void);
 
 /*!
-@brief Perform any clean up for the JasPer library.
+@brief
+Perform any clean up for the JasPer library.
 
 @details
 This function performs any clean up for the JasPer library.
+
+@warning
+Configuration, initialization, and cleanup of the library must be performed
+on the same thread.
+
+@deprecated
+This function is deprecated.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 void jas_cleanup(void);
+
+/******************************************************************************\
+* Context Management
+\******************************************************************************/
+
+/*!
+@brief
+Create a context.
+
+@details
+*/
+JAS_EXPORT
+jas_context_t jas_context_create(void);
+
+/*!
+@brief
+Destroy a context.
+
+@details
+The context being destroyed must not be the current context.
+*/
+JAS_EXPORT
+void jas_context_destroy(jas_context_t context);
+
+/*!
+@brief
+Get the current context for the calling thread.
+
+@details
+*/
+JAS_EXPORT
+jas_context_t jas_get_default_context(void);
+
+/*!
+@brief
+Get the current context for the calling thread.
+
+@details
+*/
+JAS_EXPORT
+jas_context_t jas_get_context(void);
+
+/*!
+@brief
+Set the current context for the calling thread.
+
+@details
+*/
+JAS_EXPORT
+void jas_set_context(jas_context_t context);
+
+/******************************************************************************\
+* Getting/Setting Context Properties
+\******************************************************************************/
+
+/* This function is only for internal use by the library. */
+JAS_EXPORT
+int jas_get_debug_level_internal(void);
+
+/* This function is only for internal use by the library. */
+JAS_EXPORT
+size_t jas_get_dec_default_max_samples_internal(void);
+
+/* This function is only for internal use by the library. */
+JAS_EXPORT
+jas_vlogmsgf_t *jas_get_vlogmsgf_internal(void);
+
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+#if defined(JAS_HAVE_THREAD_LOCAL)
+extern _Thread_local jas_ctx_t *jas_cur_ctx;
+#endif
+
+/* This function is only for internal use by the library. */
+jas_ctx_t *jas_get_ctx_internal(void);
+
+/* This function is only for internal use by the library. */
+static inline jas_ctx_t *jas_get_ctx(void)
+{
+#if defined(JAS_HAVE_THREAD_LOCAL)
+	return jas_cur_ctx ? jas_cur_ctx : jas_get_ctx_internal();
+#else
+	return JAS_CAST(jas_ctx_t *, jas_get_ctx_internal());
+#endif
+}
+#endif
+
+/*!
+@brief
+Set the debug level for a particular context.
+
+@details
+*/
+JAS_EXPORT
+void jas_set_debug_level(int debug_level);
+
+/*!
+@brief
+Get the debug level for a particular context.
+
+@details
+*/
+static inline int jas_get_debug_level(void)
+{
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+	jas_ctx_t *ctx = jas_get_ctx();
+	return ctx->debug_level;
+#else
+	return jas_get_debug_level_internal();
+#endif
+}
+
+/*!
+@brief
+Set the default maximum number of samples that a decoder is permitted to
+process.
+
+@details
+*/
+JAS_EXPORT
+void jas_set_dec_default_max_samples(size_t max_samples);
+
+/*!
+@brief
+Get the default maximum number of samples that a decoder is permitted to
+process.
+
+@details
+*/
+static inline size_t jas_get_dec_default_max_samples(void)
+{
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+	jas_ctx_t *ctx = jas_get_ctx();
+	return ctx->dec_default_max_samples;
+#else
+	return jas_get_dec_default_max_samples_internal();
+#endif
+}
+
+/*!
+@brief
+Set the function to be used for log messages.
+
+@details
+*/
+JAS_EXPORT
+void jas_set_vlogmsgf(jas_vlogmsgf_t *func);
+
+/*!
+@brief
+Get the function to be used for log messages.
+
+@details
+*/
+static inline
+jas_vlogmsgf_t *jas_get_vlogmsgf(void)
+{
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+	jas_ctx_t *ctx = jas_get_ctx();
+	return ctx->vlogmsgf;
+#else
+	return jas_get_vlogmsgf_internal();
+#endif
+}
 
 /*!
  * @}
--- /dev/null
+++ b/jasper/jas_log.h
@@ -1,0 +1,168 @@
+/*
+ * 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_log.h
+ * @brief JasPer Logging Functionality
+ */
+
+#ifndef JAS_LOG_H
+#define JAS_LOG_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * @addtogroup module_log
+ * @{
+ */
+
+/******************************************************************************\
+* Macros and functions.
+\******************************************************************************/
+
+/*! Log type class for unclassified messages. */
+#define JAS_LOGTYPE_CLASS_NULL 0
+/*! Log type class for errors. */
+#define JAS_LOGTYPE_CLASS_ERROR 1
+/*! Log type class for warnings. */
+#define JAS_LOGTYPE_CLASS_WARN 2
+/*! Log type class for informational messages. */
+#define JAS_LOGTYPE_CLASS_INFO 3
+/*! Log type class for debugging messages. */
+#define JAS_LOGTYPE_CLASS_DEBUG 4
+#define JAS_LOGTYPE_NUM_CLASSES 5
+
+#define JAS_LOGTYPE_MAX_PRIORITY 16384
+
+// NOTE: without the @struct, jas_logtype_t autolinks are not generated
+/*!
+@struct jas_logtype_t
+@brief Type used for the log type.
+*/
+typedef unsigned int jas_logtype_t;
+
+/*!
+@brief Type used for formatted message logging function.
+*/
+typedef int (jas_vlogmsgf_t)(jas_logtype_t, const char *, va_list);
+
+/*!
+@brief Create an instance of a logtype.
+*/
+static inline jas_logtype_t jas_logtype_init(int clas, int priority)
+{
+	assert(clas >= 0 && clas < JAS_LOGTYPE_NUM_CLASSES);
+	assert(priority >= 0 && priority <= JAS_LOGTYPE_MAX_PRIORITY);
+	return (clas & 0xf) | (priority << 4);
+}
+
+/*!
+@brief Get the class of a logtype.
+*/
+static inline int jas_logtype_getclass(jas_logtype_t type)
+{
+	return type & 0xf;
+}
+
+/*!
+@brief Get the priority of a logtype.
+*/
+static inline int jas_logtype_getpriority(jas_logtype_t type)
+{
+	return type >> 4;
+}
+
+/*!
+@brief Print formatted log message.
+*/
+JAS_EXPORT
+int jas_vlogmsgf(jas_logtype_t type, const char *fmt, va_list ap);
+
+/*!
+@brief Output a log message to standard error.
+*/
+JAS_EXPORT
+int jas_vlogmsgf_stderr(jas_logtype_t type, const char *fmt, va_list ap);
+
+/*!
+@brief Output a log message to nowhere (i.e., discard the message).
+*/
+JAS_EXPORT
+int jas_vlogmsgf_discard(jas_logtype_t type, const char *fmt, va_list ap);
+
+/*!
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- a/jasper/jas_malloc.h
+++ b/jasper/jas_malloc.h
@@ -77,17 +77,282 @@
 /* The configuration header file should be included first. */
 #include <jasper/jas_config.h>
 
+#include <jasper/jas_types.h>
+#include <jasper/jas_thread.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#define jas_malloc malloc
-#define jas_free free
-#define jas_realloc realloc
-#define jas_calloc calloc
-#define jas_alloc2(ne, esz) malloc(ne*esz)
-#define jas_alloc3(na, asz, esz) malloc(na*asz*esz)
-#define jas_realloc2(p, ne, esz) realloc(p, ne*esz)
+/*!
+ * @addtogroup module_alloc
+ * @{
+ */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/*!
+@brief A memory allocator.
+*/
+typedef struct jas_allocator_s {
+
+	/*!
+	Function to clean up the allocator when no longer needed.
+	The allocator cannot be used after the clean-up operation is performed.
+	This function pointer may be null, in which case the clean-up operation
+	is treated as a no-op.
+	*/
+	void (*cleanup)(struct jas_allocator_s *allocator);
+
+	/*!
+	Function to allocate memory.
+	This function should have behavior similar to malloc.
+	*/
+	void *(*alloc)(struct jas_allocator_s *allocator, size_t size);
+
+	/*!
+	Function to deallocate memory.
+	This function should have behavior similar to free.
+	*/
+	void (*free)(struct jas_allocator_s *allocator, void *pointer);
+
+	/*!
+	Function to reallocate memory.
+	This function should have behavior similar to realloc.
+	*/
+	void *(*realloc)(struct jas_allocator_s *allocator, void *pointer,
+	  size_t new_size);
+
+	/*! For future use. */
+	void (*(reserved[4]))(void);
+
+} jas_allocator_t;
+
+/*!
+@brief The standard library allocator (i.e., a wrapper for malloc and friends).
+
+@details
+Essentially, jas_std_allocator_t can be thought of as having an inheritance
+relationship with jas_allocator_t.
+In particular, jas_std_allocator_t is derived from jas_allocator_t.
+*/
+typedef struct {
+
+	/* The base class. */
+	jas_allocator_t base;
+
+} jas_std_allocator_t;
+
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+/*
+The allocator wrapper type.
+This type is an allocator that adds memory usage tracking to another
+allocator.
+The allocator wrapper does not directly perform memory allocation itself.
+Instead, it delegate to another allocator.
+*/
+typedef struct {
+
+	/* The base class. */
+	jas_allocator_t base;
+
+	/* The delegated-to allocator. */
+	jas_allocator_t *delegate;
+
+	/* The maximum amount of memory that can be used by the allocator. */
+	size_t max_mem;
+
+	/* The current amount of memory in use by the allocator. */
+	size_t mem;
+
+#if defined(JAS_THREADS)
+	/* A mutex for synchronized access to the allocator. */
+	jas_mutex_t mutex;
+#endif
+
+} jas_basic_allocator_t;
+#endif
+
+/******************************************************************************\
+* Data.
+\******************************************************************************/
+
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+extern jas_allocator_t *jas_allocator;
+extern jas_std_allocator_t jas_std_allocator;
+extern jas_basic_allocator_t jas_basic_allocator;
+#endif
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/*!
+@brief
+Allocate memory.
+
+@details
+This function has an identical behavior as malloc (from the C standard
+library), except that a zero-sized allocation returns a non-null pointer
+(assuming no out-of-memory error occurs).
+*/
+JAS_EXPORT
+void *jas_malloc(size_t size);
+
+/*!
+@brief
+Free memory.
+
+@details
+This function has an identical behavior as free (from the C standard library).
+*/
+JAS_EXPORT
+void jas_free(void *ptr);
+
+/*!
+@brief
+Resize a block of allocated memory.
+
+@details
+This function has an identical behavior as realloc (from the C standard
+library).
+*/
+JAS_EXPORT
+void *jas_realloc(void *ptr, size_t size);
+
+/*!
+@brief
+Allocate a block of memory and initialize the contents to zero.
+
+@details
+This function has an identical behavior as calloc (from the C standard
+library).
+*/
+JAS_EXPORT
+void *jas_calloc(size_t num_elements, size_t element_size);
+
+/*!
+@brief
+Allocate array (with overflow checking).
+*/
+JAS_EXPORT
+void *jas_alloc2(size_t num_elements, size_t element_size);
+
+/*!
+@brief
+Allocate array of arrays (with overflow checking).
+*/
+JAS_EXPORT
+void *jas_alloc3(size_t num_arrays, size_t array_size, size_t element_size);
+
+/*!
+@brief
+Resize a block of allocated memory (with overflow checking).
+*/
+JAS_EXPORT
+void *jas_realloc2(void *ptr, size_t num_elements, size_t element_size);
+
+/*!
+@brief
+Set the maximum memory usage allowed by the allocator wrapper.
+
+@param max_mem
+The maximum amount of memory (in bytes) that the allocator can use.
+
+
+@details
+This function sets the maximum amount of memory (in bytes) that the
+allocator wrapper is permitted to use to @c max_mem.
+If @c max_mem is zero, no limit is imposed on the amount of memory used by
+allocator.
+This function can only be called if the use of the allocator wrapper
+is enabled.
+Calling this function if the allocator wrapper is not enabled results
+in undefined behavior.
+The limit on the amount of memory that the allocator can use should
+never be set to a value less than the amount of memory currently being
+used by the allocator (as doing so results in undefined behavior).
+*/
+JAS_EXPORT
+void jas_set_max_mem_usage(size_t max_mem);
+
+/*!
+@brief
+Get the current memory usage from the allocator wrapper.
+
+@details
+This function queries the amount of memory currently in use by the allocator
+wrapper.
+This function can only be called if the use of the allocator wrapper
+is enabled.
+Calling this function if the allocator wrapper is not enabled results
+in undefined behavior.
+*/
+JAS_EXPORT
+size_t jas_get_mem_usage(void);
+
+/*!
+@brief
+Initialize a memory allocator that uses malloc and related functions
+for managing memory.
+
+@param allocator
+A pointer to the storage in memory that will hold the state associated
+with the allocator.
+
+@details
+The object referenced by @c allocator must have a lifetime that extends
+until @c jas_allocator_cleanup is called for the allocator.
+*/
+JAS_EXPORT
+void jas_std_allocator_init(jas_std_allocator_t *allocator);
+
+/*!
+@brief
+Clean up an allocator that is no longer needed.
+
+@details
+This function cleans up an allocator, releasing any resources associated
+with the allocator.
+After clean up is performed, the allocator can no longer be used.
+*/
+JAS_EXPORT
+void jas_allocator_cleanup(jas_allocator_t *allocator);
+
+#if defined(JAS_FOR_INTERNAL_USE_ONLY)
+
+/* This function is for internal library use only. */
+void jas_set_allocator(jas_allocator_t* allocator);
+
+/* This function is for internal library use only. */
+void jas_basic_allocator_init(jas_basic_allocator_t *allocator,
+  jas_allocator_t *delegate, size_t max_mem);
+
+#endif
+
+/*!
+@brief
+Get the total amount of memory available on the system.
+
+@details
+This function may be called prior to the library being initialized.
+In fact, this function may be useful for determining a reasonable value
+for the memory limit setting to be used during (run-time) library
+configuration.
+
+@returns
+The total amount of memory available (in bytes) is returned, if this can
+be determined.
+Otherwise, zero is returned.
+*/
+JAS_EXPORT
+size_t jas_get_total_mem_size(void);
+
+/*!
+ * @}
+ */
 
 #ifdef __cplusplus
 }
--- a/jasper/jas_math.h
+++ b/jasper/jas_math.h
@@ -75,6 +75,8 @@
 
 /* The configuration header file should be included first. */
 #include <jasper/jas_config.h>
+
+#include <jasper/jas_compiler.h>
 #include <jasper/jas_types.h>
 
 #ifdef __cplusplus
@@ -109,6 +111,12 @@
   set to one. */
 #define	JAS_ONES(n) \
   ((1 << (n)) - 1)
+#if 0
+#define	JAS_ONES_X(type, n) \
+  ((JAS_CAST(type, 1) << (n)) - 1)
+#endif
+#define	JAS_POW2_X(type, n) \
+  (JAS_CAST(type, 1) << (n))
 
 /******************************************************************************\
 *
@@ -122,13 +130,13 @@
 #endif
 
 JAS_ATTRIBUTE_CONST
-JAS_ATTRIBUTE_DISABLE_USAN
+JAS_ATTRIBUTE_DISABLE_UBSAN
 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. */
+	// The behavior is undefined when x is negative.
 	// We tacitly assume the behavior is equivalent to a signed
 	// arithmetic right shift.
 	return x >> n;
@@ -135,13 +143,13 @@
 }
 
 JAS_ATTRIBUTE_CONST
-JAS_ATTRIBUTE_DISABLE_USAN
+JAS_ATTRIBUTE_DISABLE_UBSAN
 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. */
+	// The behavior is undefined when x is negative.
 	// We tacitly assume the behavior is equivalent to a signed
 	// arithmetic left shift.
 	return x << n;
@@ -148,13 +156,13 @@
 }
 
 JAS_ATTRIBUTE_CONST
-JAS_ATTRIBUTE_DISABLE_USAN
+JAS_ATTRIBUTE_DISABLE_UBSAN
 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. */
+	// The behavior is undefined when x is negative.
 	// We tacitly assume the behavior is equivalent to a signed
 	// arithmetic right shift.
 	return x >> n;
@@ -161,13 +169,13 @@
 }
 
 JAS_ATTRIBUTE_CONST
-JAS_ATTRIBUTE_DISABLE_USAN
+JAS_ATTRIBUTE_DISABLE_UBSAN
 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. */
+	// The behavior is undefined when x is negative.
 	// We tacitly assume the behavior is equivalent to a signed
 	// arithmetic left shift.
 	return x << n;
@@ -174,13 +182,13 @@
 }
 
 JAS_ATTRIBUTE_CONST
-JAS_ATTRIBUTE_DISABLE_USAN
+JAS_ATTRIBUTE_DISABLE_UBSAN
 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. */
+	// The behavior is undefined when x is negative.
 	// We tacitly assume the behavior is equivalent to a signed
 	// arithmetic right shift.
 	return x >> n;
@@ -187,13 +195,13 @@
 }
 
 JAS_ATTRIBUTE_CONST
-JAS_ATTRIBUTE_DISABLE_USAN
+JAS_ATTRIBUTE_DISABLE_UBSAN
 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. */
+	// The behavior is undefined when x is negative.
 	// We tacitly assume the behavior is equivalent to a signed
 	// arithmetic left shift.
 	return x << n;
@@ -210,11 +218,13 @@
 /* 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)
+#if jas_has_builtin(__builtin_mul_overflow) || (defined(__GNUC__) && __GNUC__ > 5)
 	size_t result_buffer;
-	if (!result)
-		result = &result_buffer;
-	return !__builtin_mul_overflow(x, y, result);
+	bool valid = !__builtin_mul_overflow(x, y, &result_buffer);
+	if (valid && result) {
+		*result = result_buffer;
+	}
+	return valid;
 #else
 	/* Check if overflow would occur */
 	if (x && y > SIZE_MAX / x) {
@@ -246,11 +256,13 @@
 /* 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)
+#if jas_has_builtin(__builtin_add_overflow) || (defined(__GNUC__) && __GNUC__ > 5)
 	size_t result_buffer;
-	if (!result)
-		result = &result_buffer;
-	return !__builtin_add_overflow(x, y, result);
+	bool valid = !__builtin_add_overflow(x, y, &result_buffer);
+	if (valid && result) {
+		*result = result_buffer;
+	}
+	return valid;
 #else
 	if (y > SIZE_MAX - x) {
 		return false;
@@ -265,11 +277,13 @@
 /* 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)
+#if jas_has_builtin(__builtin_sub_overflow) || (defined(__GNUC__) && __GNUC__ > 5)
 	size_t result_buffer;
-	if (!result)
-		result = &result_buffer;
-	return !__builtin_sub_overflow(x, y, result);
+	bool valid = !__builtin_sub_overflow(x, y, &result_buffer);
+	if (valid && result) {
+		*result = result_buffer;
+	}
+	return valid;
 #else
 	if (y > x) {
 		return false;
@@ -285,11 +299,13 @@
 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)
+#if jas_has_builtin(__builtin_mul_overflow) || (defined(__GNUC__) && __GNUC__ > 5)
 	int_fast32_t result_buffer;
-	if (!result)
-		result = &result_buffer;
-	return !__builtin_mul_overflow(x, y, result);
+	bool valid = !__builtin_mul_overflow(x, y, &result_buffer);
+	if (valid && result) {
+		*result = result_buffer;
+	}
+	return valid;
 #else
 	if (x > 0) {
 		/* x is positive */
@@ -344,11 +360,13 @@
 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)
+#if jas_has_builtin(__builtin_add_overflow) || (defined(__GNUC__) && __GNUC__ > 5)
 	int_fast32_t result_buffer;
-	if (!result)
-		result = &result_buffer;
-	return !__builtin_add_overflow(x, y, result);
+	bool valid = !__builtin_add_overflow(x, y, &result_buffer);
+	if (valid && result) {
+		*result = result_buffer;
+	}
+	return valid;
 #else
 	if ((y > 0 && x > INT_FAST32_MAX - y) ||
 	  (y < 0 && x < INT_FAST32_MIN - y)) {
@@ -360,6 +378,357 @@
 	return true;
 #endif
 }
+
+#if 0
+/*
+This function is potentially useful but not currently used.
+So, it is commented out.
+*/
+inline static bool jas_safe_uint_mul(unsigned x, unsigned y, unsigned *result)
+{
+	/* Check if overflow would occur */
+	if (x && y > UINT_MAX / x) {
+		/* Overflow would occur. */
+		return false;
+	}
+	if (result) {
+		*result = x * y;
+	}
+	return true;
+}
+#endif
+
+/******************************************************************************\
+* Safe 32-bit unsigned integer arithmetic (i.e., with overflow checking).
+\******************************************************************************/
+
+#define JAS_SAFEUI32_MAX (0xffffffffU)
+
+typedef struct {
+	bool valid;
+	uint_least32_t value;
+} jas_safeui32_t;
+
+JAS_ATTRIBUTE_CONST
+static inline jas_safeui32_t jas_safeui32_from_ulong(unsigned long x)
+{
+	jas_safeui32_t result;
+	result.valid = 1;
+	result.value = JAS_CAST(uint_least32_t, x);
+	return result;
+}
+
+JAS_ATTRIBUTE_PURE
+static inline bool jas_safeui32_to_intfast32(jas_safeui32_t x,
+  int_fast32_t* y)
+{
+	if (x.value <= INT_FAST32_MAX) {
+		*y = x.value;
+		return true;
+	} else {
+		return false;
+	}
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jas_safeui32_t jas_safeui32_add(jas_safeui32_t x,
+  jas_safeui32_t y)
+{
+	jas_safeui32_t result;
+	if (x.valid && y.valid && y.value <= UINT_LEAST32_MAX - x.value) {
+		result.valid = true;
+		result.value = x.value + y.value;
+	} else {
+		result.valid = false;
+		result.value = 0;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safeui32_t jas_safeui32_sub(jas_safeui32_t x, jas_safeui32_t y)
+{
+	jas_safeui32_t result;
+	if (x.valid && y.valid && y.value <= x.value) {
+		result.valid = true;
+		result.value = x.value - y.value;
+	} else {
+		result.valid = false;
+		result.value = 0;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline jas_safeui32_t jas_safeui32_mul(jas_safeui32_t x,
+  jas_safeui32_t y)
+{
+	jas_safeui32_t result;
+	if (!x.valid || !y.valid || (x.value && y.value > UINT_LEAST32_MAX /
+	  x.value)) {
+		result.valid = false;
+		result.value = 0;
+	} else {
+		result.valid = true;
+		result.value = x.value * y.value;
+	}
+	return result;
+}
+
+/******************************************************************************\
+* Safe 64-bit signed integer arithmetic (i.e., with overflow checking).
+\******************************************************************************/
+
+typedef struct {
+	bool valid;
+	int_least64_t value;
+} jas_safei64_t;
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safei64_t jas_safei64_from_intmax(intmax_t x)
+{
+	jas_safei64_t result;
+	result.valid = true;
+	result.value = JAS_CAST(int_least64_t, x);
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safei64_t jas_safei64_add(jas_safei64_t x, jas_safei64_t y)
+{
+	jas_safei64_t result;
+	if (((y.value > 0) && (x.value > (INT_LEAST64_MAX - y.value))) ||
+	  ((y.value < 0) && (x.value < (INT_LEAST64_MIN - y.value)))) {
+		result.value = false;
+		result.value = 0;
+	} else {
+		result.valid = true;
+		result.value = x.value + y.value;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safei64_t jas_safei64_sub(jas_safei64_t x, jas_safei64_t y)
+{
+	jas_safei64_t result;
+	if ((y.value > 0 && x.value < INT_LEAST64_MIN + y.value) ||
+	(y.value < 0 && x.value > INT_LEAST64_MAX + y.value)) {
+		result.valid = false;
+		result.value = 0;
+	} else {
+		result.valid = true;
+		result.value = x.value - y.value;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safei64_t jas_safei64_mul(jas_safei64_t x, jas_safei64_t y)
+{
+	jas_safei64_t result;
+	if (x.value > 0) {  /* x.value is positive */
+		if (y.value > 0) {  /* x.value and y.value are positive */
+			if (x.value > (INT_LEAST64_MAX / y.value)) {
+				goto error;
+			}
+		} else { /* x.value positive, y.value nonpositive */
+			if (y.value < (INT_LEAST64_MIN / x.value)) {
+				goto error;
+			}
+		} /* x.value positive, y.value nonpositive */
+	} else { /* x.value is nonpositive */
+		if (y.value > 0) { /* x.value is nonpositive, y.value is positive */
+			if (x.value < (INT_LEAST64_MIN / y.value)) {
+				goto error;
+			}
+		} else { /* x.value and y.value are nonpositive */
+			if ( (x.value != 0) && (y.value < (INT_LEAST64_MAX / x.value))) {
+				goto error;
+			}
+		} /* End if x.value and y.value are nonpositive */
+	} /* End if x.value is nonpositive */
+	result.valid = true;
+	result.value = x.value * y.value;
+	return result;
+error:
+	result.valid = false;
+	result.value = 0;
+	return result;
+}
+
+#if 0
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safei64_t jas_safei64_div(jas_safei64_t x, jas_safei64_t y)
+{
+	// TODO/FIXME: Not yet implemented.
+	jas_safei64_t result;
+	result.valid = false;
+	result.value = 0;
+	return result;
+}
+#endif
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_i32_t jas_safei64_to_i32(jas_safei64_t x, jas_i32_t invalid_value)
+{
+	jas_i32_t result;
+	if (x.valid && x.value >= JAS_I32_MIN && x.value <= JAS_I32_MAX) {
+		result = JAS_CAST(jas_i32_t, x.value);
+	} else {
+		result = invalid_value;
+	}
+	return result;
+}
+
+/******************************************************************************\
+* Safe 64-bit unsigned integer arithmetic (i.e., with overflow checking).
+\******************************************************************************/
+
+typedef struct {
+	bool valid;
+	uint_least64_t value;
+} jas_safeui64_t;
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safeui64_t jas_safeui64_from_intmax(intmax_t x)
+{
+	jas_safeui64_t result;
+	if (x >= 0) {
+		result.valid = true;
+		result.value = JAS_CAST(uint_least64_t, x);
+	} else {
+		result.valid = false;
+		result.value = 0;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safeui64_t jas_safeui64_add(jas_safeui64_t x, jas_safeui64_t y)
+{
+	jas_safeui64_t result;
+	if (x.valid && y.valid && y.value <= UINT_LEAST64_MAX - x.value) {
+		result.valid = true;
+		result.value = x.value + y.value;
+	} else {
+		result.valid = false;
+		result.value = 0;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safeui64_t jas_safeui64_sub(jas_safeui64_t x, jas_safeui64_t y)
+{
+	jas_safeui64_t result;
+	if (x.valid && y.valid && y.value <= x.value) {
+		result.valid = true;
+		result.value = x.value - y.value;
+	} else {
+		result.valid = false;
+		result.value = 0;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safeui64_t jas_safeui64_mul(jas_safeui64_t x, jas_safeui64_t y)
+{
+	jas_safeui64_t result;
+	if (!x.valid || !y.valid || (x.value && y.value > UINT_LEAST64_MAX /
+	  x.value)) {
+		result.valid = false;
+		result.value = 0;
+	} else {
+		result.valid = true;
+		result.value = x.value * y.value;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safeui64_t jas_safeui64_div(jas_safeui64_t x, jas_safeui64_t y)
+{
+	jas_safeui64_t result;
+	if (x.valid && y.valid && y.value) {
+		result.valid = true;
+		result.value = x.value / y.value;
+	} else {
+		result.valid = false;
+		result.value = 0;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_safeui64_t jas_safeui64_pow2_intmax(intmax_t x)
+{
+	jas_safeui64_t result;
+	if (x >= 0 && x < 64) {
+		result.valid = true;
+		result.value = JAS_CAST(uint_least64_t, 1) << x;
+	} else {
+		result.valid = false;
+		result.value = 0;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+int jas_safeui64_to_int(jas_safeui64_t x, int invalid_value)
+{
+	int result;
+	if (x.valid && x.value <= INT_MAX) {
+		result = JAS_CAST(int, x.value);
+	} else {
+		result = invalid_value;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_ui32_t jas_safeui64_to_ui32(jas_safeui64_t x, jas_ui32_t invalid_value)
+{
+	jas_ui32_t result;
+	if (x.valid && x.value <= JAS_UI32_MAX) {
+		result = JAS_CAST(jas_ui32_t, x.value);
+	} else {
+		result = invalid_value;
+	}
+	return result;
+}
+
+JAS_ATTRIBUTE_CONST
+static inline
+jas_i32_t jas_safeui64_to_i32(jas_safeui64_t x, jas_i32_t invalid_value)
+{
+	jas_i32_t result;
+	if (x.valid && x.value <= JAS_I32_MAX) {
+		result = JAS_CAST(jas_i32_t, x.value);
+	} else {
+		result = invalid_value;
+	}
+	return result;
+}
+
+/******************************************************************************\
+\******************************************************************************/
 
 #ifdef __cplusplus
 }
--- a/jasper/jas_seq.h
+++ b/jasper/jas_seq.h
@@ -77,6 +77,7 @@
 #include <jasper/jas_config.h> /* IWYU pragma: keep */
 
 #include <jasper/jas_types.h>
+#include <jasper/jas_fix.h>
 #include <jasper/jas_math.h>
 
 #ifdef __cplusplus
@@ -83,6 +84,11 @@
 extern "C" {
 #endif
 
+/*!
+ * @addtogroup module_seq
+ * @{
+ */
+
 /******************************************************************************\
 * Constants.
 \******************************************************************************/
@@ -95,29 +101,17 @@
 \******************************************************************************/
 
 /* 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
+typedef jas_fix_t jas_seqent_t;
+#define PRIjas_seqent PRIjas_fix
 
 /* 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
+typedef jas_fix_t jas_matent_t;
 
-#ifdef JAS_ENABLE_32BIT
-typedef int_least32_t jas_matind_t;
-#else
-typedef int_fast32_t jas_matind_t;
-#endif
+typedef jas_fix_t jas_matind_t;
 
-/* Matrix. */
-
+/*!
+@brief Matrix type.
+*/
 typedef struct {
 
 	/* Additional state information. */
@@ -155,7 +149,16 @@
 
 } jas_matrix_t;
 
+/*!
+@struct jas_seq2d_t
+@brief Two-dimensional sequence type.
+*/
 typedef jas_matrix_t jas_seq2d_t;
+
+/*!
+@struct jas_seq_t
+@brief One-dimensional sequence type.
+*/
 typedef jas_matrix_t jas_seq_t;
 
 /******************************************************************************\
@@ -162,7 +165,10 @@
 * Functions/macros for matrix class.
 \******************************************************************************/
 
-/* Get the number of rows. */
+/*!
+@brief
+Get the number of rows in a matrix.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_matrix_numrows(const jas_matrix_t *matrix)
 {
@@ -169,7 +175,9 @@
 	return matrix->numrows_;
 }
 
-/* Get the number of columns. */
+/*!
+@brief Get the number of columns in a matrix.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_matrix_numcols(const jas_matrix_t *matrix)
 {
@@ -176,6 +184,10 @@
 	return matrix->numcols_;
 }
 
+/*!
+@brief
+Get the number of elements in a matrix.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_matrix_size(const jas_matrix_t *matrix)
 {
@@ -182,6 +194,10 @@
 	return jas_matrix_numcols(matrix) * jas_matrix_numrows(matrix);
 }
 
+/*!
+@brief
+Test if a matrix is empty (i.e., contains no elements).
+*/
 JAS_ATTRIBUTE_PURE
 static inline bool jas_matrix_empty(const jas_matrix_t *matrix)
 {
@@ -188,20 +204,31 @@
 	return jas_matrix_numcols(matrix) == 0 || jas_matrix_numrows(matrix) == 0;
 }
 
-/* Get a matrix element. */
+/*!
+@brief
+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)
 {
+	assert(i >= 0 && i < matrix->numrows_ && j >= 0 && j < matrix->numcols_);
 	return matrix->rows_[i][j];
 }
 
-/* Set a matrix element. */
+/*!
+@brief
+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)
 {
+	assert(i >= 0 && i < matrix->numrows_ && j >= 0 && j < matrix->numcols_);
 	matrix->rows_[i][j] = v;
 }
 
-/* Get an element from a matrix that is known to be a row or column vector. */
+/*!
+@brief
+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)
 {
@@ -210,7 +237,10 @@
 		: matrix->rows_[i][0];
 }
 
-/* Set an element in a matrix that is known to be a row or column vector. */
+/*!
+@brief
+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)
@@ -219,7 +249,10 @@
 		matrix->rows_[i][0] = v;
 }
 
-/* Get the address of an element in a matrix. */
+/*!
+@brief
+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)
 {
@@ -226,6 +259,10 @@
 	return &matrix->rows_[i][j];
 }
 
+/*!
+@brief
+Get a reference to a particular row of a 2-D sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_seqent_t *jas_matrix_getvref(const jas_matrix_t *matrix, jas_matind_t i)
 {
@@ -234,50 +271,100 @@
 		: 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);
+/*!
+@brief
+Create a matrix with the specified dimensions.
+*/
+JAS_EXPORT
+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);
+/*!
+@brief
+Destroy a matrix.
+*/
+JAS_EXPORT
+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);
+/*!
+@brief
+Resize a matrix.  The previous contents of the matrix are lost.
+*/
+JAS_EXPORT
+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, int fd);
+/*!
+@brief
+Write a matrix to a C standard library stream.
+*/
+JAS_EXPORT
+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,
+/*!
+@brief
+Create a matrix that references part of another matrix.
+*/
+JAS_EXPORT
+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. */
+/*!
+@brief
+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. */
+/*!
+@brief
+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,
+/*!
+@brief
+Clip the values of matrix elements to the specified range.
+*/
+JAS_EXPORT
+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);
+/*!
+@brief
+Arithmetic shift left of all elements in a matrix.
+*/
+JAS_EXPORT
+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);
+/*!
+@brief
+Arithmetic shift right of all elements in a matrix.
+*/
+JAS_EXPORT
+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);
+/*!
+@brief
+Almost-but-not-quite arithmetic shift right of all elements in a matrix.
+*/
+JAS_EXPORT
+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);
+/*!
+@brief
+Set all elements of a matrix to the specified value.
+*/
+JAS_EXPORT
+void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val);
 
-/* The spacing between rows of a matrix. */
+/*!
+@brief
+The spacing between rows of a matrix.
+*/
 JAS_ATTRIBUTE_PURE
 static inline size_t jas_matrix_rowstep(const jas_matrix_t *matrix)
 {
@@ -286,7 +373,10 @@
 		: 0u;
 }
 
-/* The spacing between columns of a matrix. */
+/*!
+@brief
+The spacing between columns of a matrix.
+*/
 JAS_ATTRIBUTE_PURE
 static inline size_t jas_matrix_step(const jas_matrix_t *matrix)
 {
@@ -295,31 +385,57 @@
 		: 1;
 }
 
-/* Compare two matrices for equality. */
-JAS_DLLEXPORT int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1);
+/*!
+@brief
+Compare two matrices for equality.
+*/
+JAS_EXPORT
+int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1);
 
-JAS_DLLEXPORT jas_matrix_t *jas_matrix_copy(jas_matrix_t *x);
+/*!
+@brief
+Copy a matrix.
+*/
+JAS_EXPORT
+jas_matrix_t *jas_matrix_copy(jas_matrix_t *x);
 
-JAS_DLLEXPORT jas_matrix_t *jas_matrix_input(int);
+/*!
+@brief
+Read a matrix from a C standard library stream.
+*/
+JAS_EXPORT
+jas_matrix_t *jas_matrix_input(FILE *);
 
+/*!
+@brief
+*/
 JAS_ATTRIBUTE_CONST
 static inline jas_seqent_t jas_seqent_asl(jas_seqent_t x, unsigned n)
 {
+#if 0
 #ifdef JAS_ENABLE_32BIT
 	return jas_least32_asl(x, n);
 #else
 	return jas_fast32_asl(x, n);
 #endif
+#endif
+	return jas_fix_asl(x, n);
 }
 
+/*!
+@brief
+*/
 JAS_ATTRIBUTE_CONST
 static inline jas_seqent_t jas_seqent_asr(jas_seqent_t x, unsigned n)
 {
+#if 0
 #ifdef JAS_ENABLE_32BIT
 	return jas_least32_asr(x, n);
 #else
 	return jas_fast32_asr(x, n);
 #endif
+#endif
+	return jas_fix_asr(x, n);
 }
 
 /******************************************************************************\
@@ -326,16 +442,34 @@
 * Functions/macros for 2-D sequence class.
 \******************************************************************************/
 
-JAS_DLLEXPORT jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x);
+/*!
+@brief
+Copy a 2-D sequence.
+*/
+JAS_EXPORT
+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,
+/*!
+@brief
+Create a 2-D sequence.
+*/
+JAS_EXPORT
+jas_matrix_t *jas_seq2d_create(jas_matind_t xstart, jas_matind_t ystart,
   jas_matind_t xend, jas_matind_t yend);
 
+/*!
+@brief
+Destroy a 2-D sequence.
+*/
 static inline void jas_seq2d_destroy(jas_seq2d_t *s)
 {
 	jas_matrix_destroy(s);
 }
 
+/*!
+@brief
+Get the starting x-coordinate of the sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_seq2d_xstart(const jas_seq2d_t *s)
 {
@@ -342,6 +476,10 @@
 	return s->xstart_;
 }
 
+/*!
+@brief
+Get the starting y-coordinate of the sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_seq2d_ystart(const jas_seq2d_t *s)
 {
@@ -348,6 +486,10 @@
 	return s->ystart_;
 }
 
+/*!
+@brief
+Get the ending x-coordinate of the sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_seq2d_xend(const jas_seq2d_t *s)
 {
@@ -354,6 +496,10 @@
 	return s->xend_;
 }
 
+/*!
+@brief
+Get the ending y-coordinate of the sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_seq2d_yend(const jas_seq2d_t *s)
 {
@@ -360,6 +506,10 @@
 	return s->yend_;
 }
 
+/*!
+@brief
+Get a pointer (i.e., reference) to an element of a 2-D sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_seqent_t *jas_seq2d_getref(const jas_seq2d_t *s, jas_matind_t x, jas_matind_t y)
 {
@@ -366,6 +516,10 @@
 	return jas_matrix_getref(s, y - s->ystart_, x - s->xstart_);
 }
 
+/*!
+@brief
+Get an element of a 2-D sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_seqent_t jas_seq2d_get(const jas_seq2d_t *s, jas_matind_t x, jas_matind_t y)
 {
@@ -372,6 +526,10 @@
 	return jas_matrix_get(s, y - s->ystart_, x - s->xstart_);
 }
 
+/*!
+@brief
+Get the stride between successive rows in the sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline size_t jas_seq2d_rowstep(const jas_seq2d_t *s)
 {
@@ -378,6 +536,10 @@
 	return jas_matrix_rowstep(s);
 }
 
+/*!
+@brief
+Get the number of columns in the sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline unsigned jas_seq2d_width(const jas_seq2d_t *s)
 {
@@ -384,6 +546,10 @@
 	return (unsigned)(s->xend_ - s->xstart_);
 }
 
+/*!
+@brief
+Get the number of rows in the sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline unsigned jas_seq2d_height(const jas_seq2d_t *s)
 {
@@ -390,6 +556,10 @@
 	return (unsigned)(s->yend_ - s->ystart_);
 }
 
+/*!
+@brief
+Set the shift (i.e., starting x- and y-coordinates) of the sequence.
+*/
 static inline void jas_seq2d_setshift(jas_seq2d_t *s, jas_matind_t x, jas_matind_t y)
 {
 	s->xstart_ = x;
@@ -398,6 +568,10 @@
 	s->yend_ = s->ystart_ + s->numrows_;
 }
 
+/*!
+@brief
+Get the number of elements in the sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_seq2d_size(const jas_seq2d_t *s)
 {
@@ -404,6 +578,10 @@
 	return jas_seq2d_width(s) * jas_seq2d_height(s);
 }
 
+/*!
+@brief
+Test if the sequence is empty (i.e., contains no elements).
+*/
 JAS_ATTRIBUTE_PURE
 static inline bool jas_seq2d_empty(const jas_seq2d_t *s)
 {
@@ -410,7 +588,12 @@
 	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,
+/*!
+@brief
+Initialize a sequence to reference a subsequence of another sequence.
+*/
+JAS_EXPORT
+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);
 
 /******************************************************************************\
@@ -417,21 +600,37 @@
 * Functions/macros for 1-D sequence class.
 \******************************************************************************/
 
+/*!
+@brief
+Create a 1-D sequence.
+*/
 static inline jas_seq_t *jas_seq_create(jas_matind_t start, jas_matind_t end)
 {
 	return jas_seq2d_create(start, 0, end, 1);
 }
 
+/*!
+@brief
+Destroy a 1-D sequence.
+*/
 static inline void jas_seq_destroy(jas_seq_t *seq)
 {
 	jas_seq2d_destroy(seq);
 }
 
+/*!
+@brief
+Set an element of a sequence.
+*/
 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;
 }
 
+/*!
+@brief
+Get a pointer (i.e., reference) to an element of a sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_seqent_t *jas_seq_getref(const jas_seq_t *seq, jas_matind_t i)
 {
@@ -438,6 +637,10 @@
 	return &seq->rows_[0][i - seq->xstart_];
 }
 
+/*!
+@brief
+Get an element of a sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_seqent_t jas_seq_get(const jas_seq_t *seq, jas_matind_t i)
 {
@@ -444,6 +647,10 @@
 	return seq->rows_[0][i - seq->xstart_];
 }
 
+/*!
+@brief
+Get the starting index of a sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_seq_start(const jas_seq_t *seq)
 {
@@ -450,11 +657,19 @@
 	return seq->xstart_;
 }
 
+/*!
+@brief
+Get the ending index of a sequence.
+*/
 JAS_ATTRIBUTE_PURE
 static inline jas_matind_t jas_seq_end(const jas_seq_t *seq)
 {
 	return seq->xend_;
 }
+
+/*!
+ * @}
+ */
 
 #ifdef __cplusplus
 }
--- a/jasper/jas_stream.h
+++ b/jasper/jas_stream.h
@@ -75,6 +75,10 @@
 
 /* The configuration header file should be included first. */
 #include <jasper/jas_config.h> /* IWYU pragma: export */
+
+#if defined(JAS_HAVE_FCNTL_H)
+#include <fcntl.h>
+#endif
 #include <jasper/jas_types.h>
 
 #ifdef __cplusplus
@@ -82,7 +86,7 @@
 #endif
 
 /*!
- * @addtogroup iostreams
+ * @addtogroup module_iostreams
  * @{
  */
 
@@ -95,8 +99,6 @@
 #define O_BINARY	0
 #endif
 
-#define EOF (-1)
-
 /*
  * Stream open flags.
  */
@@ -176,10 +178,10 @@
 typedef struct {
 
 	/* Read characters from a file object. */
-	int (*read_)(jas_stream_obj_t *obj, char *buf, unsigned cnt);
+	ssize_t (*read_)(jas_stream_obj_t *obj, char *buf, size_t cnt);
 
 	/* Write characters to a file object. */
-	int (*write_)(jas_stream_obj_t *obj, const char *buf, unsigned cnt);
+	ssize_t (*write_)(jas_stream_obj_t *obj, const char *buf, size_t cnt);
 
 	/* Set the position for a file object. */
 	long (*seek_)(jas_stream_obj_t *obj, long offset, int origin);
@@ -189,8 +191,15 @@
 
 } jas_stream_ops_t;
 
-/*
- * Stream object.
+/*!
+@brief
+I/O stream object.
+
+@warning
+Library users should never directly access any of the members of this
+class.
+The functions/macros provided by the JasPer library API should always
+be used.
  */
 
 typedef struct {
@@ -248,6 +257,7 @@
 typedef struct {
 	int fd;
 	int flags;
+	char pathname[L_tmpnam + 1];
 } jas_stream_fileobj_t;
 
 /* Delete underlying file object upon stream close. */
@@ -268,10 +278,10 @@
 	size_t bufsize_;
 
 	/* The length of the file. */
-	uint_fast32_t len_;
+	size_t len_;
 
 	/* The seek position. */
-	uint_fast32_t pos_;
+	size_t pos_;
 
 	/* Is the buffer growable? */
 	int growable_;
@@ -299,7 +309,7 @@
 Upon success, a pointer to the opened stream is returned.
 Otherwise, a null pointer is returned.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 jas_stream_t *jas_stream_fopen(const char *filename, const char *mode);
 
 /*!
@@ -325,26 +335,20 @@
 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);
+JAS_EXPORT
+jas_stream_t *jas_stream_memopen(char *buffer, size_t buffer_size);
 
 /*!
-@warning
-This function will be renamed jas_stream_memopen in a future release.
+@brief
+Do not use.
+@deprecated
 Do not use this function.
+This function is deprecated.
+Use jas_stream_memopen instead.
 */
-JAS_DLLEXPORT
+JAS_DEPRECATED
+JAS_EXPORT
 jas_stream_t *jas_stream_memopen2(char *buffer, size_t buffer_size);
 
 /*!
@@ -361,10 +365,52 @@
 Upon success, a pointer to the opened stream is returned.
 Otherwise, a null pointer is returned.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 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 null-terminated string containing the pathname of the file
+to be reopened.
+@param mode
+A pointer to a null-terminated string containing the mode to be used for
+reopening the file.
+This string is similar to that used by the fdopen function in the
+C standard library.
+@param fp
+A pointer to the `FILE` (i.e., stdio stream) to be reopened.
+
+@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_EXPORT
+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_EXPORT
+jas_stream_t *jas_stream_tmpfile(void);
+
+/*!
 @brief Close a stream.
 
 @param stream
@@ -382,7 +428,7 @@
 If no errors are encountered when closing the stream, 0 is returned.
 Otherwise, a nonzero value is returned.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_stream_close(jas_stream_t *stream);
 
 /******************************************************************************\
@@ -404,6 +450,7 @@
 
 /*!
 @brief Get the error indicator for a stream.
+
 @param stream
 The stream whose error indicator is to be queried.
 @return
@@ -417,6 +464,7 @@
 
 /*!
 @brief Clear the error indicator for a stream.
+
 @param stream
 The stream whose error indicator is to be cleared.
 
@@ -441,6 +489,7 @@
 
 /*!
 @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
@@ -453,7 +502,7 @@
 @return
 The old read/write limit is returned.
 */
-JAS_DLLEXPORT long jas_stream_setrwlimit(jas_stream_t *stream, long rwlimit);
+JAS_EXPORT long jas_stream_setrwlimit(jas_stream_t *stream, long rwlimit);
 
 /*!
 @brief Get the read/write count for a stream.
@@ -470,6 +519,7 @@
 
 /*!
 @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
@@ -480,7 +530,8 @@
 @todo
 TODO/FIXME: Should this macro evaluate to void?
 */
-JAS_DLLEXPORT long jas_stream_setrwcount(jas_stream_t *stream, long rw_count);
+JAS_EXPORT
+long jas_stream_setrwcount(jas_stream_t *stream, long rw_count);
 
 /******************************************************************************\
 * Macros/functions for I/O.
@@ -491,6 +542,13 @@
 /*!
 @brief jas_stream_getc
 Read a character from a stream.
+
+@param stream
+A pointer to the stream from which to read a character.
+
+@returns
+If a character is succesfully read, the character is returned.
+Otherwise, EOF is returned.
 */
 #define	jas_stream_getc(stream)	jas_stream_getc_func(stream)
 #else
@@ -502,6 +560,16 @@
 /*!
 @brief jas_stream_putc
 Write a character to a stream.
+
+@param stream
+A pointer to the stream to which to write the character.
+@param c
+The character to be written.
+
+@returns
+If the character is successfully output, the value of the character is
+returned.
+Otherwise, EOF is returned.
 */
 #define jas_stream_putc(stream, c)	jas_stream_putc_func(stream, c)
 #else
@@ -525,6 +593,9 @@
 The number of characters read can be less than @c count, due to
 end-of-file (EOF) or an I/O error.
 
+(This function is analogous to fread with the two read-count
+parameters combined into a single size.)
+
 @return
 The number of characters read is returned.
 In the case that the number of characters read is less than @c count,
@@ -535,18 +606,16 @@
 <li>a failure due to the read/write limit being exceeded
 <li>EOF.
 </ol>
-TODO/CHECK: can items 1 and 2 be distinguished currently?
+(The functions jas_stream_getrwcount() and jas_stream_getrwlimit()
+can be used to distinguish between failure due to an I/O error
+and failure due to the read/write limit being exceeed.)
 
-@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.
+@todo
+TODO: should jas_stream_error be true if RWLIMIT exceeded?
+or maybe introduce a jas_stream_rwlimit predicate?
 */
-JAS_DLLEXPORT
-unsigned jas_stream_read(jas_stream_t *stream, void *buffer, unsigned count);
+JAS_EXPORT
+size_t jas_stream_read(jas_stream_t *stream, void *buffer, size_t count);
 
 /*!
 @brief Attempt to retrieve one or more pending characters of input
@@ -569,9 +638,11 @@
 or EOF.
 
 @warning
-TODO/FIXME: peeking at EOF should be distinguishable from an I/O error
+TODO/FIXME: peeking at EOF should be distinguishable from an I/O error;
+also should return type be changed to size_t?
+
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 unsigned jas_stream_peek(jas_stream_t *stream, void *buffer, size_t count);
 
 /*!
@@ -590,6 +661,9 @@
 The number of characters written can be less than @c count due to
 an I/O error or the read/write limit being exceeded.
 
+(This function is analogous to fwrite with the two write-count
+parameters combined into a single size.)
+
 @return
 Upon success, the number of characters successfully written is returned.
 If an error occurs, the value returned will be less than @c count.
@@ -599,15 +673,10 @@
 <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);
+JAS_EXPORT
+size_t jas_stream_write(jas_stream_t *stream, const void *buffer,
+  size_t count);
 
 /*!
 @brief Write formatted output to a stream.
@@ -630,7 +699,7 @@
 I think that the return type of int is okay here.
 It is consistent with printf and friends.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 int jas_stream_printf(jas_stream_t *stream, const char *format, ...);
 
 /*!
@@ -644,11 +713,14 @@
 @details
 The null character is not output.
 
+(This function is analogous to fputs for C standard library streams.)
+
 @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);
+JAS_EXPORT
+int jas_stream_puts(jas_stream_t *stream, const char *s);
 
 /*!
 @brief Read a line of input from a stream.
@@ -666,13 +738,15 @@
 Since the buffer may be too small to hold the input,
 this operation can fail due to attempted buffer overrun.
 
+(This function is analogous to fgets for C standard library streams.)
+
 @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);
+JAS_EXPORT
+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
@@ -719,8 +793,8 @@
 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);
+JAS_EXPORT
+int jas_stream_ungetc(jas_stream_t *stream, int c);
 
 /******************************************************************************\
 * Macros/functions for getting/setting the stream position.
@@ -741,7 +815,8 @@
 positive value is returned.
 Otherwise, 0 is returned.
 */
-JAS_ATTRIBUTE_PURE JAS_DLLEXPORT
+JAS_EXPORT
+JAS_ATTRIBUTE_PURE
 int jas_stream_isseekable(jas_stream_t *stream);
 
 /*!
@@ -763,11 +838,12 @@
 Upon success, the new stream position is returned.
 Upon failure, a negative value is returned.
 */
-JAS_DLLEXPORT
+JAS_EXPORT
 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.
 
@@ -774,26 +850,34 @@
 @details
 The current position of the stream is returned.
 
+(This function is analogous to ftell for C standard library streams.)
+
 @return
 Upon success, the current stream position is returned.
 If an error is encountered, a negative value is returned.
 */
-JAS_ATTRIBUTE_PURE JAS_DLLEXPORT
+JAS_EXPORT
 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).
+
+(This function is analogous to frewind for C standard library streams.)
+
 @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);
+JAS_EXPORT
+int jas_stream_rewind(jas_stream_t *stream);
 
 /******************************************************************************\
 * Macros/functions for flushing.
@@ -801,15 +885,21 @@
 
 /*!
 @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.
+
+(This function is analogous to fflush for C standard library streams.)
+
 @return
 Upon success, zero is returned.
 Otherwise, a negative value is returned.
 */
-JAS_DLLEXPORT int jas_stream_flush(jas_stream_t *stream);
+JAS_EXPORT
+int jas_stream_flush(jas_stream_t *stream);
 
 /******************************************************************************\
 * Miscellaneous macros/functions.
@@ -828,16 +918,52 @@
 @details
 The function copies the specified number of characters from the
 source stream to the destination stream.
+In particular, if @c count is nonnegative, @c count characters are
+copied from the source stream @c source to the destination stream
+@c destination.
+Otherwise (i.e., if @c count is negative), the entire source
+stream @c source (i.e., until EOF is reached) is copied to the
+destination stream @c destination.
 
 @return
 Upon success, 0 is returned; otherwise, -1 is returned.
 
 @todo
-TODO/FIXME: count should probably be a size_t; return type ssize_t?
+TODO/FIXME: should return type be ssize_t and the return value be
+the count of the characters copied?
+Perhaps, it might be safer to introduce a new function with differing
+semantics and deprecate this one?
 */
-JAS_DLLEXPORT int jas_stream_copy(jas_stream_t *destination, jas_stream_t *source, int count);
+JAS_EXPORT
+int jas_stream_copy(jas_stream_t *destination, jas_stream_t *source,
+  ssize_t 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_EXPORT
+int jas_stream_display(jas_stream_t *stream, FILE *fp, int count);
+
+/*!
 @brief Consume (i.e., discard) characters from stream.
 
 @param stream
@@ -855,11 +981,9 @@
 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);
+JAS_EXPORT
+ssize_t jas_stream_gobble(jas_stream_t *stream, size_t count);
 
 /*!
 @brief Write a fill character multiple times to a stream.
@@ -881,16 +1005,15 @@
 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);
+JAS_EXPORT
+ssize_t jas_stream_pad(jas_stream_t *stream, size_t count, int value);
 
 /*!
 @brief Get the size of the file associated with the specified stream.
 
 @param stream
+A pointer to the stream.
 
 @details
 This function queries the size (i.e., length) of the underlying file object
@@ -901,10 +1024,11 @@
 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?
+@todo
+Should the return type be long or ssize_t?  long is consistent with the
+type used for seek offsets.
 */
-JAS_ATTRIBUTE_PURE JAS_DLLEXPORT
+JAS_EXPORT
 long jas_stream_length(jas_stream_t *stream);
 
 /******************************************************************************\
@@ -917,10 +1041,10 @@
 /* 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);
+JAS_EXPORT int jas_stream_fillbuf(jas_stream_t *stream, int getflag);
+JAS_EXPORT int jas_stream_flushbuf(jas_stream_t *stream, int c);
+JAS_EXPORT int jas_stream_getc_func(jas_stream_t *stream);
+JAS_EXPORT 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)
--- /dev/null
+++ b/jasper/jas_string.h
@@ -1,0 +1,150 @@
+/*
+ * 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>
+
+#include <jasper/jas_types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * @addtogroup module_string
+ * @{
+ */
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/*!
+@brief
+Create a copy of a null-terminated string.
+
+@details
+This function has a behavior similar to the well-known strdup function.
+*/
+JAS_EXPORT
+char *jas_strdup(const char *);
+
+/*!
+@brief
+Extract tokens from a string.
+
+@details
+This function has a similar behavior as @c strtok_r in the POSIX standard.
+*/
+JAS_EXPORT
+char *jas_strtok(char *str, const char *delim, char **saveptr);
+
+/*!
+@brief
+Split a string into tokens based on specified delimiters.
+
+@param string
+A pointer to a null-terminated string to be split into tokens.
+@param delim
+A pointer to a null-terminated string contained characters used to delimit
+tokens.
+@param tokens_buf
+A pointer to the output token array.
+@param max_tokens_buf
+A pointer to the allocated size of the token array.
+@param num_tokens_buf
+A pointer to the number of elements in the token array.
+
+@details
+The memory to hold token information is allocated via jas_malloc()
+and friends.
+
+@returns
+If successful, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+JAS_EXPORT
+int jas_stringtokenize(const char *string, const char *delim,
+  char ***tokens_buf, size_t *max_tokens_buf, size_t *num_tokens_buf);
+
+/*!
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_thread.h
@@ -1,0 +1,795 @@
+/*
+ * 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_thread.h
+ * @brief Threads
+ */
+
+#ifndef JAS_THREAD_H
+#define JAS_THREAD_H
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#include "jasper/jas_compiler.h"
+#include "jasper/jas_types.h"
+
+#if defined(JAS_THREADS)
+
+#include <stdlib.h>
+#include <assert.h>
+
+#if defined(JAS_THREADS_C11)
+#include <threads.h>
+#include <stdatomic.h>
+#elif defined(JAS_THREADS_PTHREAD)
+#include <pthread.h>
+#include <sched.h>
+#elif defined(JAS_THREADS_WIN32)
+#include <process.h>
+#include <windows.h>
+#include <processthreadsapi.h>
+#endif
+
+#endif
+
+/******************************************************************************\
+\******************************************************************************/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * @cond DOXYGEN_EXCLUDE
+ * @addtogroup module_threads
+ * @{
+ */
+
+#if defined(JAS_THREADS)
+#if defined(JAS_FOR_INTERNAL_USE_ONLY) || defined(JAS_FOR_JASPER_APP_USE_ONLY)
+
+/******************************************************************************\
+* Types
+\******************************************************************************/
+
+#if defined(JAS_THREADS_C11)
+#	define JAS_THREADS_IMPL "C11"
+#	define JAS_USE_SPINLOCK
+#elif defined(JAS_THREADS_PTHREAD)
+#	define JAS_THREADS_IMPL "PTHREAD"
+#	undef JAS_USE_SPINLOCK
+#elif defined(JAS_THREADS_WIN32)
+#	define JAS_THREADS_IMPL "WIN32"
+#	define JAS_USE_SPINLOCK
+#endif
+
+/**************************************\
+* Spinlock
+\**************************************/
+
+/*! Spinlock type. */
+#if defined(JAS_THREADS_C11)
+#	define JAS_USE_SPINLOCK
+typedef struct {
+	atomic_flag flag;
+} jas_spinlock_t;
+#elif defined(JAS_THREADS_PTHREAD)
+/* There is no pthread_spinlock_t type on MacOS. */
+#	undef JAS_USE_SPINLOCK
+#elif defined(JAS_THREADS_WIN32)
+#	define JAS_USE_SPINLOCK
+typedef struct {
+	LONG flag;
+} jas_spinlock_t;
+#endif
+
+/*!  Spinlock initializer. */
+#if defined(JAS_THREADS_C11)
+#define JAS_SPINLOCK_INITIALIZER {ATOMIC_FLAG_INIT}
+#elif defined(JAS_THREADS_PTHREAD)
+/* There is no pthread_spinlock_t type on MacOS. */
+#elif defined(JAS_THREADS_WIN32)
+#define JAS_SPINLOCK_INITIALIZER {0}
+#endif
+
+/**************************************\
+* Basic Mutex
+\**************************************/
+
+/*!  Mutex type. */
+#if defined(JAS_THREADS_C11)
+typedef mtx_t jas_basicmutex_t;
+#elif defined(JAS_THREADS_PTHREAD)
+typedef pthread_mutex_t jas_basicmutex_t;
+#elif defined(JAS_THREADS_WIN32)
+typedef CRITICAL_SECTION jas_basicmutex_t;
+#endif
+
+/*!  Mutex initializer. */
+#if defined(JAS_THREADS_C11)
+#undef JAS_BASICMUTEX_INITIALIZER
+#elif defined(JAS_THREADS_PTHREAD)
+#define JAS_BASICMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
+#elif defined(JAS_THREADS_WIN32)
+#define JAS_BASICMUTEX_INITIALIZER
+#endif
+
+/**************************************\
+* Mutex (Allowing Static Initialization)
+\**************************************/
+
+#if defined(JAS_USE_SPINLOCK)
+#	define jas_mutex_t jas_spinlock_t
+#	define JAS_MUTEX_INITIALIZER JAS_SPINLOCK_INITIALIZER
+#	define jas_mutex_init jas_spinlock_init
+#	define jas_mutex_cleanup jas_spinlock_cleanup
+#	define jas_mutex_lock jas_spinlock_lock
+#	define jas_mutex_unlock jas_spinlock_unlock
+#else
+#	define jas_mutex_t jas_basicmutex_t
+#	define JAS_MUTEX_INITIALIZER JAS_BASICMUTEX_INITIALIZER
+#	define jas_mutex_init jas_basicmutex_init
+#	define jas_mutex_cleanup jas_basicmutex_cleanup
+#	define jas_mutex_lock jas_basicmutex_lock
+#	define jas_mutex_unlock jas_basicmutex_unlock
+#endif
+
+/**************************************\
+* Once Flag
+\**************************************/
+
+/*!  Once-flag type. */
+#if defined(JAS_THREADS_C11)
+typedef once_flag jas_once_flag_t;
+#elif defined(JAS_THREADS_PTHREAD)
+typedef pthread_once_t jas_once_flag_t;
+#elif defined(JAS_THREADS_WIN32)
+typedef struct {
+	volatile LONG status;
+} jas_once_flag_t;
+#endif
+
+/*!  Once-flag initializer. */
+#if defined(JAS_THREADS_C11)
+#	define JAS_ONCE_FLAG_INIT ONCE_FLAG_INIT
+#elif defined(JAS_THREADS_PTHREAD)
+#	define JAS_ONCE_FLAG_INIT PTHREAD_ONCE_INIT
+#elif defined(JAS_THREADS_WIN32)
+#	define JAS_ONCE_FLAG_INIT {0}
+#endif
+
+/**************************************\
+* Threads
+\**************************************/
+
+#if defined(JAS_FOR_INTERNAL_USE_ONLY) || defined(JAS_FOR_JASPER_APP_USE_ONLY)
+
+/*!  Thread ID type. */
+#if defined(JAS_THREADS_C11)
+typedef thrd_t jas_thread_id_t;
+#elif defined(JAS_THREADS_PTHREAD)
+typedef pthread_t jas_thread_id_t;
+#elif defined(JAS_THREADS_WIN32)
+typedef HANDLE jas_thread_id_t;
+#endif
+
+/*!  Thread type. */
+#if defined(JAS_THREADS_C11)
+typedef thrd_t jas_thread_t;
+#elif defined(JAS_THREADS_PTHREAD)
+typedef struct {
+	pthread_t id;
+	int (*func)(void *);
+	void *arg;
+	int result;
+} jas_thread_t;
+#elif defined(JAS_THREADS_WIN32)
+typedef struct {
+	jas_thread_id_t id;
+	int (*func)(void *);
+	void *arg;
+} jas_thread_t;
+#endif
+
+static inline void jas_thread_yield(void);
+
+#endif
+
+/**************************************\
+* Thread-Specific Storage (TSS)
+\**************************************/
+
+/*!  Thread-specific storage type. */
+#if defined(JAS_THREADS_C11)
+typedef tss_t jas_tss_t;
+#elif defined(JAS_THREADS_PTHREAD)
+typedef pthread_key_t jas_tss_t;
+#elif defined(JAS_THREADS_WIN32)
+typedef DWORD jas_tss_t;
+#endif
+
+
+/******************************************************************************\
+* Spinlock
+\******************************************************************************/
+
+#if defined(JAS_USE_SPINLOCK)
+
+/*!
+@brief
+Initialize a spinlock.
+
+@param mtx
+A pointer to the spinlock to be initialized.
+
+@returns
+If the spinlock is successfully initialized, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+static inline int jas_spinlock_init(jas_spinlock_t *mtx)
+{
+	assert(mtx);
+#if defined(JAS_THREADS_C11)
+	atomic_flag_clear(&mtx->flag);
+	return 0;
+#elif defined(JAS_THREADS_PTHREAD)
+	JAS_UNUSED(mtx);
+	abort();
+	return -1;
+#elif defined(JAS_THREADS_WIN32)
+	InterlockedExchange(&mtx->flag, 0);
+	return 0;
+#endif
+}
+
+/*!
+@brief
+Clean up a spinlock mutex.
+
+@param mtx
+A pointer to the spinlock to be cleaned up.
+
+@returns
+If the spinlock is successfully cleaned up, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+static inline int jas_spinlock_cleanup(jas_spinlock_t *mtx)
+{
+	assert(mtx);
+#if defined(JAS_THREADS_C11)
+	JAS_UNUSED(mtx);
+	return 0;
+#elif defined(JAS_THREADS_PTHREAD)
+	JAS_UNUSED(mtx);
+	abort();
+	return -1;
+#elif defined(JAS_THREADS_WIN32)
+	JAS_UNUSED(mtx);
+	return 0;
+#endif
+}
+
+/*!
+@brief
+Acquire a spinlock.
+
+@param mtx
+A pointer to the spinlock to be acquired.
+
+@returns
+If successful, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+static inline int jas_spinlock_lock(jas_spinlock_t *mtx)
+{
+	assert(mtx);
+#if defined(JAS_THREADS_C11)
+	while (atomic_flag_test_and_set(&mtx->flag)) {}
+	return 0;
+#elif defined(JAS_THREADS_PTHREAD)
+	JAS_UNUSED(mtx);
+	abort();
+	return -1;
+#elif defined(JAS_THREADS_WIN32)
+	while (InterlockedCompareExchange(&mtx->flag, 1, 0)) {}
+	return 0;
+#endif
+}
+
+/*!
+@brief
+Release a spinlock.
+
+@param mtx
+A pointer to the spinlock to be released.
+
+@returns
+If the operation is successful, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+static inline int jas_spinlock_unlock(jas_spinlock_t *mtx)
+{
+	assert(mtx);
+#if defined(JAS_THREADS_C11)
+	atomic_flag_clear(&mtx->flag);
+	return 0;
+#elif defined(JAS_THREADS_PTHREAD)
+	JAS_UNUSED(mtx);
+	abort();
+	return -1;
+#elif defined(JAS_THREADS_WIN32)
+	InterlockedExchange(&mtx->flag, 0);
+	return 0;
+#endif
+}
+
+#endif
+
+/******************************************************************************\
+* Basic Mutex
+\******************************************************************************/
+
+/* For internal use only. */
+static inline int jas_basicmutex_init(jas_basicmutex_t *mtx)
+{
+	assert(mtx);
+#if defined(JAS_THREADS_C11)
+	return mtx_init(mtx, mtx_plain) == thrd_success ? 0 : -1;
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_mutex_init(mtx, 0);
+#elif defined(JAS_THREADS_WIN32)
+	InitializeCriticalSection(mtx);
+	return 0;
+#endif
+}
+
+/* For internal use only. */
+static inline int jas_basicmutex_cleanup(jas_basicmutex_t *mtx)
+{
+	assert(mtx);
+#if defined(JAS_THREADS_C11)
+	mtx_destroy(mtx);
+	return 0;
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_mutex_destroy(mtx);
+#elif defined(JAS_THREADS_WIN32)
+	DeleteCriticalSection(mtx);
+	return 0;
+#endif
+}
+
+/* For internal use only. */
+static inline int jas_basicmutex_lock(jas_basicmutex_t *mtx)
+{
+	assert(mtx);
+#if defined(JAS_THREADS_C11)
+	return mtx_lock(mtx);
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_mutex_lock(mtx);
+#elif defined(JAS_THREADS_WIN32)
+	EnterCriticalSection(mtx);
+	return 0;
+#endif
+}
+
+/* For internal use only. */
+static inline int jas_basicmutex_unlock(jas_basicmutex_t *mtx)
+{
+	assert(mtx);
+#if defined(JAS_THREADS_C11)
+	return mtx_unlock(mtx);
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_mutex_unlock(mtx);
+#elif defined(JAS_THREADS_WIN32)
+	LeaveCriticalSection(mtx);
+	return 0;
+#endif
+}
+
+/******************************************************************************\
+* Thread-Specific Storage (TSS)
+\******************************************************************************/
+
+/*!
+@brief
+Create thread-specific storage.
+
+@param tss
+A pointer to the TSS object to be initialized.
+@param destructor
+A function to be called when the TSS is deallocated when the thread exits.
+
+@returns
+If the operation is successful, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+static inline
+int jas_tss_create(jas_tss_t *tss, void (*destructor)(void *))
+{
+	assert(tss);
+#if defined(JAS_THREADS_C11)
+	return tss_create(tss, destructor) == thrd_success ? 0 : -1;
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_key_create(tss, destructor);
+#elif defined(JAS_THREADS_WIN32)
+	if (destructor) {
+		return -1;
+	}
+	DWORD id;
+	if ((id = TlsAlloc()) == TLS_OUT_OF_INDEXES) {
+		return -2;
+	}
+	*tss = id;
+	return 0;
+#endif
+}
+
+/*!
+@brief Delete thread-specific storage.
+
+@param tss
+The TSS to be destroyed.
+
+@returns
+If the operation is successful, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+static inline
+void jas_tss_delete(jas_tss_t tss)
+{
+#if defined(JAS_THREADS_C11)
+	tss_delete(tss);
+#elif defined(JAS_THREADS_PTHREAD)
+	pthread_key_delete(tss);
+#elif defined(JAS_THREADS_WIN32)
+	TlsFree(tss);
+#endif
+}
+
+/*!
+@brief Get the thread-specific storage instance for the calling thread.
+
+@param tss
+The TSS to be queried.
+
+@returns
+A pointer to the TSS is returned.
+*/
+static inline
+void *jas_tss_get(jas_tss_t tss)
+{
+#if defined(JAS_THREADS_C11)
+	return tss_get(tss);
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_getspecific(tss);
+#elif defined(JAS_THREADS_WIN32)
+	return TlsGetValue(tss);
+#endif
+}
+
+/*!
+@brief Set the thread-specific storage instance for the calling thread.
+
+@param tss
+The TSS object.
+
+@returns
+If the operation is successful, zero is returned.
+Otherwise, a nonzero value is returned.
+*/
+static inline
+int jas_tss_set(jas_tss_t tss, void *value)
+{
+#if defined(JAS_THREADS_C11)
+	return tss_set(tss, value) == thrd_success ? 0 : -1;
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_setspecific(tss, value);
+#elif defined(JAS_THREADS_WIN32)
+	return TlsSetValue(tss, value) ? 0 : -1;
+#endif
+}
+
+/******************************************************************************\
+* Once Flag
+\******************************************************************************/
+
+/*!
+@brief Register to call a function once.
+
+@param flag
+A pointer to a flag to track whether the function has been called yet.
+@param func
+A pointer to the function to be called.
+
+@returns
+*/
+static inline int jas_call_once(jas_once_flag_t *flag, void (*func)(void))
+{
+	assert(flag);
+	assert(func);
+#if defined(JAS_THREADS_C11)
+	call_once(flag, func);
+	return 0;
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_once(flag, func);
+#elif defined(JAS_THREADS_WIN32)
+	if (InterlockedCompareExchange(&flag->status, 1, 0) == 0) {
+		(func)();
+		InterlockedExchange(&flag->status, 2);
+	} else {
+		while (flag->status == 1) {
+			/* Perform a busy wait.  This is ugly. */
+			/* Yield processor. */
+			SwitchToThread();
+		}
+	}
+	return 0;
+#endif
+}
+
+/******************************************************************************\
+* Threads
+\******************************************************************************/
+
+#if defined(JAS_FOR_INTERNAL_USE_ONLY) || defined(JAS_FOR_JASPER_APP_USE_ONLY)
+
+#if defined(JAS_THREADS_PTHREAD)
+static void *thread_func_wrapper(void *thread_ptr)
+{
+	jas_thread_t *thread = JAS_CAST(jas_thread_t *, thread_ptr);
+	int result = (thread->func)(thread->arg);
+	thread->result = result;
+	return thread;
+}
+#elif defined(JAS_THREADS_WIN32)
+static unsigned __stdcall thread_func_wrapper(void *thread_ptr)
+{
+	jas_thread_t *thread = JAS_CAST(jas_thread_t *, thread_ptr);
+	int result = (thread->func)(thread->arg);
+	return JAS_CAST(unsigned, result);
+}
+#endif
+
+/*!
+@brief Compare two thread IDs.
+
+@warning
+This function is only for internal use by the JasPer software.
+This function may be changed/removed without any notice in future versions
+of JasPer.
+*/
+static inline
+int jas_thread_compare(jas_thread_id_t x, jas_thread_id_t y)
+{
+#if defined(JAS_THREADS_C11)
+	return thrd_equal(x, y);
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_equal(x, y);
+#elif defined(JAS_THREADS_WIN32)
+	return GetThreadId(x) == GetThreadId(y);
+#endif
+}
+
+/*!
+@brief Create a thread.
+
+@warning
+This function is only for internal use by the JasPer software.
+This function may be changed/removed without any notice in future versions
+of JasPer.
+*/
+static inline
+int jas_thread_create(jas_thread_t *thread, int (*func)(void *), void *arg)
+{
+	assert(thread);
+	assert(func);
+#if defined(JAS_THREADS_C11)
+	return thrd_create(thread, func, arg) == thrd_success ? 0 : -1;
+#elif defined(JAS_THREADS_PTHREAD)
+	thread->func = func;
+	thread->arg = arg;
+	thread->result = 0;
+	return pthread_create(&thread->id, 0, thread_func_wrapper, thread);
+#elif defined(JAS_THREADS_WIN32)
+	uintptr_t handle;
+	thread->func = func;
+	thread->arg = arg;
+	if (!(handle = _beginthreadex(0, 0, thread_func_wrapper, thread, 0, 0))) {
+		return -1;
+	}
+	thread->id = JAS_CAST(jas_thread_id_t, handle);
+	return 0;
+#endif
+}
+
+/*!
+@brief Join a thread.
+
+@warning
+This function is only for internal use by the JasPer software.
+This function may be changed/removed without any notice in future versions
+of JasPer.
+*/
+static inline
+int jas_thread_join(jas_thread_t *thread, int *result)
+{
+	assert(thread);
+#if defined(JAS_THREADS_C11)
+	return thrd_join(*thread, result) == thrd_success ? 0 : -1;
+#elif defined(JAS_THREADS_PTHREAD)
+	void *result_buf;
+	int ret = pthread_join(thread->id, &result_buf);
+	if (!ret) {
+		jas_thread_t *other_thread = JAS_CAST(jas_thread_t *, result_buf);
+		if (result) {
+			/* A null pointer is probably a bug. */
+			assert(other_thread);
+			*result = other_thread ? other_thread->result : 0;
+		}
+	}
+	return ret;
+#elif defined(JAS_THREADS_WIN32)
+	DWORD w;
+	DWORD code;
+	if ((w = WaitForSingleObject(thread->id, INFINITE)) != WAIT_OBJECT_0) {
+		return -1;
+	}
+	if (result) {
+		if (!GetExitCodeThread(thread->id, &code)) {
+			CloseHandle(thread->id);
+			return -1;
+		}
+		*result = JAS_CAST(int, code);
+	}
+	CloseHandle(thread->id);
+	return 0;
+#endif
+}
+
+/*!
+@brief
+Yield the processor.
+
+@warning
+This function is only for internal use by the JasPer software.
+This function may be changed/removed without any notice in future versions
+of JasPer.
+*/
+
+static inline void jas_thread_yield(void)
+{
+#if defined(JAS_THREADS_C11)
+	thrd_yield();
+#elif defined(JAS_THREADS_PTHREAD)
+	sched_yield();
+#elif defined(JAS_THREADS_WIN32)
+	SwitchToThread();
+#endif
+}
+
+#if 0
+/* This functionality is not available for all threading support libraries. */
+static inline
+void jas_thread_exit(int result)
+{
+#if defined(JAS_THREADS_C11)
+	thrd_exit(result);
+#elif defined(JAS_THREADS_PTHREAD)
+	/* This does not have a trivial implementation, as far as I can see. */
+	/* There is no jas_thread_find function. */
+	jas_thread_t *thread = jas_thread_find(pthread_self());
+	thread->result = result;
+	pthread_exit(JAS_CAST(void *, thread));
+#endif
+}
+#endif
+
+#if 0
+/*!
+@brief Get the ID of the calling thread.
+*/
+static inline
+jas_thread_id_t jas_thread_current(void)
+{
+#if defined(JAS_THREADS_C11)
+	return thrd_current();
+#elif defined(JAS_THREADS_PTHREAD)
+	return pthread_self();
+#elif defined(JAS_THREADS_WIN32)
+	/* FIXME - NOT YET IMPLEMENTED. */
+	abort();
+#endif
+}
+#endif
+
+#endif
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#endif
+#else
+
+/******************************************************************************\
+* No Threading Support.
+\******************************************************************************/
+
+#endif
+
+/*!
+ * @}
+ * @endcond
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/jasper/jas_tvp.h
@@ -1,0 +1,200 @@
+/*
+ * 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_tvp.h
+ * @brief Tag/Value Pair Parser
+ */
+
+#ifndef JAS_TVP_H
+#define JAS_TVP_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * @addtogroup module_tvp
+ * @{
+ */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/*!
+@brief
+Tag information type.
+*/
+typedef struct {
+
+	int id;
+	/* The ID for the tag. */
+
+	const char *name;
+	/* The name of the tag. */
+
+} jas_taginfo_t;
+
+/*!
+@brief
+Tag-value parser type.
+*/
+typedef struct {
+
+	char *buf;
+	/* The parsing buffer. */
+
+	char *tag;
+	/* The current tag name. */
+
+	const char *val;
+	/* The current value. */
+
+	char *pos;
+	/* The current position in the parsing buffer. */
+
+} jas_tvparser_t;
+
+/******************************************************************************\
+* Tag information functions.
+\******************************************************************************/
+
+/*!
+@brief
+Lookup a tag by name.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_EXPORT
+const jas_taginfo_t *jas_taginfos_lookup(const jas_taginfo_t *taginfos,
+  const char *name);
+
+/*!
+@brief
+Ensure a nonnull taginfo pointer.
+
+@details
+This function returns a pointer to the specified taginfo object if it
+  exists (i.e., the pointer is nonnull); otherwise, a pointer to a dummy
+  object is returned.  This is useful in some situations to avoid checking
+  for a null pointer.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_EXPORT
+const jas_taginfo_t *jas_taginfo_nonull(const jas_taginfo_t *taginfo);
+
+/******************************************************************************\
+* Tag-value parser functions.
+\******************************************************************************/
+
+/*!
+@brief
+Create a tag-value parser for the specified string.
+*/
+JAS_EXPORT
+jas_tvparser_t *jas_tvparser_create(const char *s);
+
+/*!
+@brief
+Destroy a tag-value parser.
+*/
+JAS_EXPORT
+void jas_tvparser_destroy(jas_tvparser_t *tvparser);
+
+/*!
+@brief
+Get the next tag-value pair.
+*/
+JAS_EXPORT
+int jas_tvparser_next(jas_tvparser_t *tvparser);
+
+/*!
+@brief
+Get the tag name for the current tag-value pair.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_EXPORT
+const char *jas_tvparser_gettag(const jas_tvparser_t *tvparser);
+
+/*!
+@brief
+Get the value for the current tag-value pair.
+*/
+JAS_ATTRIBUTE_PURE
+JAS_EXPORT
+const char *jas_tvparser_getval(const jas_tvparser_t *tvparser);
+
+/*!
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- a/jasper/jas_types.h
+++ b/jasper/jas_types.h
@@ -72,47 +72,71 @@
 /* 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
+#if defined(JAS_HAVE_SYS_TYPES_H)
+#include <sys/types.h> /* IWYU pragma: export */
+#endif
 
-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;
+#ifdef __cplusplus
+extern "C" {
+#endif
 
-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;
+#define jas_uchar unsigned char
+#define jas_uint unsigned int
+#define jas_ulong unsigned long
+#define jas_longlong long long
+#define jas_ulonglong unsigned long long
 
-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;
+#if !defined(JAS_NO_SET_SSIZE_T)
+#	if !defined(SSIZE_MAX)
+#		if (JAS_SIZEOF_INT == JAS_SIZEOF_SIZE_T)
+#			define ssize_t int
+#			define SSIZE_MAX INT_MAX
+#		elif (JAS_SIZEOF_LONG == JAS_SIZEOF_SIZE_T)
+#			define ssize_t long
+#			define SSIZE_MAX LONG_MAX
+#		else
+#			define ssize_t jas_longlong
+#			define SSIZE_MAX LLONG_MAX
+#		endif
+#	endif
+#endif
 
-typedef enum { false, true } bool;
+#if 0
+#if defined(JAS_HAVE_SSIZE_T)
+#define jas_ssize_t ssize_t
+#define JAS_SSIZE_MAX SSIZE_MAX
+#else
+#define jas_ssize_t jas_longlong
+#define JAS_SSIZE_MAX LLONG_MAX
+#endif
+#endif
 
+#if defined(_MSC_VER) && (_MSC_VER < 1800)
+#define bool  int
+#define false 0
+#define true  1
+
 #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
+#ifdef _WIN64
+    #define PRIdPTR "lld"
+#else
+    #define PRIdPTR "d"
+#endif
+
+#ifndef _HUGE_ENUF
+    #define _HUGE_ENUF 1e+300
+#endif
+
 #define INFINITY ((float)(_HUGE_ENUF * _HUGE_ENUF))
 
+#define strtoull _strtoui64
+
+#endif
+
 /* 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". */
@@ -123,9 +147,59 @@
 /* NOTE: This could underestimate the size on some exotic architectures. */
 #define JAS_UINTFAST32_NUMBITS (8 * sizeof(uint_fast32_t))
 
-#ifdef __cplusplus
-extern "C" {
+#if 0
+#if defined(JAS_HAVE_MAX_ALIGN_T)
+#define	jas_max_align_t	max_align_t
+#else
+#define	jas_max_align_t	long double
 #endif
+#endif
+
+/*
+Assume that a compiler claiming to be compliant with C11 or a later version
+of the C standard provides a suitable definition of max_align_t.
+The JAS_NO_SET_MAX_ALIGN_T preprocessor symbol can be used to override
+this behavior.
+*/
+#if defined(JAS_NO_SET_MAX_ALIGN_T)
+	/*
+	The user of this header is assuming responsibility for providing a
+	suitable definition for max_align_t.
+	*/
+#elif defined(_MSC_VER)
+	/*
+	Define max_align_t as a preprocessor symbol since using typedef will
+	cause problems.
+	*/
+#	define max_align_t long double
+#elif !(defined(__STDC_VERSION__) && (__STDC_VERSION__ - 0 >= 201112L))
+#	define max_align_t long double
+#endif
+
+#if 0
+#if defined(JAS_HAVE_UINTMAX_T)
+#define jas_uintmax_t uintmax_t
+#else
+#define jas_uintmax_t uint_fast64_t
+#endif
+#endif
+
+#if 0
+#if defined(JAS_HAVE_INTMAX_T)
+#define jas_intmax_t intmax_t
+#else
+#define jas_intmax_t int_fast64_t
+#endif
+#endif
+
+/* 32-bit unsigned integer type */
+typedef uint_least32_t jas_ui32_t;
+#define JAS_UI32_MAX UINT_LEAST32_MAX
+
+/* 32-bit signed integer type */
+typedef int_least32_t jas_i32_t;
+#define JAS_I32_MIN INT_LEAST32_MIN
+#define JAS_I32_MAX INT_LEAST32_MAX
 
 #ifdef __cplusplus
 }
--- /dev/null
+++ b/jasper/jas_version.h
@@ -1,0 +1,113 @@
+/*
+ * 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_version.h
+ * @brief JasPer Version
+ */
+
+#ifndef JAS_VERSION_H
+#define JAS_VERSION_H
+
+/* The configuration header file should be included first. */
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Constants and types.
+\******************************************************************************/
+
+#define	JAS_COPYRIGHT \
+	"Copyright (c) 2001-2022 Michael David Adams.\n" \
+	"Copyright (c) 1999-2000 Image Power, Inc. and the University of\n" \
+	"  British Columbia.\n" \
+	"All rights reserved.\n"
+
+#define	JAS_NOTES \
+	"For information about the JasPer project, see:\n" \
+	"    https://jasper-software.github.io/jasper\n" \
+	"    https://www.ece.uvic.ca/~mdadams/jasper\n" \
+	"For online documentation on the JasPer software, see:\n" \
+	"    https://jasper-software.github.io/jasper-manual\n" \
+	"Please submit bug reports using the bug-tracker at:\n" \
+	"    https://github.com/jasper-software/jasper/issues\n"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+JAS_ATTRIBUTE_CONST
+JAS_EXPORT
+const char *jas_getversion(void);
+/* Get the version information for the JasPer library. */
+/* Note:  Since libjasper can be built as a shared library, the version
+  returned by this function may not necessarily correspond to JAS_VERSION. */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- a/jasper/jasper.h
+++ b/jasper/jasper.h
@@ -73,6 +73,7 @@
 #include <jasper/jas_config.h>
 
 #include <jasper/jas_types.h>
+#include <jasper/jas_version.h>
 
 #include <jasper/jas_init.h>
 #include <jasper/jas_cm.h>
@@ -84,6 +85,11 @@
 #include <jasper/jas_malloc.h>
 #include <jasper/jas_seq.h>
 #include <jasper/jas_stream.h>
+#include <jasper/jas_string.h>
+#include <jasper/jas_tvp.h>
+#include <jasper/jas_thread.h>
+#include <jasper/jas_init.h>
+#include <jasper/jas_log.h>
 
 #pragma lib "./libjp2.a"
 
--- a/jp2.c
+++ b/jp2.c
@@ -34,7 +34,10 @@
 		usage();
 
 	memimageinit();
-	jas_init();
+	jas_conf_clear();
+	jas_conf_set_max_mem_usage(512*1024*1024);
+	jas_init_library();
+	jas_init_thread();
 
 	if((cp = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)) == nil){
 		werrstr("failed to create color space");
--- a/jp2_cod.c
+++ b/jp2_cod.c
@@ -75,13 +75,12 @@
 
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_debug.h"
+#include "jasper/jas_types.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);
@@ -95,6 +94,8 @@
 
 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);
+
 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);
@@ -106,46 +107,78 @@
 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);
 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);
 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);
 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);
 
 /******************************************************************************\
+\******************************************************************************/
+
+static inline uint_fast32_t ones(int n)
+{
+	assert(n >= 0);
+	return (JAS_CAST(uint_fast32_t, 1) << n) - 1;
+}
+
+/******************************************************************************\
 * Local data.
 \******************************************************************************/
 
 static const jp2_boxinfo_t jp2_boxinfos[] = {
-	{JP2_BOX_JP, 0, "JP", {0, 0, jp2_jp_getdata, jp2_jp_putdata}},
-	{JP2_BOX_FTYP, 0, "FTYP", {0, 0, jp2_ftyp_getdata, jp2_ftyp_putdata}},
-	{JP2_BOX_JP2H, JP2_BOX_SUPER, "JP2H", {0, 0, 0, 0}},
-	{JP2_BOX_IHDR, 0, "IHDR", {0, 0, jp2_ihdr_getdata, jp2_ihdr_putdata}},
-	{JP2_BOX_BPCC, 0, "BPCC", {0, jp2_bpcc_destroy, jp2_bpcc_getdata, jp2_bpcc_putdata}},
-	{JP2_BOX_COLR, 0, "COLR", {0, jp2_colr_destroy, jp2_colr_getdata, jp2_colr_putdata}},
-	{JP2_BOX_PCLR, 0, "PCLR", {0, jp2_pclr_destroy, jp2_pclr_getdata, jp2_pclr_putdata}},
-	{JP2_BOX_CMAP, 0, "CMAP", {0, jp2_cmap_destroy, jp2_cmap_getdata, jp2_cmap_putdata}},
-	{JP2_BOX_CDEF, 0, "CDEF", {0, jp2_cdef_destroy, jp2_cdef_getdata, jp2_cdef_putdata}},
-	{JP2_BOX_RES, JP2_BOX_SUPER, "RES", {0, 0, 0, 0}},
-	{JP2_BOX_RESC, 0, "RESC", {0, 0, 0, 0}},
-	{JP2_BOX_RESD, 0, "RESD", {0, 0, 0, 0}},
-	{JP2_BOX_JP2C, JP2_BOX_NODATA, "JP2C", {0, 0, 0, 0}},
-	{JP2_BOX_JP2I, 0, "JP2I", {0, 0, 0, 0}},
-	{JP2_BOX_XML, 0, "XML", {0, 0, 0, 0}},
-	{JP2_BOX_UUID, 0, "UUID", {0, 0, 0, 0}},
-	{JP2_BOX_UINF, JP2_BOX_SUPER, "UINF", {0, 0, 0, 0}},
-	{JP2_BOX_ULST, 0, "ULST", {0, 0, 0, 0}},
-	{JP2_BOX_URL, 0, "URL", {0, 0, 0, 0}},
-	{0, 0, 0, {0, 0, 0, 0}},
+	{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, 0, "Unknown", {0, 0, 0, 0, 0}
 };
 
 /******************************************************************************\
@@ -239,19 +272,19 @@
 	boxinfo = jp2_boxinfolookup(box->type);
 	box->info = boxinfo;
 	box->len = len;
-	JAS_DBGLOG(10, (
+	JAS_LOGDEBUGF(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"));
+		JAS_LOGDEBUGF(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");
+			jas_logerrorf("cannot handle large 64-bit box length\n");
 			goto error;
 		}
 		box->len = extlen;
@@ -262,10 +295,9 @@
 	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 */
+	if (box->len > SSIZE_MAX) {
+		/* This limit is the largest value which can be passed to
+		  jas_stream_copy() without overflowing. */
 		goto error;
 	}
 
@@ -280,7 +312,7 @@
 			goto error;
 		}
 		if (jas_stream_copy(tmpstream, in, box->datalen)) {
-			jas_eprintf("cannot copy box data\n");
+			jas_logerrorf("cannot copy box data\n");
 			goto error;
 		}
 		jas_stream_rewind(tmpstream);
@@ -291,7 +323,7 @@
 
 		if (box->ops->getdata) {
 			if ((*box->ops->getdata)(box, tmpstream)) {
-				jas_eprintf("cannot parse box data\n");
+				jas_logerrorf("cannot parse box data\n");
 				goto error;
 			}
 		}
@@ -298,6 +330,10 @@
 		jas_stream_close(tmpstream);
 	}
 
+	if (jas_get_debug_level() >= 1) {
+		jp2_box_dump(box);
+	}
+
 	return box;
 
 error:
@@ -310,6 +346,19 @@
 	return 0;
 }
 
+static void jp2_box_dump(const jp2_box_t *box)
+{
+	const jp2_boxinfo_t *boxinfo = box->info;
+	assert(boxinfo);
+
+	jas_logprintf(
+	  "JP2 box: type=%c%s%c (0x%08"PRIxFAST32"); length=%"PRIuFAST32"\n", '"',
+	  boxinfo->name, '"', box->type, box->len);
+	if (box->ops->dumpdata) {
+		(*box->ops->dumpdata)(box);
+	}
+}
+
 static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in)
 {
 	jp2_jp_t *jp = &box->data.jp;
@@ -376,6 +425,20 @@
 	return 0;
 }
 
+static void jp2_colr_dumpdata(const jp2_box_t *box)
+{
+	const jp2_colr_t *colr = &box->data.colr;
+	jas_logprintf("method=%d; pri=%d; approx=%d\n", (int)colr->method, (int)colr->pri, (int)colr->approx);
+	switch (colr->method) {
+	case JP2_COLR_ENUM:
+		jas_logprintf("csid=%d\n", (int)colr->csid);
+		break;
+	case JP2_COLR_ICC:
+		jas_logmemdump(colr->iccp, colr->iccplen);
+		break;
+	}
+}
+
 static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in)
 {
 	if (box->datalen < 3)
@@ -388,17 +451,25 @@
 
 	if (jp2_getuint8(in, &colr->method) || jp2_getuint8(in, &colr->pri) ||
 	  jp2_getuint8(in, &colr->approx)) {
+		jas_logerrorf("cannot get COLR box data\n");
 		return -1;
 	}
 	switch (colr->method) {
 	case JP2_COLR_ENUM:
 		if (jp2_getuint32(in, &colr->csid)) {
+			jas_logerrorf("cannot get CSID\n");
 			return -1;
 		}
 		break;
 	case JP2_COLR_ICC:
+		if (box->datalen <= 3) {
+			jas_logerrorf("empty ICC profile data\n");
+			return -1;
+		}
+		assert(box->datalen >= 3);
 		colr->iccplen = box->datalen - 3;
-		if (colr->iccplen > 1024 * 1024)
+#if 0
+		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
@@ -405,6 +476,8 @@
 			   very pessimistic and should be lowered
 			   further) */
 			return -1;
+		}
+#endif
 		if (!(colr->iccp = jas_alloc2(colr->iccplen, sizeof(uint_fast8_t)))) {
 			return -1;
 		}
@@ -416,6 +489,17 @@
 	return 0;
 }
 
+static void jp2_cdef_dumpdata(const jp2_box_t *box)
+{
+	const jp2_cdef_t *cdef = &box->data.cdef;
+	unsigned int i;
+	for (i = 0; i < cdef->numchans; ++i) {
+		jas_logprintf(
+		  "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;
@@ -472,7 +556,7 @@
 		box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
 		jas_stream_rewind(tmpstream);
 	}
-	extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
+	extlen = 0;
 	if (jp2_putuint32(out, extlen ? 1 : box->len)) {
 		goto error;
 	}
@@ -488,7 +572,7 @@
 	if (dataflag) {
 		if (jas_stream_copy(out, tmpstream, box->len -
 		  JP2_BOX_HDRLEN(false))) {
-			jas_eprintf("cannot copy box data\n");
+			jas_logerrorf("cannot copy box data\n");
 			goto error;
 		}
 		jas_stream_close(tmpstream);
@@ -703,10 +787,6 @@
 	return &jp2_boxinfo_unk;
 }
 
-
-
-
-
 static void jp2_cmap_destroy(jp2_box_t *box)
 {
 	jp2_cmap_t *cmap = &box->data.cmap;
@@ -746,13 +826,23 @@
 
 static int jp2_cmap_putdata(const jp2_box_t *box, jas_stream_t *out)
 {
-	/* Eliminate compiler warning about unused variables. */
-	USED(box);
-	USED(out);
-
+	JAS_UNUSED(box);
+	JAS_UNUSED(out);
 	return -1;
 }
 
+static void jp2_cmap_dumpdata(const jp2_box_t *box)
+{
+	const jp2_cmap_t *cmap = &box->data.cmap;
+	unsigned int i;
+	jas_logprintf("numchans = %d\n", (int) cmap->numchans);
+	for (i = 0; i < cmap->numchans; ++i) {
+		const jp2_cmapent_t *ent = &cmap->ents[i];
+		jas_logprintf("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;
@@ -813,12 +903,26 @@
 #if 0
 	const jp2_pclr_t *pclr = &box->data.pclr;
 #endif
-	/* Eliminate warning about unused variable. */
-	USED(box);
-	USED(out);
+	JAS_UNUSED(box);
+	JAS_UNUSED(out);
 	return -1;
 }
 
+static void jp2_pclr_dumpdata(const jp2_box_t *box)
+{
+	const jp2_pclr_t *pclr = &box->data.pclr;
+	unsigned int i;
+	int j;
+	jas_logprintf("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) {
+			jas_logprintf("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;
@@ -828,6 +932,12 @@
 
 	m = (n + 7) / 8;
 
+	// Ensure that the integer to be read has a valid size.
+	if (n < 0 || n > 32) {
+		jas_logerrorf("jp2_getint: invalid integer size (%d bits)\n", n);
+		return -1;
+	}
+
 	v = 0;
 	for (i = 0; i < m; ++i) {
 		if ((c = jas_stream_getc(in)) == EOF) {
@@ -835,11 +945,11 @@
 		}
 		v = (v << 8) | c;
 	}
-	v &= ONES(n);
+	v &= ones(n);
 	if (s) {
 		int sb;
-		sb = v & (1 << (8 * m - 1));
-		*val = ((~v) + 1) & ONES(8 * m);
+		sb = v & (JAS_CAST(uint_fast32_t, 1) << (8 * m - 1));
+		*val = ((~v) + 1) & ones(8 * m);
 		if (sb) {
 			*val = -*val;
 		}
--- a/jp2_cod.h
+++ b/jp2_cod.h
@@ -245,7 +245,7 @@
 	uint_fast32_t type;
 
 	/* The length of the box including the (variable-length) header. */
-	uint_fast64_t len;
+	uint_fast32_t len;
 
 	/* The length of the box data. */
 	uint_fast32_t datalen;
@@ -268,6 +268,7 @@
 	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);
 } jp2_boxops_t;
 
 /******************************************************************************\
@@ -307,6 +308,5 @@
 #define ICC_CS_GRAY	0x47524159
 
 const jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo);
-
 
 #endif
--- a/jp2_dec.c
+++ b/jp2_dec.c
@@ -81,7 +81,9 @@
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_types.h"
 
-#define	JP2_VALIDATELEN	(JAS_MIN(JP2_JP_LEN + 16, JAS_STREAM_MAXPUTBACK))
+/******************************************************************************\
+* Function prototypes.
+\******************************************************************************/
 
 static jp2_dec_t *jp2_dec_create(void);
 static void jp2_dec_destroy(jp2_dec_t *dec);
@@ -104,7 +106,10 @@
 	unsigned int i;
 	jp2_cmap_t *cmapd;
 	jp2_pclr_t *pclrd;
+#if 0
+	/* The following code appears to no longer be needed. */
 	jp2_cdef_t *cdefd;
+#endif
 	unsigned int channo;
 	int newcmptno;
 	int_fast32_t *lutents;
@@ -117,8 +122,9 @@
 	jas_iccprof_t *iccprof;
 
 	box = 0;
+	image = 0;
 
-	JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr));
+	JAS_LOGDEBUGF(100, "jp2_decode(%p, \"%s\")\n", in, optstr);
 
 	if (!(dec = jp2_dec_create())) {
 		goto error;
@@ -126,15 +132,17 @@
 
 	/* Get the first box.  This should be a JP box. */
 	if (!(box = jp2_box_get(in))) {
-		jas_eprintf("error: cannot get box\n");
+		jas_logerrorf("error: cannot get box\n");
 		goto error;
 	}
 	if (box->type != JP2_BOX_JP) {
-		jas_eprintf("error: expecting signature box\n");
+		jas_logerrorf("error: expecting signature box\n");
 		goto error;
 	}
 	if (box->data.jp.magic != JP2_JP_MAGIC) {
-		jas_eprintf("incorrect magic number\n");
+		jas_logerrorf("incorrect magic number (0x%lx != 0x%lx)\n",
+		  JAS_CAST(unsigned long, box->data.jp.magic),
+		  JAS_CAST(unsigned long, JP2_JP_MAGIC));
 		goto error;
 	}
 	jp2_box_destroy(box);
@@ -141,10 +149,11 @@
 
 	/* Get the second box.  This should be a FTYP box. */
 	if (!(box = jp2_box_get(in))) {
+		jas_logerrorf("error: cannot get box\n");
 		goto error;
 	}
 	if (box->type != JP2_BOX_FTYP) {
-		jas_eprintf("expecting file type box\n");
+		jas_logerrorf("expecting file type box\n");
 		goto error;
 	}
 	jp2_box_destroy(box);
@@ -152,8 +161,8 @@
 	/* 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);
+		if (jas_get_debug_level() >= 1) {
+			jas_logdebugf(1, "got box type %s\n", box->info->name);
 		}
 		switch (box->type) {
 		case JP2_BOX_JP2C:
@@ -206,18 +215,18 @@
 	}
 
 	if (!found) {
-		jas_eprintf("error: no code stream found\n");
+		jas_logerrorf("error: no code stream found\n");
 		goto error;
 	}
 
 	if (!(dec->image = jpc_decode(in, optstr))) {
-		jas_eprintf("error: cannot decode code stream\n");
+		jas_logerrorf("error: cannot decode code stream\n");
 		goto error;
 	}
 
 	/* An IHDR box must be present. */
 	if (!dec->ihdr) {
-		jas_eprintf("error: missing IHDR box\n");
+		jas_logerrorf("error: missing IHDR box\n");
 		goto error;
 	}
 
@@ -225,12 +234,13 @@
 	  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");
+		jas_logerrorf("error: number of components mismatch (IHDR)\n");
+		goto error;
 	}
 
 	/* At least one component must be present. */
 	if (!jas_image_numcmpts(dec->image)) {
-		jas_eprintf("error: no components\n");
+		jas_logerrorf("error: no components\n");
 		goto error;
 	}
 
@@ -248,12 +258,13 @@
 	  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");
+		jas_logerrorf("error: component data type mismatch (IHDR)\n");
+		goto error;
 	}
 
 	/* Is the compression type supported? */
 	if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
-		jas_eprintf("error: unsupported compression type\n");
+		jas_logerrorf("error: unsupported compression type\n");
 		goto error;
 	}
 
@@ -260,9 +271,10 @@
 	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");
+		if (dec->bpcc->data.bpcc.numcmpts !=
+		  JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) {
+			jas_logerrorf("error: number of components mismatch (BPCC)\n");
+			goto error;
 		}
 		/* Is the component data type information indicated in the BPCC
 		  box consistent with the code stream data? */
@@ -271,17 +283,18 @@
 			  ++i) {
 				if (jas_image_cmptdtype(dec->image, i) !=
 				  JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
-					jas_eprintf("warning: component data type mismatch\n");
+					jas_logerrorf("error: component data type mismatch (BPCC)\n");
+						goto error;
 				}
 			}
 		} else {
-			jas_eprintf("warning: superfluous BPCC box\n");
+			jas_logwarnf("warning: superfluous BPCC box\n");
 		}
 	}
 
 	/* A COLR box must be present. */
 	if (!dec->colr) {
-		jas_eprintf("error: no COLR box\n");
+		jas_logerrorf("error: no COLR box\n");
 		goto error;
 	}
 
@@ -293,16 +306,17 @@
 		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");
+			jas_logerrorf("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));
+		JAS_LOGDEBUGF(2, "ICC Profile CS %08x\n", icchdr.colorspc);
 		dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
 		if (!dec->image->cmprof_) {
-			jas_iccprof_destroy(iccprof);
-			goto error;
+			jas_image_setclrspc(dec->image, JAS_CLRSPC_UNKNOWN);
+			jas_logwarnf("warning: cannot create CM profile from ICC profile\n");
+		} else {
+			jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
 		}
 		jas_iccprof_destroy(iccprof);
 		break;
@@ -310,7 +324,7 @@
 
 	/* 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");
+		jas_logwarnf("warning: missing PCLR box or superfluous CMAP box\n");
 		jp2_box_destroy(dec->cmap);
 		dec->cmap = 0;
 	}
@@ -317,7 +331,7 @@
 
 	/* 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");
+		jas_logwarnf("warning: missing CMAP box or superfluous PCLR box\n");
 		jp2_box_destroy(dec->pclr);
 		dec->pclr = 0;
 	}
@@ -333,13 +347,13 @@
 			/* 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");
+				jas_logerrorf("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");
+				jas_logerrorf("error: invalid CMAP LUT index\n");
 				goto error;
 			}
 		}
@@ -348,7 +362,7 @@
 	/* 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");
+		jas_logerrorf("error: no memory\n");
 		goto error;
 	}
 
@@ -357,8 +371,18 @@
 			dec->chantocmptlut[i] = i;
 		}
 	} else {
+		/* Check to ensure that CMAP/PCLR were initialized. */
+		if (!dec->cmap || !dec->pclr) {
+			jas_logerrorf("missing CMAP/PCLR box\n");
+			goto error;
+		}
+
 		cmapd = &dec->cmap->data.cmap;
 		pclrd = &dec->pclr->data.pclr;
+#if 0
+		/* The following code appears to no longer be needed. */
+		cdefd = &dec->cdef->data.cdef;
+#endif
 		for (channo = 0; channo < cmapd->numchans; ++channo) {
 			cmapent = &cmapd->ents[channo];
 			if (cmapent->map == JP2_CMAP_DIRECT) {
@@ -365,10 +389,12 @@
 				dec->chantocmptlut[channo] = channo;
 			} else if (cmapent->map == JP2_CMAP_PALETTE) {
 				if (!pclrd->numlutents) {
+					jas_logerrorf("error: empty LUT\n");
 					goto error;
 				}
-				lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t));
-				if (!lutents) {
+				if (!(lutents = jas_alloc2(pclrd->numlutents,
+				  sizeof(int_fast32_t)))) {
+					jas_logerrorf("error: cannot allocate LUT\n");
 					goto error;
 				}
 				for (i = 0; i < pclrd->numlutents; ++i) {
@@ -375,12 +401,18 @@
 					lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
 				}
 				newcmptno = jas_image_numcmpts(dec->image);
-				jas_image_depalettize(dec->image, cmapent->cmptno,
+				if (jas_image_depalettize(dec->image, cmapent->cmptno,
 				  pclrd->numlutents, lutents,
-				  JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
+				  JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno)) {
+					jas_logerrorf("jas_image_depalettize failed\n");
+					jas_free(lutents);
+					jas_logerrorf("error: depalettize failed\n");
+					goto error;
+				}
 				dec->chantocmptlut[channo] = newcmptno;
 				jas_free(lutents);
 #if 0
+				/* The following code appears to no longer be needed. */
 				if (dec->cdef) {
 					cdefent = jp2_cdef_lookup(cdefd, channo);
 					if (!cdefent) {
@@ -390,17 +422,25 @@
 				} 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");
+				jas_logerrorf("error: invalid MTYP in CMAP box\n");
 				goto error;
 			}
 		}
 	}
 
+#if 0
+	/* The following code appears to no longer be needed. */
+	/* Ensure that the number of channels being used by the decoder
+	  matches the number of image components. */
+	if (dec->numchans != jas_image_numcmpts(dec->image)) {
+		jas_logerrorf("error: mismatch in number of components (%d != %d)\n",
+		  dec->numchans, jas_image_numcmpts(dec->image));
+		goto error;
+	}
+#endif
+
 	/* Mark all components as being of unknown type. */
 
 	for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) {
@@ -410,13 +450,21 @@
 	/* Determine the type of each component. */
 	if (dec->cdef) {
 		for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) {
+			uint_fast16_t channo = dec->cdef->data.cdef.ents[i].channo;
 			/* 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");
+			if (channo >= dec->numchans) {
+				jas_logerrorf("error: invalid channel number in CDEF box (%d)\n",
+				  channo);
 				goto error;
 			}
-			jas_image_setcmpttype(dec->image,
-			  dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
+			unsigned compno = dec->chantocmptlut[channo];
+			if (compno >= jas_image_numcmpts(dec->image)) {
+				jas_logerrorf(
+				  "error: invalid component reference in CDEF box (%d)\n",
+				  compno);
+				goto error;
+			}
+			jas_image_setcmpttype(dec->image, compno,
 			  jp2_getct(jas_image_clrspc(dec->image),
 			  dec->cdef->data.cdef.ents[i].type,
 			  dec->cdef->data.cdef.ents[i].assoc));
@@ -423,7 +471,13 @@
 		}
 	} else {
 		for (i = 0; i < dec->numchans; ++i) {
-			jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
+			unsigned compno = dec->chantocmptlut[i];
+			if (compno >= jas_image_numcmpts(dec->image)) {
+				jas_logerrorf(
+				  "error: invalid component reference (%d)\n", compno);
+				goto error;
+			}
+			jas_image_setcmpttype(dec->image, compno,
 			  jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
 		}
 	}
@@ -437,12 +491,9 @@
 
 	/* Ensure that some components survived. */
 	if (!jas_image_numcmpts(dec->image)) {
-		jas_eprintf("error: no components\n");
+		jas_logerrorf("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;
@@ -453,6 +504,9 @@
 	return image;
 
 error:
+	if (image) {
+		jas_image_destroy(image);
+	}
 	if (box) {
 		jp2_box_destroy(box);
 	}
@@ -462,25 +516,25 @@
 	return 0;
 }
 
+#define JP2_VALIDATE_LEN JAS_MIN(JP2_JP_LEN + 4, JAS_STREAM_MAXPUTBACK)
 int jp2_validate(jas_stream_t *in)
 {
-	unsigned char buf[JP2_VALIDATELEN];
-#if 0
-	jas_stream_t *tmpstream;
-	jp2_box_t *box;
-#endif
+	unsigned char buf[JP2_VALIDATE_LEN];
 
-	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))
+	assert(sizeof(buf) <= JAS_STREAM_MAXPUTBACK);
+	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)
-	{
+	assert(JP2_VALIDATE_LEN >= 8);
+	if (((JAS_CAST(uint_least32_t, buf[4]) << 24) |
+	  (JAS_CAST(uint_least32_t, buf[5]) << 16) |
+	  (JAS_CAST(uint_least32_t, buf[6] << 8)) |
+	  (JAS_CAST(uint_least32_t, buf[7]))) !=
+	  JP2_BOX_JP) {
 		return -1;
 	}
 
--- /dev/null
+++ b/jp2_enc.c
@@ -1,0 +1,494 @@
+/*
+ * 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 "jasper/jas_image.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_cm.h"
+#include "jasper/jas_icc.h"
+#include "jasper/jas_debug.h"
+
+#include "jp2_cod.h"
+
+/******************************************************************************\
+* Function prototypes.
+\******************************************************************************/
+
+static uint_fast32_t jp2_gettypeasoc(int colorspace, int ctype);
+static int clrspctojp2(jas_clrspc_t clrspc);
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr)
+{
+	jp2_box_t *box;
+	jp2_ftyp_t *ftyp;
+	jp2_ihdr_t *ihdr;
+	jas_stream_t *tmpstream;
+	int allcmptssame;
+	jp2_bpcc_t *bpcc;
+	long len;
+	uint_fast16_t cmptno;
+	jp2_colr_t *colr;
+	char buf[4096];
+	uint_fast32_t overhead;
+	jp2_cdefchan_t *cdefchanent;
+	jp2_cdef_t *cdef;
+	uint_fast32_t typeasoc;
+	jas_iccprof_t *iccprof;
+	jas_stream_t *iccstream;
+	int pos;
+	int needcdef;
+
+	box = 0;
+	tmpstream = 0;
+	iccstream = 0;
+	iccprof = 0;
+
+	if (jas_image_numcmpts(image) < 1) {
+		jas_logerrorf("image must have at least one component\n");
+		goto error;
+	}
+
+	allcmptssame = 1;
+	const bool sgnd = jas_image_cmptsgnd(image, 0);
+	const unsigned prec = jas_image_cmptprec(image, 0);
+	for (unsigned i = 1; i < jas_image_numcmpts(image); ++i) {
+		if (jas_image_cmptsgnd(image, i) != sgnd ||
+		  jas_image_cmptprec(image, i) != prec) {
+			allcmptssame = 0;
+			break;
+		}
+	}
+
+	/* Output the signature box. */
+
+	if (!(box = jp2_box_create(JP2_BOX_JP))) {
+		jas_logerrorf("cannot create JP box\n");
+		goto error;
+	}
+	box->data.jp.magic = JP2_JP_MAGIC;
+	if (jp2_box_put(box, out)) {
+		jas_logerrorf("cannot write JP box\n");
+		goto error;
+	}
+	jp2_box_destroy(box);
+
+	/* Output the file type box. */
+
+	if (!(box = jp2_box_create(JP2_BOX_FTYP))) {
+		jas_logerrorf("cannot create FTYP box\n");
+		goto error;
+	}
+	ftyp = &box->data.ftyp;
+	ftyp->majver = JP2_FTYP_MAJVER;
+	ftyp->minver = JP2_FTYP_MINVER;
+	ftyp->numcompatcodes = 1;
+	ftyp->compatcodes[0] = JP2_FTYP_COMPATCODE;
+	if (jp2_box_put(box, out)) {
+		jas_logerrorf("cannot write FTYP box\n");
+		goto error;
+	}
+	jp2_box_destroy(box);
+	box = 0;
+
+	/*
+	 * Generate the data portion of the JP2 header box.
+	 * We cannot simply output the header for this box
+	 * since we do not yet know the correct value for the length
+	 * field.
+	 */
+
+	if (!(tmpstream = jas_stream_memopen(0, 0))) {
+		jas_logerrorf("cannot create temporary stream\n");
+		goto error;
+	}
+
+	/* Generate image header box. */
+
+	if (!(box = jp2_box_create(JP2_BOX_IHDR))) {
+		jas_logerrorf("cannot create IHDR box\n");
+		goto error;
+	}
+	ihdr = &box->data.ihdr;
+	ihdr->width = jas_image_width(image);
+	ihdr->height = jas_image_height(image);
+	ihdr->numcmpts = jas_image_numcmpts(image);
+	ihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0),
+	  jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL;
+	ihdr->comptype = JP2_IHDR_COMPTYPE;
+	ihdr->csunk = 0;
+	ihdr->ipr = 0;
+	if (jp2_box_put(box, tmpstream)) {
+		jas_logerrorf("cannot write IHDR box\n");
+		goto error;
+	}
+	jp2_box_destroy(box);
+
+	/* Generate bits per component box. */
+
+	if (!allcmptssame) {
+		if (!(box = jp2_box_create(JP2_BOX_BPCC))) {
+			jas_logerrorf("cannot create BPCC box\n");
+			goto error;
+		}
+		bpcc = &box->data.bpcc;
+		bpcc->numcmpts = jas_image_numcmpts(image);
+		if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts,
+		  sizeof(uint_fast8_t)))) {
+			jas_logerrorf("memory allocation failed\n");
+			goto error;
+		}
+		for (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) {
+			bpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image,
+			  cmptno), jas_image_cmptprec(image, cmptno));
+		}
+		if (jp2_box_put(box, tmpstream)) {
+			jas_logerrorf("cannot write BPCC box\n");
+			goto error;
+		}
+		jp2_box_destroy(box);
+	}
+
+	/* Generate color specification box. */
+
+	if (!(box = jp2_box_create(JP2_BOX_COLR))) {
+		jas_logerrorf("cannot create COLR box\n");
+		goto error;
+	}
+	colr = &box->data.colr;
+	switch (jas_image_clrspc(image)) {
+	case JAS_CLRSPC_SRGB:
+	case JAS_CLRSPC_SYCBCR:
+	case JAS_CLRSPC_SGRAY:
+		colr->method = JP2_COLR_ENUM;
+		colr->csid = clrspctojp2(jas_image_clrspc(image));
+		colr->pri = JP2_COLR_PRI;
+		colr->approx = 0;
+		break;
+	default:
+		colr->method = JP2_COLR_ICC;
+		colr->pri = JP2_COLR_PRI;
+		colr->approx = 0;
+		/* Ensure that cmprof_ is not null. */
+		if (!jas_image_cmprof(image)) {
+			jas_logerrorf("CM profile is null\n");
+			goto error;
+		}
+		if (!(iccprof = jas_iccprof_createfromcmprof(
+		  jas_image_cmprof(image)))) {
+			jas_logerrorf("cannot create ICC profile\n");
+			goto error;
+		}
+		if (!(iccstream = jas_stream_memopen(0, 0))) {
+			jas_logerrorf("cannot create temporary stream\n");
+			goto error;
+		}
+		if (jas_iccprof_save(iccprof, iccstream)) {
+			jas_logerrorf("cannot write ICC profile\n");
+			goto error;
+		}
+		if ((pos = jas_stream_tell(iccstream)) < 0) {
+			jas_logerrorf("cannot get stream position\n");
+			goto error;
+		}
+		colr->iccplen = pos;
+		if (!(colr->iccp = jas_malloc(pos))) {
+			jas_logerrorf("memory allocation failed\n");
+			goto error;
+		}
+		jas_stream_rewind(iccstream);
+		if (jas_stream_read(iccstream, colr->iccp, colr->iccplen) !=
+		  colr->iccplen) {
+			jas_logerrorf("cannot read temporary stream\n");
+			goto error;
+		}
+		jas_stream_close(iccstream);
+		iccstream = 0;
+		jas_iccprof_destroy(iccprof);
+		iccprof = 0;
+		break;
+	}
+	if (jp2_box_put(box, tmpstream)) {
+		jas_logerrorf("cannot write box\n");
+		goto error;
+	}
+	jp2_box_destroy(box);
+
+	needcdef = 1;
+	switch (jas_clrspc_fam(jas_image_clrspc(image))) {
+	case JAS_CLRSPC_FAM_RGB:
+		if (jas_image_numcmpts(image) >= 3 &&
+		  jas_image_cmpttype(image, 0) ==
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) &&
+		  jas_image_cmpttype(image, 1) ==
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) &&
+		  jas_image_cmpttype(image, 2) ==
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))
+			needcdef = 0;
+		break;
+	case JAS_CLRSPC_FAM_YCBCR:
+		if (jas_image_numcmpts(image) >= 3 &&
+		  jas_image_cmpttype(image, 0) ==
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) &&
+		  jas_image_cmpttype(image, 1) ==
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) &&
+		  jas_image_cmpttype(image, 2) ==
+		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))
+			needcdef = 0;
+		break;
+	case JAS_CLRSPC_FAM_GRAY:
+		if (jas_image_numcmpts(image) >= 1 &&
+		  jas_image_cmpttype(image, 0) ==
+		  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))
+			needcdef = 0;
+		break;
+	default:
+		assert(false);
+		JAS_UNREACHABLE();
+	}
+
+	if (needcdef) {
+		if (!(box = jp2_box_create(JP2_BOX_CDEF))) {
+			jas_logerrorf("cannot create CDEF box\n");
+			goto error;
+		}
+		cdef = &box->data.cdef;
+		cdef->numchans = jas_image_numcmpts(image);
+		cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t));
+		if (!cdef->ents) {
+			goto error;
+		}
+		for (unsigned i = 0; i < jas_image_numcmpts(image); ++i) {
+			cdefchanent = &cdef->ents[i];
+			cdefchanent->channo = i;
+			typeasoc = jp2_gettypeasoc(jas_image_clrspc(image), jas_image_cmpttype(image, i));
+			cdefchanent->type = typeasoc >> 16;
+			cdefchanent->assoc = typeasoc & 0x7fff;
+		}
+		if (jp2_box_put(box, tmpstream)) {
+			jas_logerrorf("cannot write CDEF box\n");
+			goto error;
+		}
+		jp2_box_destroy(box);
+	}
+
+	/* Determine the total length of the JP2 header box. */
+
+	len = jas_stream_tell(tmpstream);
+	jas_stream_rewind(tmpstream);
+
+	/*
+	 * Output the JP2 header box and all of the boxes which it contains.
+	 */
+
+	if (!(box = jp2_box_create(JP2_BOX_JP2H))) {
+		jas_logerrorf("cannot create JP2H box\n");
+		goto error;
+	}
+	box->len = len + JP2_BOX_HDRLEN(false);
+	if (jp2_box_put(box, out)) {
+		jas_logerrorf("cannot write JP2H box\n");
+		goto error;
+	}
+	jp2_box_destroy(box);
+	box = 0;
+
+	if (jas_stream_copy(out, tmpstream, len)) {
+		jas_logerrorf("cannot copy stream\n");
+		goto error;
+	}
+
+	jas_stream_close(tmpstream);
+	tmpstream = 0;
+
+	/*
+	 * Output the contiguous code stream box.
+	 */
+
+	if (!(box = jp2_box_create(JP2_BOX_JP2C))) {
+		jas_logerrorf("cannot create JP2C box\n");
+		goto error;
+	}
+	box->len = 0;
+	if (jp2_box_put(box, out)) {
+		jas_logerrorf("cannot write JP2C box\n");
+		goto error;
+	}
+	jp2_box_destroy(box);
+	box = 0;
+
+	/* Output the JPEG-2000 code stream. */
+
+	overhead = jas_stream_getrwcount(out);
+	sprintf(buf, "%s\n_jp2overhead=%lu\n", (optstr ? optstr : ""),
+	  (unsigned long) overhead);
+
+	if (jpc_encode(image, out, buf)) {
+		jas_logerrorf("jpc_encode failed\n");
+		goto error;
+	}
+
+	return 0;
+
+error:
+
+	if (iccprof) {
+		jas_iccprof_destroy(iccprof);
+	}
+	if (iccstream) {
+		jas_stream_close(iccstream);
+	}
+	if (box) {
+		jp2_box_destroy(box);
+	}
+	if (tmpstream) {
+		jas_stream_close(tmpstream);
+	}
+	return -1;
+}
+
+static uint_fast32_t jp2_gettypeasoc(int colorspace, int ctype)
+{
+	int type;
+	int asoc;
+
+	if (ctype & JAS_IMAGE_CT_OPACITY) {
+		type = JP2_CDEF_TYPE_OPACITY;
+		asoc = JP2_CDEF_ASOC_ALL;
+		goto done;
+	}
+
+	type = JP2_CDEF_TYPE_UNSPEC;
+	asoc = JP2_CDEF_ASOC_NONE;
+	switch (jas_clrspc_fam(colorspace)) {
+	case JAS_CLRSPC_FAM_RGB:
+		switch (JAS_IMAGE_CT_COLOR(ctype)) {
+		case JAS_IMAGE_CT_RGB_R:
+			type = JP2_CDEF_TYPE_COLOR;
+			asoc = JP2_CDEF_RGB_R;
+			break;
+		case JAS_IMAGE_CT_RGB_G:
+			type = JP2_CDEF_TYPE_COLOR;
+			asoc = JP2_CDEF_RGB_G;
+			break;
+		case JAS_IMAGE_CT_RGB_B:
+			type = JP2_CDEF_TYPE_COLOR;
+			asoc = JP2_CDEF_RGB_B;
+			break;
+		}
+		break;
+	case JAS_CLRSPC_FAM_YCBCR:
+		switch (JAS_IMAGE_CT_COLOR(ctype)) {
+		case JAS_IMAGE_CT_YCBCR_Y:
+			type = JP2_CDEF_TYPE_COLOR;
+			asoc = JP2_CDEF_YCBCR_Y;
+			break;
+		case JAS_IMAGE_CT_YCBCR_CB:
+			type = JP2_CDEF_TYPE_COLOR;
+			asoc = JP2_CDEF_YCBCR_CB;
+			break;
+		case JAS_IMAGE_CT_YCBCR_CR:
+			type = JP2_CDEF_TYPE_COLOR;
+			asoc = JP2_CDEF_YCBCR_CR;
+			break;
+		}
+		break;
+	case JAS_CLRSPC_FAM_GRAY:
+		type = JP2_CDEF_TYPE_COLOR;
+		asoc = JP2_CDEF_GRAY_Y;
+		break;
+	}
+
+done:
+	return (type << 16) | asoc;
+}
+
+static int clrspctojp2(jas_clrspc_t clrspc)
+{
+	switch (clrspc) {
+	case JAS_CLRSPC_SRGB:
+		return JP2_COLR_SRGB;
+	case JAS_CLRSPC_SYCBCR:
+		return JP2_COLR_SYCC;
+	case JAS_CLRSPC_SGRAY:
+		return JP2_COLR_SGRAY;
+	default:
+		assert(false);
+		JAS_UNREACHABLE();
+	}
+	JAS_UNREACHABLE();
+	return -1;
+}
--- a/jpc_bs.c
+++ b/jpc_bs.c
@@ -166,9 +166,9 @@
 int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream)
 {
 	int ret;
-	JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func(%p)\n", bitstream));
+	JAS_LOGDEBUGF(1000, "jpc_bitstream_getbit_func(%p)\n", bitstream);
 	ret = jpc_bitstream_getbit_macro(bitstream);
-	JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func -> %d\n", ret));
+	JAS_LOGDEBUGF(1000, "jpc_bitstream_getbit_func -> %d\n", ret);
 	return ret;
 }
 
@@ -176,9 +176,9 @@
 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));
+	JAS_LOGDEBUGF(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));
+	JAS_LOGDEBUGF(1000, "jpc_bitstream_putbit_func() -> %d\n", ret);
 	return ret;
 }
 
@@ -362,6 +362,7 @@
 	}
 	if (n > 0) {
 		if ((u = jpc_bitstream_getbits(bitstream, n)) < 0) {
+			JAS_LOGDEBUGF(1, "jpc_bitstream_inalign failed\n");
 			return -1;
 		}
 		m += n;
@@ -369,6 +370,7 @@
 	}
 	if ((bitstream->buf_ & 0xff) == 0xff) {
 		if ((u = jpc_bitstream_getbits(bitstream, 7)) < 0) {
+			JAS_LOGDEBUGF(1, "jpc_bitstream_inalign failed\n");
 			return -1;
 		}
 		v = (v << 7) | u;
@@ -382,6 +384,7 @@
 	}
 	if (((~(v ^ filldata)) & fillmask) != fillmask) {
 		/* The actual fill pattern does not match the expected one. */
+		JAS_LOGDEBUGF(1, "jpc_bitstream_inalign failed (mismatch)\n");
 		return 1;
 	}
 
--- a/jpc_bs.h
+++ b/jpc_bs.h
@@ -212,12 +212,12 @@
 int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream);
 
 #define	jpc_bitstream_getbit_macro(bitstream) \
-	  ((--(bitstream)->cnt_ >= 0) ? \
+	( (--(bitstream)->cnt_ >= 0) ? \
 	  ((int)(((bitstream)->buf_ >> (bitstream)->cnt_) & 1)) : \
 	  jpc_bitstream_fillbuf(bitstream))
 
 #define jpc_bitstream_putbit_macro(bitstream, bit) \
-	  ((--(bitstream)->cnt_ < 0) ? \
+	( (--(bitstream)->cnt_ < 0) ? \
 	  ((bitstream)->buf_ = ((bitstream)->buf_ << 8) & 0xffff, \
 	  (bitstream)->cnt_ = ((bitstream)->buf_ == 0xff00) ? 6 : 7, \
 	  (bitstream)->buf_ |= ((bit) & 1) << (bitstream)->cnt_, \
--- /dev/null
+++ b/jpc_cod.c
@@ -1,0 +1,109 @@
+/*
+ * 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__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#define JAS_FOR_INTERNAL_USE_ONLY
+
+#include <jasper/jas_config.h>
+#include "jasper/jas_thread.h"
+#include "jasper/jas_debug.h"
+
+#include "jpc_cod.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jpc_init_helper(void);
+
+#if defined(JAS_THREADS)
+jas_once_flag_t jpc_init_once = JAS_ONCE_FLAG_INIT;
+#else
+int jpc_init_once = 0;
+#endif
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+void jpc_init(void)
+{
+#if defined(JAS_THREADS)
+	jas_call_once(&jpc_init_once, jpc_init_helper);
+#else
+	if (!jpc_init_once) {
+		jpc_init_helper();
+		jpc_init_once = 1;
+	}
+#endif
+}
+
+static void jpc_init_helper(void)
+{
+	JAS_LOGDEBUGF(10, "jpc_init_helper called\n");
+	jpc_initmqctxs();
+	jpc_initluts();
+}
--- a/jpc_cod.h
+++ b/jpc_cod.h
@@ -68,6 +68,8 @@
 #ifndef JPC_COD_H
 #define JPC_COD_H
 
+#include "jpc_t1cod.h"
+
 /******************************************************************************\
 * Constants.
 \******************************************************************************/
@@ -74,5 +76,7 @@
 
 /* The nominal word size used by this implementation. */
 #define	JPC_PREC	32
+
+void jpc_init(void);
 
 #endif
--- a/jpc_cs.c
+++ b/jpc_cs.c
@@ -94,6 +94,7 @@
 
 static const jpc_mstabent_t *jpc_mstab_lookup(int id);
 
+static int jpc_poc_dumpparms(jpc_ms_t *ms);
 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);
@@ -126,6 +127,20 @@
 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);
+static int jpc_siz_dumpparms(jpc_ms_t *ms);
+static int jpc_cod_dumpparms(jpc_ms_t *ms);
+static int jpc_coc_dumpparms(jpc_ms_t *ms);
+static int jpc_qcd_dumpparms(jpc_ms_t *ms);
+static int jpc_qcc_dumpparms(jpc_ms_t *ms);
+static int jpc_rgn_dumpparms(jpc_ms_t *ms);
+static int jpc_unk_dumpparms(jpc_ms_t *ms);
+static int jpc_sop_dumpparms(jpc_ms_t *ms);
+static int jpc_ppm_dumpparms(jpc_ms_t *ms);
+static int jpc_ppt_dumpparms(jpc_ms_t *ms);
+static int jpc_crg_dumpparms(jpc_ms_t *ms);
+static int jpc_com_dumpparms(jpc_ms_t *ms);
+
 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);
@@ -153,26 +168,40 @@
 \******************************************************************************/
 
 static const jpc_mstabent_t jpc_mstab[] = {
-	{JPC_MS_SOC, "SOC", {0, 0, 0}},
-	{JPC_MS_SOT, "SOT", {0, jpc_sot_getparms, jpc_sot_putparms}},
-	{JPC_MS_SOD, "SOD", {0, 0, 0}},
-	{JPC_MS_EOC, "EOC", {0, 0, 0}},
-	{JPC_MS_SIZ, "SIZ", {jpc_siz_destroyparms, jpc_siz_getparms, jpc_siz_putparms}},
-	{JPC_MS_COD, "COD", {jpc_cod_destroyparms, jpc_cod_getparms, jpc_cod_putparms}},
-	{JPC_MS_COC, "COC", {jpc_coc_destroyparms, jpc_coc_getparms, jpc_coc_putparms}},
-	{JPC_MS_RGN, "RGN", {0, jpc_rgn_getparms, jpc_rgn_putparms}},
-	{JPC_MS_QCD, "QCD", {jpc_qcd_destroyparms, jpc_qcd_getparms, jpc_qcd_putparms}},
-	{JPC_MS_QCC, "QCC", {jpc_qcc_destroyparms, jpc_qcc_getparms, jpc_qcc_putparms}},
-	{JPC_MS_POC, "POC", {jpc_poc_destroyparms, jpc_poc_getparms, jpc_poc_putparms}},
-	{JPC_MS_TLM, "TLM", {jpc_unk_destroyparms, jpc_unk_getparms, jpc_unk_putparms,}},
-	{JPC_MS_PLM, "PLM", {jpc_unk_destroyparms, jpc_unk_getparms, jpc_unk_putparms}},
-	{JPC_MS_PPM, "PPM", {jpc_ppm_destroyparms, jpc_ppm_getparms, jpc_ppm_putparms}},
-	{JPC_MS_PPT, "PPT", {jpc_ppt_destroyparms, jpc_ppt_getparms, jpc_ppt_putparms}},
-	{JPC_MS_SOP, "SOP", {0, jpc_sop_getparms, jpc_sop_putparms}},
-	{JPC_MS_EPH, "EPH", {0, 0, 0}},
-	{JPC_MS_CRG, "CRG", {jpc_crg_destroyparms, jpc_crg_getparms, jpc_crg_putparms}},
-	{JPC_MS_COM, "COM", {jpc_com_destroyparms, jpc_com_getparms, jpc_com_putparms}},
-	{-1, "UNKNOWN",  {jpc_unk_destroyparms, jpc_unk_getparms, jpc_unk_putparms}}
+	{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}}
 };
 
 /******************************************************************************\
@@ -238,7 +267,7 @@
 			return 0;
 		}
 		if (jas_stream_copy(tmpstream, in, ms->len) ||
-		  jas_stream_seek(tmpstream, 0, 0) < 0) {
+		  jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) {
 			jas_stream_close(tmpstream);
 			jpc_ms_destroy(ms);
 			return 0;
@@ -251,8 +280,12 @@
 			return 0;
 		}
 
+		if (jas_get_debug_level() > 0) {
+			jpc_ms_dump(ms);
+		}
+
 		if (JAS_CAST(jas_ulong, jas_stream_tell(tmpstream)) != ms->len) {
-			jas_eprintf(
+			jas_logwarnf(
 			  "warning: trailing garbage in marker segment (%ld bytes)\n",
 			  ms->len - jas_stream_tell(tmpstream));
 		}
@@ -263,6 +296,10 @@
 	} else {
 		/* There are no marker segment parameters. */
 		ms->len = 0;
+
+		if (jas_get_debug_level() > 0) {
+			jpc_ms_dump(ms);
+		}
 	}
 
 	/* Update the code stream state information based on the type of
@@ -306,7 +343,7 @@
 		ms->len = len;
 		/* Write the marker segment length and parameter data to
 		  the output stream. */
-		if (jas_stream_seek(tmpstream, 0, 0) < 0 ||
+		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);
@@ -322,6 +359,10 @@
 		cstate->numcomps = ms->parms.siz.numcomps;
 	}
 
+	if (jas_get_debug_level() > 0) {
+		jpc_ms_dump(ms);
+	}
+
 	return 0;
 }
 
@@ -355,6 +396,24 @@
 	jas_free(ms);
 }
 
+/* Dump a marker segment to a stream for debugging. */
+void jpc_ms_dump(jpc_ms_t *ms)
+{
+	const jpc_mstabent_t *mstabent;
+	mstabent = jpc_mstab_lookup(ms->id);
+	jas_logprintf("type = 0x%04"PRIxFAST16" (%s);", ms->id, mstabent->name);
+	if (JPC_MS_HASPARMS(ms->id)) {
+		jas_logprintf(" len = %"PRIuFAST16";", ms->len + 2);
+		if (ms->ops->dumpparms) {
+			(*ms->ops->dumpparms)(ms);
+		} else {
+			jas_logprintf("\n");
+		}
+	} else {
+		jas_logprintf("\n");
+	}
+}
+
 /******************************************************************************\
 * SOT marker segment operations.
 \******************************************************************************/
@@ -363,8 +422,7 @@
 {
 	jpc_sot_t *sot = &ms->parms.sot;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_getuint16(in, &sot->tileno) ||
 	  jpc_getuint32(in, &sot->len) ||
@@ -385,8 +443,7 @@
 {
 	jpc_sot_t *sot = &ms->parms.sot;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_putuint16(out, sot->tileno) ||
 	  jpc_putuint32(out, sot->len) ||
@@ -397,6 +454,15 @@
 	return 0;
 }
 
+static int jpc_sot_dumpparms(jpc_ms_t *ms)
+{
+	jpc_sot_t *sot = &ms->parms.sot;
+	jas_logprintf(
+	  "tileno = %"PRIuFAST16"; len = %"PRIuFAST32"; partno = %d; numparts = %d\n",
+	  sot->tileno, sot->len, sot->partno, sot->numparts);
+	return 0;
+}
+
 /******************************************************************************\
 * SIZ marker segment operations.
 \******************************************************************************/
@@ -418,8 +484,7 @@
 
 	siz->comps = 0;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_getuint16(in, &siz->caps) ||
 	  jpc_getuint32(in, &siz->width) ||
@@ -434,31 +499,31 @@
 		goto error;
 	}
 	if (!siz->width || !siz->height) {
-		jas_eprintf("reference grid cannot have zero area\n");
+		jas_logerrorf("reference grid cannot have zero area\n");
 		goto error;
 	}
 	if (!siz->tilewidth || !siz->tileheight) {
-		jas_eprintf("tile cannot have zero area\n");
+		jas_logerrorf("tile cannot have zero area\n");
 		goto error;
 	}
 	if (!siz->numcomps || siz->numcomps > 16384) {
-		jas_eprintf("number of components not in permissible range\n");
+		jas_logerrorf("number of components not in permissible range\n");
 		goto error;
 	}
 	if (siz->xoff >= siz->width) {
-		jas_eprintf("XOsiz not in permissible range\n");
+		jas_logerrorf("XOsiz not in permissible range\n");
 		goto error;
 	}
 	if (siz->yoff >= siz->height) {
-		jas_eprintf("YOsiz not in permissible range\n");
+		jas_logerrorf("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");
+		jas_logerrorf("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");
+		jas_logerrorf("YTOsiz not in permissible range\n");
 		goto error;
 	}
 
@@ -472,11 +537,11 @@
 			goto error;
 		}
 		if (siz->comps[i].hsamp == 0) {
-			jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
+			jas_logerrorf("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);
+			jas_logerrorf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
 			goto error;
 		}
 		siz->comps[i].sgnd = (tmp >> 7) & 1;
@@ -485,7 +550,7 @@
 		   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);
+			jas_logerrorf("invalid component bit depth %d\n", siz->comps[i].prec);
 			goto error;
 		}
 	}
@@ -506,8 +571,7 @@
 	jpc_siz_t *siz = &ms->parms.siz;
 	unsigned int i;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	assert(siz->width && siz->height && siz->tilewidth &&
 	  siz->tileheight && siz->numcomps);
@@ -534,6 +598,26 @@
 	return 0;
 }
 
+static int jpc_siz_dumpparms(jpc_ms_t *ms)
+{
+	jpc_siz_t *siz = &ms->parms.siz;
+	unsigned int i;
+	jas_logprintf("caps = 0x%02"PRIxFAST16";\n", siz->caps);
+	jas_logprintf("width = %"PRIuFAST32"; height = %"PRIuFAST32"; xoff = %"PRIuFAST32"; yoff = %" PRIuFAST32 ";\n",
+	  siz->width, siz->height, siz->xoff, siz->yoff);
+	jas_logprintf("tilewidth = %"PRIuFAST32"; tileheight = %"PRIuFAST32"; "
+	  "tilexoff = %"PRIuFAST32"; tileyoff = %" PRIuFAST32 ";\n",
+	  siz->tilewidth, siz->tileheight, siz->tilexoff, siz->tileyoff);
+	jas_logprintf("numcomps = %"PRIuFAST16";\n", siz->numcomps);
+	for (i = 0; i < siz->numcomps; ++i) {
+		jas_logprintf("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.
 \******************************************************************************/
@@ -587,6 +671,28 @@
 	return 0;
 }
 
+static int jpc_cod_dumpparms(jpc_ms_t *ms)
+{
+	jpc_cod_t *cod = &ms->parms.cod;
+	int i;
+	jas_logprintf("csty = 0x%02x;\n", cod->compparms.csty);
+	jas_logprintf("numdlvls = %d; qmfbid = %d; mctrans = %d\n",
+	  cod->compparms.numdlvls, cod->compparms.qmfbid, cod->mctrans);
+	jas_logprintf("prg = %d; numlyrs = %"PRIuFAST16";\n",
+	  cod->prg, cod->numlyrs);
+	jas_logprintf("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_logprintf("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.
 \******************************************************************************/
@@ -647,6 +753,16 @@
 	return 0;
 }
 
+static int jpc_coc_dumpparms(jpc_ms_t *ms)
+{
+	jpc_coc_t *coc = &ms->parms.coc;
+	jas_logprintf("compno = %"PRIuFAST16"; csty = 0x%02x; numdlvls = %d;\n",
+	  coc->compno, coc->compparms.csty, coc->compparms.numdlvls);
+	jas_logprintf("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.
 \******************************************************************************/
@@ -653,8 +769,7 @@
 
 static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms)
 {
-	/* Eliminate compiler warning about unused variables. */
-	USED(compparms);
+	JAS_UNUSED(compparms);
 }
 
 static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
@@ -663,9 +778,8 @@
 	uint_fast8_t tmp;
 	int i;
 
-	/* Eliminate compiler warning about unused variables. */
-	USED(ms);
-	USED(cstate);
+	JAS_UNUSED(ms);
+	JAS_UNUSED(cstate);
 
 	if (jpc_getuint8(in, &compparms->numdlvls) ||
 	  jpc_getuint8(in, &compparms->cblkwidthval) ||
@@ -711,9 +825,8 @@
 	int i;
 	assert(compparms->numdlvls <= 32);
 
-	/* Eliminate compiler warning about unused variables. */
-	USED(ms);
-	USED(cstate);
+	JAS_UNUSED(ms);
+	JAS_UNUSED(cstate);
 
 	if (jpc_putuint8(out, compparms->numdlvls) ||
 	  jpc_putuint8(out, compparms->cblkwidthval) ||
@@ -778,6 +891,14 @@
 	return 0;
 }
 
+static int jpc_rgn_dumpparms(jpc_ms_t *ms)
+{
+	jpc_rgn_t *rgn = &ms->parms.rgn;
+	jas_logprintf("compno = %"PRIuFAST16"; roisty = %d; roishift = %d\n",
+	  rgn->compno, rgn->roisty, rgn->roishift);
+	return 0;
+}
+
 /******************************************************************************\
 * QCD marker segment operations.
 \******************************************************************************/
@@ -800,6 +921,20 @@
 	return jpc_qcx_putcompparms(compparms, cstate, out);
 }
 
+static int jpc_qcd_dumpparms(jpc_ms_t *ms)
+{
+	jpc_qcd_t *qcd = &ms->parms.qcd;
+	int i;
+	jas_logprintf("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) {
+		jas_logprintf("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.
 \******************************************************************************/
@@ -856,6 +991,21 @@
 	return 0;
 }
 
+static int jpc_qcc_dumpparms(jpc_ms_t *ms)
+{
+	jpc_qcc_t *qcc = &ms->parms.qcc;
+	int i;
+	jas_logprintf("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) {
+		jas_logprintf("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.
 \******************************************************************************/
@@ -874,8 +1024,7 @@
 	int n;
 	int i;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	n = 0;
 	if (jpc_getuint8(in, &tmp)) {
@@ -936,8 +1085,7 @@
 {
 	int i;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_putuint8(out, ((compparms->numguard & 7) << 5) | compparms->qntsty)) {
 		return -1;
@@ -965,8 +1113,7 @@
 {
 	jpc_sop_t *sop = &ms->parms.sop;
 
-	/* Eliminate compiler warning about unused variable. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_getuint16(in, &sop->seqno)) {
 		return -1;
@@ -978,8 +1125,7 @@
 {
 	jpc_sop_t *sop = &ms->parms.sop;
 
-	/* Eliminate compiler warning about unused variable. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_putuint16(out, sop->seqno)) {
 		return -1;
@@ -987,6 +1133,13 @@
 	return 0;
 }
 
+static int jpc_sop_dumpparms(jpc_ms_t *ms)
+{
+	jpc_sop_t *sop = &ms->parms.sop;
+	jas_logprintf("seqno = %"PRIuFAST16";\n", sop->seqno);
+	return 0;
+}
+
 /******************************************************************************\
 * PPM marker segment operations.
 \******************************************************************************/
@@ -1003,8 +1156,7 @@
 {
 	jpc_ppm_t *ppm = &ms->parms.ppm;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	ppm->data = 0;
 
@@ -1037,8 +1189,7 @@
 {
 	jpc_ppm_t *ppm = &ms->parms.ppm;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (JAS_CAST(jas_uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {
 		return -1;
@@ -1046,6 +1197,17 @@
 	return 0;
 }
 
+static int jpc_ppm_dumpparms(jpc_ms_t *ms)
+{
+	jpc_ppm_t *ppm = &ms->parms.ppm;
+	jas_logprintf("ind=%d; len = %"PRIuFAST16";\n", ppm->ind, ppm->len);
+	if (ppm->len > 0) {
+		jas_logprintf("data =\n");
+		jas_logmemdump(ppm->data, ppm->len);
+	}
+	return 0;
+}
+
 /******************************************************************************\
 * PPT marker segment operations.
 \******************************************************************************/
@@ -1062,8 +1224,7 @@
 {
 	jpc_ppt_t *ppt = &ms->parms.ppt;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	ppt->data = 0;
 
@@ -1095,8 +1256,7 @@
 {
 	jpc_ppt_t *ppt = &ms->parms.ppt;
 
-	/* Eliminate compiler warning about unused variable. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_putuint8(out, ppt->ind)) {
 		return -1;
@@ -1107,6 +1267,17 @@
 	return 0;
 }
 
+static int jpc_ppt_dumpparms(jpc_ms_t *ms)
+{
+	jpc_ppt_t *ppt = &ms->parms.ppt;
+	jas_logprintf("ind=%d; len = %"PRIuFAST32";\n", ppt->ind, ppt->len);
+	if (ppt->len > 0) {
+		jas_logprintf("data =\n");
+		jas_logmemdump(ppt->data, ppt->len);
+	}
+	return 0;
+}
+
 /******************************************************************************\
 * POC marker segment operations.
 \******************************************************************************/
@@ -1197,6 +1368,23 @@
 	return 0;
 }
 
+static int jpc_poc_dumpparms(jpc_ms_t *ms)
+{
+	jpc_poc_t *poc = &ms->parms.poc;
+	jpc_pocpchg_t *pchg;
+	int pchgno;
+	for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs;
+	  ++pchgno, ++pchg) {
+		jas_logprintf("po[%d] = %d; ", pchgno, pchg->prgord);
+		jas_logprintf("cs[%d] = %"PRIuFAST16"; ce[%d] = %"PRIuFAST16"; ",
+		  pchgno, pchg->compnostart, pchgno, pchg->compnoend);
+		jas_logprintf("rs[%d] = %d; re[%d] = %d; ",
+		  pchgno, pchg->rlvlnostart, pchgno, pchg->rlvlnoend);
+		jas_logprintf("le[%d] = %"PRIuFAST16"\n", pchgno, pchg->lyrnoend);
+	}
+	return 0;
+}
+
 /******************************************************************************\
 * CRG marker segment operations.
 \******************************************************************************/
@@ -1235,8 +1423,7 @@
 	int compno;
 	jpc_crgcomp_t *comp;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
 	  ++comp) {
@@ -1248,6 +1435,19 @@
 	return 0;
 }
 
+static int jpc_crg_dumpparms(jpc_ms_t *ms)
+{
+	jpc_crg_t *crg = &ms->parms.crg;
+	int compno;
+	jpc_crgcomp_t *comp;
+	for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
+	  ++comp) {
+		jas_logprintf("hoff[%d] = %"PRIuFAST16"; voff[%d] = %"PRIuFAST16"\n",
+		  compno, comp->hoff, compno, comp->voff);
+	}
+	return 0;
+}
+
 /******************************************************************************\
 * Operations for COM marker segment.
 \******************************************************************************/
@@ -1264,8 +1464,7 @@
 {
 	jpc_com_t *com = &ms->parms.com;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_getuint16(in, &com->regid)) {
 		return -1;
@@ -1288,8 +1487,7 @@
 {
 	jpc_com_t *com = &ms->parms.com;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (jpc_putuint16(out, com->regid)) {
 		return -1;
@@ -1300,6 +1498,29 @@
 	return 0;
 }
 
+static int jpc_com_dumpparms(jpc_ms_t *ms)
+{
+	jpc_com_t *com = &ms->parms.com;
+	unsigned int i;
+	int printable;
+	jas_logprintf("regid = %"PRIuFAST16";\n", com->regid);
+	printable = 1;
+	for (i = 0; i < com->len; ++i) {
+		if (!isprint(com->data[i])) {
+			printable = 0;
+			break;
+		}
+	}
+	if (printable) {
+		jas_logprintf("data = %.*s\n", com->len, com->data);
+/* FIXME: print the data
+		fwrite(com->data, sizeof(char), com->len, out);
+		jas_logprintf("\n");
+*/
+	}
+	return 0;
+}
+
 /******************************************************************************\
 * Operations for unknown types of marker segments.
 \******************************************************************************/
@@ -1318,8 +1539,7 @@
 
 	unk->data = 0;
 
-	/* Eliminate compiler warning about unused variables. */
-	(void)cstate;
+	JAS_UNUSED(cstate);
 
 	if (ms->len > 0) {
 		if (!(unk->data = jas_alloc2(ms->len, sizeof(unsigned char)))) {
@@ -1339,10 +1559,9 @@
 
 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);
+	JAS_UNUSED(cstate);
+	JAS_UNUSED(ms);
+	JAS_UNUSED(out);
 
 	/* If this function is called, we are trying to write an unsupported
 	  type of marker segment.  Return with an error indication.  */
@@ -1349,6 +1568,16 @@
 	return -1;
 }
 
+static int jpc_unk_dumpparms(jpc_ms_t *ms)
+{
+	unsigned int i;
+	jpc_unk_t *unk = &ms->parms.unk;
+	for (i = 0; i < unk->len; ++i) {
+		jas_logprintf("%02x ", unk->data[i]);
+	}
+	return 0;
+}
+
 /******************************************************************************\
 * Primitive I/O operations.
 \******************************************************************************/
@@ -1429,6 +1658,12 @@
 int jpc_validate(jas_stream_t *in)
 {
 	unsigned char buf[2];
+
+	/*
+	Note: The validation operation does not require the initialization of the
+	JPC codec.  So, jpc_init is not called here.
+	jpc_init();
+	*/
 
 	assert(JAS_STREAM_MAXPUTBACK >= 2);
 
--- a/jpc_cs.h
+++ b/jpc_cs.h
@@ -726,6 +726,9 @@
 	/* 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);
+
 } jpc_msops_t;
 
 /******************************************************************************\
@@ -770,6 +773,9 @@
 
 /* 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);
 
 /* Read a 8-bit unsigned integer from a stream. */
 int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val);
--- a/jpc_dec.c
+++ b/jpc_dec.c
@@ -78,8 +78,10 @@
 #include "jpc_t1dec.h"
 #include "jpc_math.h"
 
+#include "jasper/jas_init.h"
 #include "jasper/jas_types.h"
 #include "jasper/jas_math.h"
+#include "jasper/jas_tvp.h"
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_debug.h"
 
@@ -131,6 +133,8 @@
 * Local function prototypes.
 \******************************************************************************/
 
+static int jpc_dec_dump(const jpc_dec_t *dec);
+
 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);
@@ -197,6 +201,12 @@
 
 static const jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id);
 
+static void jpc_rlvl_init(jpc_dec_rlvl_t *rlvl);
+static void jpc_band_init(jpc_dec_band_t *band);
+static void jpc_prc_init(jpc_dec_prc_t *prc);
+static void jpc_cblk_init(jpc_dec_cblk_t *cblk);
+static void jpc_seglist_init(jpc_dec_seglist_t *seglist);
+
 /******************************************************************************\
 * Global data.
 \******************************************************************************/
@@ -236,13 +246,14 @@
 
 	dec = 0;
 
-	JAS_DBGLOG(100, ("jpc_decode(%p, \"%s\")\n", in, optstr));
+	JAS_LOGDEBUGF(100, "jpc_decode(%p, \"%s\")\n", in, optstr);
 
 	if (!(opts = jpc_dec_opts_create(optstr))) {
 		goto error;
 	}
 
-	jpc_initluts();
+	jpc_init();
+	//jpc_initluts();
 
 	if (!(dec = jpc_dec_create(opts, in))) {
 		goto error;
@@ -290,11 +301,27 @@
 	return 0;
 }
 
+typedef enum {
+	OPT_MAXLYRS,
+	OPT_MAXPKTS,
+	OPT_MAXSAMPLES,
+	OPT_DEBUG
+} optid_t;
+
+static const jas_taginfo_t decopts[] = {
+	{OPT_MAXLYRS, "maxlyrs"},
+	{OPT_MAXPKTS, "maxpkts"},
+	{OPT_MAXSAMPLES, "max_samples"},
+	{OPT_DEBUG, "debug"},
+	{-1, 0}
+};
+
 static jpc_dec_importopts_t *jpc_dec_opts_create(const char *optstr)
 {
 	jpc_dec_importopts_t *opts;
+	jas_tvparser_t *tvp;
 
-	USED(optstr);
+
 	if (!(opts = jas_malloc(sizeof(jpc_dec_importopts_t)))) {
 		goto error;
 	}
@@ -302,8 +329,36 @@
 	opts->debug = 0;
 	opts->maxlyrs = JPC_MAXLYRS;
 	opts->maxpkts = -1;
-	opts->max_samples = JAS_DEC_DEFAULT_MAX_SAMPLES;
+	opts->max_samples = jas_get_dec_default_max_samples();
 
+	if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
+		goto error;
+	}
+
+	while (!jas_tvparser_next(tvp)) {
+		switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts,
+		  jas_tvparser_gettag(tvp)))->id) {
+		case OPT_MAXLYRS:
+			opts->maxlyrs = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_DEBUG:
+			opts->debug = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_MAXPKTS:
+			opts->maxpkts = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_MAXSAMPLES:
+			opts->max_samples = strtoull(jas_tvparser_getval(tvp), 0, 10);
+			break;
+		default:
+			jas_logwarnf("warning: ignoring invalid option %s\n",
+			  jas_tvparser_gettag(tvp));
+			break;
+		}
+	}
+
+	jas_tvparser_destroy(tvp);
+
 	return opts;
 
 error:
@@ -353,7 +408,7 @@
 
 		/* Get the next marker segment in the code stream. */
 		if (!(ms = jpc_getms(dec->in, cstate))) {
-			jas_eprintf("cannot get marker segment\n");
+			jas_logerrorf("cannot get marker segment\n");
 			return -1;
 		}
 
@@ -363,7 +418,7 @@
 		/* 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");
+			jas_logerrorf("unexpected marker segment type\n");
 			jpc_ms_destroy(ms);
 			return -1;
 		}
@@ -407,7 +462,7 @@
 		cmpt->vsubstep = crg->comps[cmptno].voff;
 		*/
 		/* suppress -Wunused-but-set-variable */
-		USED(crg);
+		JAS_UNUSED(crg);
 	}
 	return 0;
 }
@@ -414,8 +469,7 @@
 
 static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms)
 {
-	/* Eliminate warnings about unused variables. */
-	(void)ms;
+	JAS_UNUSED(ms);
 
 	/* We should expect to encounter a SIZ marker segment next. */
 	dec->state = JPC_MHSIZ;
@@ -478,7 +532,7 @@
 	}
 
 	if (sot->tileno >= dec->numtiles) {
-		jas_eprintf("invalid tile number in SOT marker segment\n");
+		jas_logerrorf("invalid tile number in SOT marker segment\n");
 		return -1;
 	}
 	/* Set the current tile. */
@@ -529,8 +583,7 @@
 	jpc_dec_tile_t *tile;
 	int pos;
 
-	/* Eliminate compiler warnings about unused variables. */
-	(void)ms;
+	JAS_UNUSED(ms);
 
 	if (!(tile = dec->curtile)) {
 		return -1;
@@ -564,18 +617,22 @@
 			}
 		}
 		pos = jas_stream_tell(tile->pkthdrstream);
-		jas_stream_seek(tile->pkthdrstream, 0, 2);
+		jas_stream_seek(tile->pkthdrstream, 0, SEEK_END);
 		if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) {
 			return -1;
 		}
-		jas_stream_seek(tile->pkthdrstream, pos, 0);
+		jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET);
 		jpc_ppxstab_destroy(tile->pptstab);
 		tile->pptstab = 0;
 	}
 
+	if (jas_get_debug_level() >= 10) {
+		jpc_dec_dump(dec);
+	}
+
 	if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream :
 	  dec->in, dec->in)) {
-		jas_eprintf("jpc_dec_decodepkts failed\n");
+		jas_logerrorf("jpc_dec_decodepkts failed\n");
 		return -1;
 	}
 
@@ -586,17 +643,17 @@
 		curoff = jas_stream_getrwcount(dec->in);
 		if (curoff < dec->curtileendoff) {
 			n = dec->curtileendoff - curoff;
-			jas_eprintf("warning: ignoring trailing garbage (%lu bytes)\n",
+			jas_logwarnf("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");
+					jas_logerrorf("read error\n");
 					return -1;
 				}
 			}
 		} else if (curoff > dec->curtileendoff) {
-			jas_eprintf("warning: not enough tile data (%lu bytes)\n",
+			jas_logwarnf("warning: not enough tile data (%lu bytes)\n",
 			  (unsigned long) curoff - dec->curtileendoff);
 		}
 
@@ -653,7 +710,12 @@
 	uint_fast32_t tmpyend;
 	jpc_tsfb_band_t bnds[JPC_MAXBANDS];
 	jpc_pchg_t *pchg;
+	int retval = 0;
 
+	if (jas_get_debug_level() >= 1) {
+		jas_logerrorf("jpc_dec_tileinit called\n");
+	}
+
 	const jpc_dec_cp_t *cp = tile->cp;
 	tile->realmode = 0;
 	if (cp->mctid == JPC_MCT_ICT) {
@@ -665,6 +727,9 @@
 	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 (jas_get_debug_level() >= 10) {
+			jas_logdebugf(10, "[compno %d]\n", compno);
+		}
 		if (ccp->qmfbid == JPC_COX_INS) {
 			tile->realmode = 1;
 		}
@@ -671,21 +736,28 @@
 		tcomp->numrlvls = ccp->numrlvls;
 		if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls,
 		  sizeof(jpc_dec_rlvl_t)))) {
-			return -1;
+			retval = -1;
+			goto done;
 		}
 		for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
 		  ++rlvlno, ++rlvl) {
+#if 0
 			rlvl->bands = NULL;
+#else
+			jpc_rlvl_init(rlvl);
+#endif
 		}
 		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;
+			retval = -1;
+			goto done;
 		}
 		if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid,
 		  tcomp->numrlvls - 1))) {
-			return -1;
+			retval = -1;
+			goto done;
 		}
 		{
 			jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data),
@@ -719,6 +791,16 @@
 			  rlvl->prcheightexpn;
 			rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
 
+			if (jas_get_debug_level() >= 10) {
+				jas_logdebugf(10,
+				  "[compno %d rlvlno %d]: xstart %d ystart %d "
+				  "xend %d yend %d prcwidthexpn %d prcheightexpn %d "
+				  "numhprcs %d numvprcs %d numprcs %d\n",
+				  compno, rlvlno, rlvl->xstart, rlvl->ystart, rlvl->xend,
+				  rlvl->yend, rlvl->prcwidthexpn, rlvl->prcheightexpn,
+				  rlvl->numhprcs, rlvl->numvprcs, rlvl->numprcs);
+			}
+
 			if (rlvl->numprcs >= 64 * 1024) {
 				/* avoid out-of-memory due to
 				   malicious file; this limit is
@@ -747,7 +829,8 @@
 				if (rlvl->prcwidthexpn < 1 || rlvl->prcheightexpn < 1) {
 					/* the control block width/height offset
 					   exponent must not be negative */
-					return -1;
+					retval = -1;
+					goto done;
 				}
 				rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
 				rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
@@ -760,15 +843,26 @@
 			rlvl->numbands = (!rlvlno) ? 1 : 3;
 			if (!(rlvl->bands = jas_alloc2(rlvl->numbands,
 			  sizeof(jpc_dec_band_t)))) {
-				return -1;
+				retval = -1;
+				goto done;
 			}
 			unsigned bandno;
+#if 1
 			for (bandno = 0, band = rlvl->bands;
 			  bandno < rlvl->numbands; ++bandno, ++band) {
+				jpc_band_init(band);
+			}
+#endif
+			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];
 
+				if (jas_get_debug_level() >= 10) {
+					jas_logdebugf(10, "[compno %d rlvlno %d bandno %d]\n", compno, rlvlno, bandno);
+				}
+
 				band->orient = bnd->orient;
 				band->stepsize = ccp->stepsizes[bndno];
 				band->analgain = JPC_NOMINALGAIN(ccp->qmfbid,
@@ -785,11 +879,13 @@
 					continue;
 				}
 				if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
-					return -1;
+					retval = -1;
+					goto done;
 				}
 				if (jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart,
 						      bnd->locystart, bnd->locxend, bnd->locyend)) {
-					return -1;
+					retval = -1;
+					goto done;
 				}
 				jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart);
 
@@ -797,14 +893,25 @@
 
 				if (!(band->prcs = jas_alloc2(rlvl->numprcs,
 				  sizeof(jpc_dec_prc_t)))) {
-					return -1;
+					retval = -1;
+					goto done;
 				}
 
 /************************************************/
 				cbgxstart = tlcbgxstart;
 				cbgystart = tlcbgystart;
-				unsigned prccnt;				for (prccnt = rlvl->numprcs, prc = band->prcs;
+				unsigned prccnt;
+#if 1
+				for (prccnt = rlvl->numprcs, prc = band->prcs;
 				  prccnt > 0; --prccnt, ++prc) {
+					jpc_prc_init(prc);
+				}
+#endif
+				for (prccnt = rlvl->numprcs, prc = band->prcs;
+				  prccnt > 0; --prccnt, ++prc) {
+					if (jas_get_debug_level() >= 10) {
+						jas_logdebugf(10, "[compno %d rlvlno %d bandno %d prccnt %d]\n", compno, rlvlno, bandno, prccnt);
+					}
 					cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn);
 					cbgyend = cbgystart + (1 << rlvl->cbgheightexpn);
 					prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t,
@@ -831,24 +938,43 @@
 						prc->numcblks = prc->numhcblks * prc->numvcblks;
 						assert(prc->numcblks > 0);
 
+						if (jas_get_debug_level() >= 10) {
+							jas_logdebugf(10, "[compno %d rlvlno %d bandno %d prccnt %d]: "
+							  "numhcblks %d numvcblks %d numcblks %d\n",
+							  compno, rlvlno, bandno, prccnt, prc->numhcblks, prc->numvcblks,
+							  prc->numcblks);
+						}
+
 						if (!(prc->incltagtree = jpc_tagtree_create(
 						  prc->numhcblks, prc->numvcblks))) {
-							return -1;
+							retval = -1;
+							goto done;
 						}
 						if (!(prc->numimsbstagtree = jpc_tagtree_create(
 						  prc->numhcblks, prc->numvcblks))) {
-							return -1;
+							retval = -1;
+							goto done;
 						}
 						if (!(prc->cblks = jas_alloc2(prc->numcblks,
 						  sizeof(jpc_dec_cblk_t)))) {
-							return -1;
+							retval = -1;
+							goto done;
 						}
 
 						cblkxstart = cbgxstart;
 						cblkystart = cbgystart;
 						unsigned cblkcnt;
+#if 1
 						for (cblkcnt = prc->numcblks, cblk = prc->cblks;
+						  cblkcnt > 0; ++cblk, --cblkcnt) {
+							jpc_cblk_init(cblk);
+						}
+#endif
+						for (cblkcnt = prc->numcblks, cblk = prc->cblks;
 						  cblkcnt > 0;) {
+							if (jas_get_debug_level() >= 10000) {
+								jas_logdebugf(10000, "[compno %d rlvlno %d bandno %d prcno %d cblkcnt %d]\n", compno, rlvlno, bandno, prccnt, cblkcnt);
+							}
 							cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn);
 							cblkyend = cblkystart + (1 << rlvl->cblkheightexpn);
 							tmpxstart = JAS_MAX(cblkxstart, prc->xstart);
@@ -865,11 +991,13 @@
 								cblk->numlenbits = 3;
 								if (!(cblk->data = jas_seq2d_create(0, 0, 0,
 								  0))) {
-									return -1;
+									retval = -1;
+									goto done;
 								}
 								if (jas_seq2d_bindsub(cblk->data, band->data,
 										      tmpxstart, tmpystart, tmpxend, tmpyend)) {
-									return -1;
+									retval = -1;
+									goto done;
 								}
 								++cblk;
 								--cblkcnt;
@@ -899,7 +1027,8 @@
 	}
 
 	if (!(tile->pi = jpc_dec_pi_create(dec, tile))) {
-		return -1;
+		retval = -1;
+		goto done;
 	}
 
 	for (unsigned pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist);
@@ -910,7 +1039,13 @@
 	}
 	jpc_pi_init(tile->pi);
 
-	return 0;
+done:
+
+	if (jas_get_debug_level() >= 1) {
+		jas_logdebugf(1, "jpc_dec_tileinit returning %d\n", retval);
+	}
+
+	return retval;
 }
 
 static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile)
@@ -920,61 +1055,64 @@
 	jpc_dec_seg_t *seg;
 	jpc_dec_cblk_t *cblk;
 
-	if (tile->tcomps) {
+	if (jas_get_debug_level() >= 1) {
+		jas_logdebugf(1, "jpc_dec_tilefini called\n");
+	}
 
+	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);
+			if (tcomp->rlvls) {
+				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) {
+									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);
+										}
+										if (cblk->data) {
+											jas_matrix_destroy(cblk->data);
+										}
+									}
+									jas_free(prc->cblks);
 								}
-								jas_matrix_destroy(cblk->data);
+								if (prc->incltagtree) {
+									jpc_tagtree_destroy(prc->incltagtree);
+								}
+								if (prc->numimsbstagtree) {
+									jpc_tagtree_destroy(prc->numimsbstagtree);
+								}
 							}
-							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 (band->data) {
-						jas_matrix_destroy(band->data);
+					if (rlvl->bands) {
+						jas_free(rlvl->bands);
 					}
-					if (band->prcs) {
-						jas_free(band->prcs);
-					}
 				}
-				if (rlvl->bands) {
-					jas_free(rlvl->bands);
-				}
 			}
 			if (tcomp->rlvls) {
 				jas_free(tcomp->rlvls);
@@ -1020,7 +1158,7 @@
 	int v;
 
 	if (jpc_dec_decodecblks(dec, tile)) {
-		jas_eprintf("jpc_dec_decodecblks failed\n");
+		jas_logerrorf("jpc_dec_decodecblks failed\n");
 		return -1;
 	}
 
@@ -1065,11 +1203,11 @@
 	switch (tile->cp->mctid) {
 	case JPC_MCT_RCT:
 		if (dec->numcomps < 3) {
-			jas_eprintf("RCT requires at least three components\n");
+			jas_logerrorf("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");
+			jas_logerrorf("RCT requires all components have the same domain\n");
 			return -1;
 		}
 		jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data,
@@ -1077,11 +1215,11 @@
 		break;
 	case JPC_MCT_ICT:
 		if (dec->numcomps < 3) {
-			jas_eprintf("ICT requires at least three components\n");
+			jas_logerrorf("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");
+			jas_logerrorf("RCT requires all components have the same domain\n");
 			return -1;
 		}
 		jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data,
@@ -1154,7 +1292,7 @@
 		  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");
+			jas_logerrorf("write component failed\n");
 			return -1;
 		}
 	}
@@ -1166,8 +1304,7 @@
 {
 	jpc_dec_tile_t *tile;
 
-	/* Eliminate compiler warnings about unused variables. */
-	(void)ms;
+	JAS_UNUSED(ms);
 
 	unsigned tileno;
 	for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
@@ -1204,7 +1341,7 @@
 	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");
+		jas_logerrorf("image too large\n");
 		return -1;
 	}
 
@@ -1211,7 +1348,7 @@
 	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");
+		jas_logerrorf("tile too large\n");
 		return -1;
 	}
 
@@ -1248,18 +1385,22 @@
 		cmpt->hsubstep = 0;
 		cmpt->vsubstep = 0;
 
+		if (!cmpt->width || !cmpt->height) {
+			jas_logerrorf("image component has no samples\n");
+			return -1;
+		}
 		if (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) {
-			jas_eprintf("image too large\n");
+			jas_logerrorf("image too large\n");
 			return -1;
 		}
 		if (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) {
-			jas_eprintf("image too large\n");
+			jas_logerrorf("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",
+		jas_logerrorf("maximum number of samples exceeded (%zu > %zu)\n",
 		  num_samples, dec->max_samples);
 		return -1;
 	}
@@ -1287,8 +1428,8 @@
 		return -1;
 	}
 	dec->numtiles = size;
-	JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
-	  dec->numtiles, dec->numhtiles, dec->numvtiles));
+	JAS_LOGDEBUGF(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;
 	}
@@ -1377,7 +1518,7 @@
 	jpc_dec_tile_t *tile;
 
 	if (coc->compno >= dec->numcomps) {
-		jas_eprintf("invalid component number in COC marker segment\n");
+		jas_logerrorf("invalid component number in COC marker segment\n");
 		return -1;
 	}
 	switch (dec->state) {
@@ -1403,7 +1544,7 @@
 	jpc_dec_tile_t *tile;
 
 	if (rgn->compno >= dec->numcomps) {
-		jas_eprintf("invalid component number in RGN marker segment\n");
+		jas_logerrorf("invalid component number in RGN marker segment\n");
 		return -1;
 	}
 	switch (dec->state) {
@@ -1452,7 +1593,7 @@
 	jpc_dec_tile_t *tile;
 
 	if (qcc->compno >= dec->numcomps) {
-		jas_eprintf("invalid component number in QCC marker segment\n");
+		jas_logerrorf("invalid component number in QCC marker segment\n");
 		return -1;
 	}
 	switch (dec->state) {
@@ -1551,9 +1692,8 @@
 
 static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms)
 {
-	/* Eliminate compiler warnings about unused variables. */
-	USED(dec);
-	USED(ms);
+	JAS_UNUSED(dec);
+	JAS_UNUSED(ms);
 
 	return 0;
 }
@@ -1560,10 +1700,9 @@
 
 static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms)
 {
-	/* Eliminate compiler warnings about unused variables. */
-	USED(dec);
+	JAS_UNUSED(dec);
 
-	jas_eprintf("warning: ignoring unknown marker segment (0x%x)\n",
+	jas_logwarnf("warning: ignoring unknown marker segment (0x%x)\n",
 	  ms->id);
 	return 0;
 }
@@ -1586,6 +1725,7 @@
 	cp->numlyrs = 0;
 	cp->mctid = 0;
 	cp->csty = 0;
+	cp->pchglist = 0;
 	if (!(cp->ccps = jas_alloc2(cp->numcomps, sizeof(jpc_dec_ccp_t)))) {
 		goto error;
 	}
@@ -1694,7 +1834,11 @@
 	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)))));
+#if 0
+		jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno,
+		  ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3)
+		  : (0)))));
+#endif
 		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;
@@ -1758,8 +1902,7 @@
 {
 	int rlvlno;
 
-	/* Eliminate compiler warnings about unused variables. */
-	USED(cp);
+	JAS_UNUSED(cp);
 
 	if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) {
 		ccp->numrlvls = compparms->numdlvls + 1;
@@ -1803,8 +1946,7 @@
 {
 	int bandno;
 
-	/* Eliminate compiler warnings about unused variables. */
-	USED(cp);
+	JAS_UNUSED(cp);
 
 	/* Sanity check to prevent buffer overflow */
 	if (compparms->numstepsizes > (3 * JPC_MAXRLVLS + 1)) {
@@ -1886,7 +2028,15 @@
 	// 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);
+	// Note:
+	// Should anything special be done to handle the error case of
+	// absstepsize < 0 (which can arise due to numerical overflow).
+	// Using an assert is not appropriate, since this results in program
+	// termination when this type of error occurs.
+	// Simply allowing a decoded image with very high distortion would appear
+	// to be consistent with the policy adopted elsewhere in the codec.
+	// assert(absstepsize >= 0);
+
 	if (absstepsize == jpc_inttofix(1)) {
 		return;
 	}
@@ -1920,7 +2070,7 @@
 	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 "
+		jas_logwarnf("warning: forcing negative ROI shift to zero "
 		  "(bitstream is probably corrupt)\n");
 		roishift = 0;
 	}
@@ -1953,7 +2103,7 @@
 				  Here we ensure that any such bits are masked off. */
 				if (mag & (~mask)) {
 					if (!warn) {
-						jas_eprintf("warning: possibly corrupt code stream\n");
+						jas_logwarnf("warning: possibly corrupt code stream\n");
 						warn = true;
 					}
 					mag &= mask;
@@ -1992,7 +2142,7 @@
 	dec->cp = 0;
 	dec->maxlyrs = impopts->maxlyrs;
 	dec->maxpkts = impopts->maxpkts;
-dec->numpkts = 0;
+	dec->numpkts = 0;
 	dec->ppmseqno = 0;
 	dec->state = 0;
 	dec->cmpts = 0;
@@ -2001,6 +2151,10 @@
 	dec->curtileendoff = 0;
 	dec->max_samples = impopts->max_samples;
 
+	if (jas_get_debug_level() >= 1) {
+		jas_logdebugf(1, "debug %d\n", jas_get_debug_level());
+	}
+
 	return dec;
 }
 
@@ -2119,6 +2273,83 @@
 	jas_free(seg);
 }
 
+static int jpc_dec_dump(const jpc_dec_t *dec)
+{
+	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) {
+				jas_logprintf("RESOLUTION LEVEL %d\n", rlvlno);
+				jas_logprintf("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) {
+					jas_logprintf("BAND %d\n", bandno);
+					if (!band->data) {
+						jas_logprintf("band has no data (null pointer)\n");
+						assert(!band->prcs);
+						continue;
+					}
+					jas_logprintf("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) {
+						jas_logprintf("CODE BLOCK GROUP %d\n", prcno);
+						jas_logprintf("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) {
+							jas_logprintf("CODE BLOCK %d\n", cblkno);
+							jas_logprintf("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;
@@ -2365,4 +2596,76 @@
 		jas_free(ent->data);
 	}
 	jas_free(ent);
+}
+
+static void jpc_cblk_init(jpc_dec_cblk_t *cblk)
+{
+#if 1
+	memset(cblk, 0, sizeof(jpc_dec_cblk_t));
+	cblk->numpasses = 0;
+	jpc_seglist_init(&cblk->segs);
+	cblk->curseg = 0;
+	cblk->numimsbs = 0;
+	cblk->numlenbits = 0;
+	cblk->firstpassno = 0;
+	cblk->data = 0;
+#endif
+}
+
+static void jpc_prc_init(jpc_dec_prc_t *prc)
+{
+#if 1
+	memset(prc, 0, sizeof(jpc_dec_prc_t));
+	prc->xstart = 0;
+	prc->ystart = 0;
+	prc->xend = 0;
+	prc->yend = 0;
+	prc->numhcblks = 0;
+	prc->numvcblks = 0;
+	prc->cblks = 0;
+	prc->incltagtree = 0;
+	prc->numimsbstagtree = 0;
+#endif
+}
+
+static void jpc_band_init(jpc_dec_band_t *band)
+{
+#if 1
+	memset(band, 0, sizeof(jpc_dec_band_t));
+	band->prcs = 0;
+	band->data = 0;
+	band->orient = 0;
+	band->stepsize = 0;
+	band->absstepsize = 0;
+	band->numbps = 0;
+	band->analgain = 0;
+	band->roishift = 0;
+#endif
+}
+
+static void jpc_rlvl_init(jpc_dec_rlvl_t *rlvl)
+{
+#if 1
+	memset(rlvl, 0, sizeof(jpc_dec_rlvl_t));
+	rlvl->numbands = 0;
+	rlvl->bands = 0;
+	rlvl->xstart = 0;
+	rlvl->ystart = 0;
+	rlvl->xend = 0;
+	rlvl->yend = 0;
+	rlvl->prcwidthexpn = 0;
+	rlvl->prcheightexpn = 0;
+	rlvl->numhprcs = 0;
+	rlvl->numvprcs = 0;
+	rlvl->numprcs = 0;
+	rlvl->cbgwidthexpn = 0;
+	rlvl->cblkheightexpn = 0;
+#endif
+}
+
+static void jpc_seglist_init(jpc_dec_seglist_t *seglist)
+{
+	memset(seglist, 0, sizeof(jpc_dec_seglist_t));
+	seglist->head = 0;
+	seglist->tail = 0;
 }
--- a/jpc_dec.h
+++ b/jpc_dec.h
@@ -77,6 +77,7 @@
 #include "jasper/jas_stream.h"
 #include "jasper/jas_image.h"
 
+#include "jpc_cod.h"
 #include "jpc_tsfb.h"
 #include "jpc_tagtree.h"
 #include "jpc_cs.h"
--- /dev/null
+++ b/jpc_enc.c
@@ -1,0 +1,2665 @@
+/*
+ * 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_enc.h"
+#include "jpc_flt.h"
+#include "jpc_fix.h"
+#include "jpc_tagtree.h"
+#include "jpc_cs.h"
+#include "jpc_mct.h"
+#include "jpc_tsfb.h"
+#include "jpc_t1cod.h"
+#include "jpc_t1enc.h"
+#include "jpc_t2enc.h"
+#include "jpc_math.h"
+#include "jpc_util.h"
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_version.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define JPC_POW2(n) \
+	(1 << (n))
+
+#define JPC_FLOORTOMULTPOW2(x, n) \
+  (((n) > 0) ? ((x) & (~((1 << n) - 1))) : (x))
+/* Round to the nearest multiple of the specified power of two in the
+  direction of negative infinity. */
+
+#define	JPC_CEILTOMULTPOW2(x, n) \
+  (((n) > 0) ? JPC_FLOORTOMULTPOW2(((x) + (1 << (n)) - 1), n) : (x))
+/* Round to the nearest multiple of the specified power of two in the
+  direction of positive infinity. */
+
+#define	JPC_POW2(n)	\
+  (1 << (n))
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno);
+static void jpc_enc_tile_destroy(jpc_enc_tile_t *tile);
+
+static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
+  jas_image_t *image, jpc_enc_tile_t *tile);
+static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt);
+static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
+  jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos);
+static void rlvl_destroy(jpc_enc_rlvl_t *rlvl);
+static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
+  jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos);
+static void band_destroy(jpc_enc_band_t *bands);
+static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc,
+  jpc_enc_band_t *band);
+static void prc_destroy(jpc_enc_prc_t *prcs);
+static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk,
+  jpc_enc_prc_t *prc);
+static void cblk_destroy(jpc_enc_cblk_t *cblks);
+int ratestrtosize(const char *s, uint_fast32_t rawsize, uint_fast32_t *size);
+static void pass_destroy(jpc_enc_pass_t *pass);
+void jpc_enc_dump(jpc_enc_t *enc);
+
+void calcrdslopes(jpc_enc_cblk_t *cblk);
+void dump_layeringinfo(jpc_enc_t *enc);
+void jpc_quantize(jas_matrix_t *data, jpc_fix_t stepsize);
+jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image);
+void jpc_enc_destroy(jpc_enc_t *enc);
+static int jpc_enc_encodemainhdr(jpc_enc_t *enc);
+static int jpc_enc_encodemainbody(jpc_enc_t *enc);
+int jpc_enc_encodetiledata(jpc_enc_t *enc);
+int rateallocate(jpc_enc_t *enc, unsigned numlyrs, uint_fast32_t *cumlens);
+static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image);
+void jpc_enc_cp_destroy(jpc_enc_cp_t *cp);
+static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn);
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+typedef enum {
+	OPT_DEBUG,
+	OPT_IMGAREAOFFX,
+	OPT_IMGAREAOFFY,
+	OPT_TILEGRDOFFX,
+	OPT_TILEGRDOFFY,
+	OPT_TILEWIDTH,
+	OPT_TILEHEIGHT,
+	OPT_PRCWIDTH,
+	OPT_PRCHEIGHT,
+	OPT_CBLKWIDTH,
+	OPT_CBLKHEIGHT,
+	OPT_MODE,
+	OPT_PRG,
+	OPT_NOMCT,
+	OPT_MAXRLVLS,
+	OPT_SOP,
+	OPT_EPH,
+	OPT_LAZY,
+	OPT_TERMALL,
+	OPT_SEGSYM,
+	OPT_VCAUSAL,
+	OPT_RESET,
+	OPT_PTERM,
+	OPT_NUMGBITS,
+	OPT_RATE,
+	OPT_ILYRRATES,
+	OPT_JP2OVERHEAD
+} optid_t;
+
+typedef enum {
+	PO_L = 0,
+	PO_R
+} poid_t;
+
+typedef enum {
+	MODE_INT,
+	MODE_REAL
+} modeid_t;
+
+/******************************************************************************\
+* Data.
+\******************************************************************************/
+
+static const jas_taginfo_t encopts[] = {
+	{OPT_DEBUG, "debug"},
+	{OPT_IMGAREAOFFX, "imgareatlx"},
+	{OPT_IMGAREAOFFY, "imgareatly"},
+	{OPT_TILEGRDOFFX, "tilegrdtlx"},
+	{OPT_TILEGRDOFFY, "tilegrdtly"},
+	{OPT_TILEWIDTH, "tilewidth"},
+	{OPT_TILEHEIGHT, "tileheight"},
+	{OPT_PRCWIDTH, "prcwidth"},
+	{OPT_PRCHEIGHT, "prcheight"},
+	{OPT_CBLKWIDTH, "cblkwidth"},
+	{OPT_CBLKHEIGHT, "cblkheight"},
+	{OPT_MODE, "mode"},
+	{OPT_PRG, "prg"},
+	{OPT_NOMCT, "nomct"},
+	{OPT_MAXRLVLS, "numrlvls"},
+	{OPT_SOP, "sop"},
+	{OPT_EPH, "eph"},
+	{OPT_LAZY, "lazy"},
+	{OPT_TERMALL, "termall"},
+	{OPT_SEGSYM, "segsym"},
+	{OPT_VCAUSAL, "vcausal"},
+	{OPT_PTERM, "pterm"},
+	{OPT_RESET, "resetprob"},
+	{OPT_NUMGBITS, "numgbits"},
+	{OPT_RATE, "rate"},
+	{OPT_ILYRRATES, "ilyrrates"},
+	{OPT_JP2OVERHEAD, "_jp2overhead"},
+	{-1, 0}
+};
+
+static const jas_taginfo_t prgordtab[] = {
+	{JPC_COD_LRCPPRG, "lrcp"},
+	{JPC_COD_RLCPPRG, "rlcp"},
+	{JPC_COD_RPCLPRG, "rpcl"},
+	{JPC_COD_PCRLPRG, "pcrl"},
+	{JPC_COD_CPRLPRG, "cprl"},
+	{-1, 0}
+};
+
+static const jas_taginfo_t modetab[] = {
+	{MODE_INT, "int"},
+	{MODE_REAL, "real"},
+	{-1, 0}
+};
+
+/******************************************************************************\
+\******************************************************************************/
+
+/**
+ * @return UINT_FAST32_MAX on error
+ */
+static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn)
+{
+	int p;
+	uint_fast32_t mant;
+	uint_fast32_t expn;
+	int n;
+
+	if (absdelta < 0) {
+		return UINT_FAST32_MAX;
+	}
+
+	p = jpc_fix_firstone(absdelta) - JPC_FIX_FRACBITS;
+	n = 11 - jpc_fix_firstone(absdelta);
+	mant = ((n < 0) ? (absdelta >> (-n)) : (absdelta << n)) & 0x7ff;
+	expn = scaleexpn - p;
+	if (scaleexpn < p) {
+		return UINT_FAST32_MAX;
+	}
+	if (expn >= 0x1f)
+		return UINT_FAST32_MAX;
+	return JPC_QCX_EXPN(expn) | JPC_QCX_MANT(mant);
+}
+
+/******************************************************************************\
+* The main encoder entry point.
+\******************************************************************************/
+
+int jpc_encode(jas_image_t *image, jas_stream_t *out, const char *optstr)
+{
+	jpc_enc_t *enc;
+	jpc_enc_cp_t *cp;
+
+	enc = 0;
+
+	jpc_init();
+
+	if (!(cp = cp_create(optstr, image))) {
+		jas_logerrorf("invalid JP encoder options\n");
+		goto error;
+	}
+
+	if (!(enc = jpc_enc_create(cp, out, image))) {
+		jas_logerrorf("jpc_enc_create failed\n");
+		goto error;
+	}
+	cp = 0;
+
+	/* Encode the main header. */
+	if (jpc_enc_encodemainhdr(enc)) {
+		jas_logerrorf("cannot encode main header\n");
+		goto error;
+	}
+
+	/* Encode the main body.  This constitutes most of the encoding work. */
+	if (jpc_enc_encodemainbody(enc)) {
+		jas_logerrorf("cannot encode main body\n");
+		goto error;
+	}
+
+	/* Write EOC marker segment. */
+	if (!(enc->mrk = jpc_ms_create(JPC_MS_EOC))) {
+		jas_logerrorf("cannot create EOC marker\n");
+		goto error;
+	}
+	if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+		jas_logerrorf("cannot write EOC marker\n");
+		goto error;
+	}
+	jpc_ms_destroy(enc->mrk);
+	enc->mrk = 0;
+
+	if (jas_stream_flush(enc->out)) {
+		jas_logerrorf("stream flush failed\n");
+		goto error;
+	}
+
+	jpc_enc_destroy(enc);
+
+	return 0;
+
+error:
+	if (cp) {
+		jpc_enc_cp_destroy(cp);
+	}
+	if (enc) {
+		jpc_enc_destroy(enc);
+	}
+	jas_logerrorf("jpc_encode failed\n");
+	return -1;
+}
+
+/******************************************************************************\
+* Option parsing code.
+\******************************************************************************/
+
+static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image)
+{
+	jpc_enc_cp_t *cp;
+	jas_tvparser_t *tvp;
+	int numilyrrates;
+	double *ilyrrates;
+	int i;
+	int tagid;
+	jpc_enc_tcp_t *tcp;
+	jpc_enc_tccp_t *tccp;
+	jpc_enc_ccp_t *ccp;
+	uint_fast16_t rlvlno;
+	uint_fast16_t prcwidthexpn;
+	uint_fast16_t prcheightexpn;
+	bool enablemct;
+	uint_fast32_t jp2overhead;
+	uint_fast16_t lyrno;
+	uint_fast32_t hsteplcm;
+	uint_fast32_t vsteplcm;
+	bool mctvalid;
+
+	tvp = 0;
+	ilyrrates = 0;
+	numilyrrates = 0;
+
+	if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) {
+		goto error;
+	}
+
+	prcwidthexpn = 15;
+	prcheightexpn = 15;
+	enablemct = true;
+	jp2overhead = 0;
+
+	cp->ccps = 0;
+	cp->debug = 0;
+	cp->imgareatlx = UINT_FAST32_MAX;
+	cp->imgareatly = UINT_FAST32_MAX;
+	cp->refgrdwidth = 0;
+	cp->refgrdheight = 0;
+	cp->tilegrdoffx = UINT_FAST32_MAX;
+	cp->tilegrdoffy = UINT_FAST32_MAX;
+	cp->tilewidth = 0;
+	cp->tileheight = 0;
+	cp->numcmpts = jas_image_numcmpts(image);
+	cp->tcp.ilyrrates = NULL;
+
+	hsteplcm = 1;
+	vsteplcm = 1;
+	for (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
+		if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <=
+		  jas_image_brx(image) || jas_image_cmptbry(image, cmptno) +
+		  jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) {
+			jas_logerrorf("unsupported image type\n");
+			goto error;
+		}
+		/* Note: We ought to be calculating the LCMs here.  Fix some day. */
+		hsteplcm *= jas_image_cmpthstep(image, cmptno);
+		vsteplcm *= jas_image_cmptvstep(image, cmptno);
+	}
+
+	if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) {
+		goto error;
+	}
+	unsigned cmptno;
+	for (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno,
+	  ++ccp) {
+		ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno);
+		ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno);
+		/* XXX - this isn't quite correct for more general image */
+		ccp->sampgrdsubstepx = 0;
+		ccp->sampgrdsubstepx = 0;
+		ccp->prec = jas_image_cmptprec(image, cmptno);
+		ccp->sgnd = jas_image_cmptsgnd(image, cmptno);
+		ccp->numstepsizes = 0;
+		memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes));
+	}
+
+	cp->rawsize = jas_image_rawsize(image);
+	if (cp->rawsize == 0) {
+		/* prevent division by zero in cp_create() */
+		goto error;
+	}
+	cp->totalsize = UINT_FAST32_MAX;
+
+	tcp = &cp->tcp;
+	tcp->csty = 0;
+	tcp->intmode = true;
+	tcp->prg = JPC_COD_LRCPPRG;
+	tcp->numlyrs = 1;
+	tcp->ilyrrates = 0;
+
+	tccp = &cp->tccp;
+	tccp->csty = 0;
+	tccp->maxrlvls = 6;
+	tccp->cblkwidthexpn = 6;
+	tccp->cblkheightexpn = 6;
+	tccp->cblksty = 0;
+	tccp->numgbits = 2;
+
+	if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
+		goto error;
+	}
+
+	while (!jas_tvparser_next(tvp)) {
+		switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts,
+		  jas_tvparser_gettag(tvp)))->id) {
+		case OPT_DEBUG:
+			cp->debug = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_IMGAREAOFFX:
+			cp->imgareatlx = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_IMGAREAOFFY:
+			cp->imgareatly = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_TILEGRDOFFX:
+			cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_TILEGRDOFFY:
+			cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_TILEWIDTH:
+			cp->tilewidth = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_TILEHEIGHT:
+			cp->tileheight = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_PRCWIDTH:
+			prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
+			break;
+		case OPT_PRCHEIGHT:
+			prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
+			break;
+		case OPT_CBLKWIDTH:
+			tccp->cblkwidthexpn =
+			  jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
+			break;
+		case OPT_CBLKHEIGHT:
+			tccp->cblkheightexpn =
+			  jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
+			break;
+		case OPT_MODE:
+			if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab,
+			  jas_tvparser_getval(tvp)))->id) < 0) {
+				jas_logwarnf("ignoring invalid mode %s\n",
+				  jas_tvparser_getval(tvp));
+			} else {
+				tcp->intmode = (tagid == MODE_INT);
+			}
+			break;
+		case OPT_PRG:
+			if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab,
+			  jas_tvparser_getval(tvp)))->id) < 0) {
+				jas_logwarnf("ignoring invalid progression order %s\n",
+				  jas_tvparser_getval(tvp));
+			} else {
+				tcp->prg = tagid;
+			}
+			break;
+		case OPT_NOMCT:
+			enablemct = false;
+			break;
+		case OPT_MAXRLVLS:
+			tccp->maxrlvls = atoi(jas_tvparser_getval(tvp));
+			if (tccp->maxrlvls > JPC_MAXRLVLS) {
+				jas_logerrorf("number of resolution levels exceeds maximum %d\n",
+				  JPC_MAXRLVLS);
+				goto error;
+			}
+			break;
+		case OPT_SOP:
+			cp->tcp.csty |= JPC_COD_SOP;
+			break;
+		case OPT_EPH:
+			cp->tcp.csty |= JPC_COD_EPH;
+			break;
+		case OPT_LAZY:
+			tccp->cblksty |= JPC_COX_LAZY;
+			break;
+		case OPT_TERMALL:
+			tccp->cblksty |= JPC_COX_TERMALL;
+			break;
+		case OPT_SEGSYM:
+			tccp->cblksty |= JPC_COX_SEGSYM;
+			break;
+		case OPT_VCAUSAL:
+			tccp->cblksty |= JPC_COX_VSC;
+			break;
+		case OPT_RESET:
+			tccp->cblksty |= JPC_COX_RESET;
+			break;
+		case OPT_PTERM:
+			tccp->cblksty |= JPC_COX_PTERM;
+			break;
+		case OPT_NUMGBITS:
+			cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));
+			break;
+		case OPT_RATE:
+			if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
+			  &cp->totalsize)) {
+				jas_logwarnf("ignoring bad rate specifier %s\n",
+				  jas_tvparser_getval(tvp));
+			}
+			break;
+		case OPT_ILYRRATES:
+			if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,
+			  &ilyrrates)) {
+				jas_logwarnf("warning: invalid intermediate layer rates specifier ignored (%s)\n",
+				  jas_tvparser_getval(tvp));
+			}
+			break;
+
+		case OPT_JP2OVERHEAD:
+			jp2overhead = atoi(jas_tvparser_getval(tvp));
+			break;
+		default:
+			jas_logwarnf("warning: ignoring invalid option %s\n",
+			 jas_tvparser_gettag(tvp));
+			break;
+		}
+	}
+
+	jas_tvparser_destroy(tvp);
+	tvp = 0;
+
+	if (cp->totalsize != UINT_FAST32_MAX) {
+		cp->totalsize = (cp->totalsize > jp2overhead) ?
+		  (cp->totalsize - jp2overhead) : 0;
+	}
+
+	if (cp->imgareatlx == UINT_FAST32_MAX) {
+		cp->imgareatlx = 0;
+	} else {
+		if (hsteplcm != 1) {
+			jas_logwarnf("warning: overriding imgareatlx value\n");
+		}
+		cp->imgareatlx *= hsteplcm;
+	}
+	if (cp->imgareatly == UINT_FAST32_MAX) {
+		cp->imgareatly = 0;
+	} else {
+		if (vsteplcm != 1) {
+			jas_logwarnf("warning: overriding imgareatly value\n");
+		}
+		cp->imgareatly *= vsteplcm;
+	}
+	cp->refgrdwidth = cp->imgareatlx + jas_image_width(image);
+	cp->refgrdheight = cp->imgareatly + jas_image_height(image);
+	if (cp->tilegrdoffx == UINT_FAST32_MAX) {
+		cp->tilegrdoffx = cp->imgareatlx;
+	}
+	if (cp->tilegrdoffy == UINT_FAST32_MAX) {
+		cp->tilegrdoffy = cp->imgareatly;
+	}
+	if (!cp->tilewidth) {
+		cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx;
+	}
+	if (!cp->tileheight) {
+		cp->tileheight = cp->refgrdheight - cp->tilegrdoffy;
+	}
+
+	if (cp->numcmpts == 3) {
+		mctvalid = true;
+		for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
+			if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) ||
+			  jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) ||
+			  jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) ||
+			  jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) {
+				mctvalid = false;
+			}
+		}
+	} else {
+		mctvalid = false;
+	}
+	if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) {
+		jas_logwarnf("warning: color space apparently not RGB\n");
+	}
+	if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) {
+		tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT);
+	} else {
+		tcp->mctid = JPC_MCT_NONE;
+	}
+	tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS);
+
+	for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
+		tccp->prcwidthexpns[rlvlno] = prcwidthexpn;
+		tccp->prcheightexpns[rlvlno] = prcheightexpn;
+	}
+	if (prcwidthexpn != 15 || prcheightexpn != 15) {
+		tccp->csty |= JPC_COX_PRT;
+	}
+
+	/* Ensure that the tile width and height is valid. */
+	if (!cp->tilewidth) {
+		jas_logerrorf("invalid tile width %lu\n", (unsigned long)
+		  cp->tilewidth);
+		goto error;
+	}
+	if (!cp->tileheight) {
+		jas_logerrorf("invalid tile height %lu\n", (unsigned long)
+		  cp->tileheight);
+		goto error;
+	}
+
+	/* Ensure that the tile grid offset is valid. */
+	if (cp->tilegrdoffx > cp->imgareatlx ||
+	  cp->tilegrdoffy > cp->imgareatly ||
+	  cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx ||
+	  cp->tilegrdoffy + cp->tileheight < cp->imgareatly) {
+		jas_logerrorf("invalid tile grid offset (%lu, %lu)\n",
+		  (unsigned long) cp->tilegrdoffx, (unsigned long)
+		  cp->tilegrdoffy);
+		goto error;
+	}
+
+	cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx,
+	  cp->tilewidth);
+	cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy,
+	  cp->tileheight);
+	cp->numtiles = cp->numhtiles * cp->numvtiles;
+
+	if (ilyrrates && numilyrrates > 0) {
+		tcp->numlyrs = numilyrrates + 1;
+		if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1),
+		  sizeof(jpc_fix_t)))) {
+			goto error;
+		}
+		for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) {
+			tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]);
+		}
+	}
+
+	/* Ensure that the integer mode is used in the case of lossless
+	  coding. */
+	if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) {
+		jas_logerrorf("cannot use real mode for lossless coding\n");
+		goto error;
+	}
+
+	/* Ensure that the precinct width is valid. */
+	if (prcwidthexpn > 15) {
+		jas_logerrorf("invalid precinct width\n");
+		goto error;
+	}
+
+	/* Ensure that the precinct height is valid. */
+	if (prcheightexpn > 15) {
+		jas_logerrorf("invalid precinct height\n");
+		goto error;
+	}
+
+	/* Ensure that the code block width is valid. */
+	if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) {
+		jas_logerrorf("invalid code block width %d\n",
+		  JPC_POW2(cp->tccp.cblkwidthexpn));
+		goto error;
+	}
+
+	/* Ensure that the code block height is valid. */
+	if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) {
+		jas_logerrorf("invalid code block height %d\n",
+		  JPC_POW2(cp->tccp.cblkheightexpn));
+		goto error;
+	}
+
+	/* Ensure that the code block size is not too large. */
+	if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) {
+		jas_logerrorf("code block size too large\n");
+		goto error;
+	}
+
+	/* Ensure that the number of layers is valid. */
+	if (cp->tcp.numlyrs > 16384) {
+		jas_logerrorf("too many layers\n");
+		goto error;
+	}
+
+	/* There must be at least one resolution level. */
+	if (cp->tccp.maxrlvls < 1) {
+		jas_logerrorf("must be at least one resolution level\n");
+		goto error;
+	}
+
+	/* Ensure that the number of guard bits is valid. */
+	if (cp->tccp.numgbits > 8) {
+		jas_logerrorf("invalid number of guard bits\n");
+		goto error;
+	}
+
+	/* Ensure that the rate is within the legal range. */
+	if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) {
+		jas_logwarnf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize);
+	}
+
+	/* Ensure that the intermediate layer rates are valid. */
+	if (tcp->numlyrs > 1) {
+		/* The intermediate layers rates must increase monotonically. */
+		for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {
+			if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {
+				jas_logerrorf("intermediate layer rates must increase monotonically\n");
+				goto error;
+			}
+		}
+		/* The intermediate layer rates must be less than the overall rate. */
+		if (cp->totalsize != UINT_FAST32_MAX) {
+			for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {
+				if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize)
+				  / cp->rawsize) {
+					jas_logerrorf("warning: intermediate layer rates must be less than overall rate\n");
+					goto error;
+				}
+			}
+		}
+	}
+
+	if (ilyrrates) {
+		jas_free(ilyrrates);
+	}
+
+	return cp;
+
+error:
+
+	if (ilyrrates) {
+		jas_free(ilyrrates);
+	}
+	if (tvp) {
+		jas_tvparser_destroy(tvp);
+	}
+	if (cp) {
+		jpc_enc_cp_destroy(cp);
+	}
+	return 0;
+}
+
+void jpc_enc_cp_destroy(jpc_enc_cp_t *cp)
+{
+	if (cp->ccps) {
+		if (cp->tcp.ilyrrates) {
+			jas_free(cp->tcp.ilyrrates);
+		}
+		jas_free(cp->ccps);
+	}
+	jas_free(cp);
+}
+
+int ratestrtosize(const char *s, uint_fast32_t rawsize, uint_fast32_t *size)
+{
+	jpc_flt_t f;
+
+	/* Note: This function must not modify output size on failure. */
+	if (strchr(s, 'B')) {
+		*size = atoi(s);
+	} else {
+		f = atof(s);
+		if (f < 0) {
+			*size = 0;
+		} else if (f > 1.0) {
+			*size = rawsize + 1;
+		} else {
+			*size = f * rawsize;
+		}
+	}
+	return 0;
+}
+
+/******************************************************************************\
+* Encoder constructor and destructor.
+\******************************************************************************/
+
+jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image)
+{
+	jpc_enc_t *enc;
+
+	if (!(enc = jas_malloc(sizeof(jpc_enc_t)))) {
+		goto error;
+	}
+
+	enc->image = image;
+	enc->out = out;
+	enc->cp = cp;
+	enc->cstate = 0;
+	enc->tmpstream = 0;
+	enc->mrk = 0;
+	enc->curtile = 0;
+
+	if (!(enc->cstate = jpc_cstate_create())) {
+		goto error;
+	}
+	enc->len = 0;
+	enc->mainbodysize = 0;
+
+	return enc;
+
+error:
+
+	if (enc) {
+		jpc_enc_destroy(enc);
+	}
+	return 0;
+}
+
+void jpc_enc_destroy(jpc_enc_t *enc)
+{
+	/* The image object (i.e., enc->image) and output stream object
+	(i.e., enc->out) are created outside of the encoder.
+	Therefore, they must not be destroyed here. */
+
+	if (enc->curtile) {
+		jpc_enc_tile_destroy(enc->curtile);
+	}
+	if (enc->cp) {
+		jpc_enc_cp_destroy(enc->cp);
+	}
+	if (enc->cstate) {
+		jpc_cstate_destroy(enc->cstate);
+	}
+	if (enc->tmpstream) {
+		jas_stream_close(enc->tmpstream);
+	}
+	if (enc->mrk) {
+		jpc_ms_destroy(enc->mrk);
+	}
+
+	jas_free(enc);
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+static int jpc_enc_encodemainhdr(jpc_enc_t *enc)
+{
+	jpc_siz_t *siz;
+	jpc_cod_t *cod;
+	jpc_qcd_t *qcd;
+	int i;
+	long startoff;
+	long mainhdrlen;
+	jpc_enc_cp_t *cp;
+	jpc_qcc_t *qcc;
+	jpc_enc_tccp_t *tccp;
+	uint_fast16_t cmptno;
+	jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
+	jpc_enc_tcp_t *tcp;
+	jpc_tsfb_t *tsfb;
+	jpc_tsfb_band_t *bandinfo;
+	uint_fast16_t numbands;
+	uint_fast16_t bandno;
+	uint_fast16_t rlvlno;
+	uint_fast16_t analgain;
+	jpc_fix_t absstepsize;
+	char buf[1024];
+	jpc_com_t *com;
+
+	cp = enc->cp;
+
+	startoff = jas_stream_getrwcount(enc->out);
+
+	/* Write SOC marker segment. */
+	if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
+		jas_logerrorf("cannot create SOC marker\n");
+		return -1;
+	}
+	if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+		jas_logerrorf("cannot write SOC marker\n");
+		return -1;
+	}
+	jpc_ms_destroy(enc->mrk);
+	enc->mrk = 0;
+
+	/* Write SIZ marker segment. */
+	if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
+		jas_logerrorf("cannot create SIZ marker\n");
+		return -1;
+	}
+	siz = &enc->mrk->parms.siz;
+	siz->caps = 0;
+	siz->xoff = cp->imgareatlx;
+	siz->yoff = cp->imgareatly;
+	siz->width = cp->refgrdwidth;
+	siz->height = cp->refgrdheight;
+	siz->tilexoff = cp->tilegrdoffx;
+	siz->tileyoff = cp->tilegrdoffy;
+	siz->tilewidth = cp->tilewidth;
+	siz->tileheight = cp->tileheight;
+	siz->numcomps = cp->numcmpts;
+	siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t));
+	assert(siz->comps);
+	for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
+		siz->comps[i].prec = cp->ccps[i].prec;
+		siz->comps[i].sgnd = cp->ccps[i].sgnd;
+		siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
+		siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
+	}
+	if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+		jas_logerrorf("cannot write SIZ marker\n");
+		return -1;
+	}
+	jpc_ms_destroy(enc->mrk);
+	enc->mrk = 0;
+
+	if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
+		jas_logerrorf("cannot create COM marker\n");
+		return -1;
+	}
+	sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
+	com = &enc->mrk->parms.com;
+	com->len = JAS_CAST(uint_fast16_t, strlen(buf));
+	com->regid = JPC_COM_LATIN;
+	if (!(com->data = JAS_CAST(jas_uchar *, jas_strdup(buf)))) {
+		return -1;
+	}
+	if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+		jas_logerrorf("cannot write COM marker\n");
+		return -1;
+	}
+	jpc_ms_destroy(enc->mrk);
+	enc->mrk = 0;
+
+#if 0
+	if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
+		return -1;
+	}
+	crg = &enc->mrk->parms.crg;
+	crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t));
+	if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+		jas_logerrorf("cannot write CRG marker\n");
+		return -1;
+	}
+	jpc_ms_destroy(enc->mrk);
+	enc->mrk = 0;
+#endif
+
+	tcp = &cp->tcp;
+	tccp = &cp->tccp;
+	for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
+		tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
+		jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
+		  bandinfos);
+		jpc_tsfb_destroy(tsfb);
+		numbands = 3 * tccp->maxrlvls - 2;
+		for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
+		  ++bandno, ++bandinfo) {
+			rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
+			analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
+			  rlvlno, bandinfo->orient);
+			if (!tcp->intmode) {
+				absstepsize = jpc_fix_div(jpc_inttofix(1 <<
+				  (analgain + 1)), bandinfo->synenergywt);
+			} else {
+				absstepsize = jpc_inttofix(1);
+			}	
+			const uint_fast32_t stepsize =
+			  jpc_abstorelstepsize(absstepsize,
+			  cp->ccps[cmptno].prec + analgain);
+			if (stepsize == UINT_FAST32_MAX)
+				return -1;
+			cp->ccps[cmptno].stepsizes[bandno] = stepsize;
+		}
+		cp->ccps[cmptno].numstepsizes = numbands;
+	}
+
+	if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
+		jas_logerrorf("cannot create COD marker\n");
+		return -1;
+	}
+	cod = &enc->mrk->parms.cod;
+	cod->csty = cp->tccp.csty | cp->tcp.csty;
+	cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
+	cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
+	cod->compparms.numrlvls = cp->tccp.maxrlvls;
+	cod->prg = cp->tcp.prg;
+	cod->numlyrs = cp->tcp.numlyrs;
+	cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
+	cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
+	cod->compparms.cblksty = cp->tccp.cblksty;
+	cod->compparms.qmfbid = cp->tccp.qmfbid;
+	cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
+	if (tccp->csty & JPC_COX_PRT) {
+		for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
+			cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];
+			cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];
+		}
+	}
+	if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+		jas_logerrorf("cannot write COD marker\n");
+		return -1;
+	}
+	jpc_ms_destroy(enc->mrk);
+	enc->mrk = 0;
+
+	if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
+		jas_logerrorf("cannot create QCD marker\n");
+		return -1;
+	}
+	qcd = &enc->mrk->parms.qcd;
+	qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
+	  JPC_QCX_SEQNT : JPC_QCX_NOQNT;
+	qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
+	qcd->compparms.numguard = cp->tccp.numgbits;
+	qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
+	if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+		jas_logerrorf("cannot write marker\n");
+		return -1;
+	}
+	/* We do not want the step size array to be freed! */
+	qcd->compparms.stepsizes = 0;
+	jpc_ms_destroy(enc->mrk);
+	enc->mrk = 0;
+
+	tccp = &cp->tccp;
+	for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
+		if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
+			jas_logerrorf("cannot create QCC marker\n");
+			return -1;
+		}
+		qcc = &enc->mrk->parms.qcc;
+		qcc->compno = cmptno;
+		qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
+		  JPC_QCX_SEQNT : JPC_QCX_NOQNT;
+		qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
+		qcc->compparms.numguard = cp->tccp.numgbits;
+		qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
+		if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+			jas_logerrorf("cannot write marker\n");
+			return -1;
+		}
+		/* We do not want the step size array to be freed! */
+		qcc->compparms.stepsizes = 0;
+		jpc_ms_destroy(enc->mrk);
+		enc->mrk = 0;
+	}
+
+#define MAINTLRLEN	2
+	mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
+	enc->len += mainhdrlen;
+	if (enc->cp->totalsize != UINT_FAST32_MAX) {
+		uint_fast32_t overhead;
+		overhead = mainhdrlen + MAINTLRLEN;
+		enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
+		  (enc->cp->totalsize - overhead) : 0;
+	} else {
+		enc->mainbodysize = UINT_FAST32_MAX;
+	}
+
+	return 0;
+}
+
+static int jpc_enc_encodemainbody(jpc_enc_t *enc)
+{
+	int tileno;
+	jpc_sot_t *sot;
+	jpc_enc_tcmpt_t *comp;
+	jpc_enc_tcmpt_t *endcomps;
+	jpc_enc_band_t *band;
+	jpc_enc_band_t *endbands;
+	jpc_enc_rlvl_t *lvl;
+	unsigned rlvlno;
+	jpc_qcc_t *qcc;
+	jpc_cod_t *cod;
+	int adjust;
+	int absbandno;
+	long tilehdrlen;
+	long tilelen;
+	jpc_enc_tile_t *tile;
+	jpc_enc_cp_t *cp;
+	double rho;
+	unsigned cmptno;
+	int samestepsizes;
+	jpc_enc_ccp_t *ccps;
+	jpc_enc_tccp_t *tccp;
+	int bandno;
+	int mingbits;
+	int actualnumbps;
+	jpc_fix_t mxmag;
+	jpc_fix_t mag;
+	int numgbits;
+
+	cp = enc->cp;
+
+	for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) {
+		if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image,
+		  tileno))) {
+			jas_logerrorf("cannot create tile\n");
+			return -1;
+		}
+
+		tile = enc->curtile;
+
+		if (jas_get_debug_level() >= 10) {
+			jpc_enc_dump(enc);
+		}
+
+		for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) {
+			if (!cp->ccps[cmptno].sgnd) {
+				adjust = 1 << (cp->ccps[cmptno].prec - 1);
+				for (jas_matind_t i = 0; i < jas_matrix_numrows(comp->data); ++i) {
+					for (jas_matind_t j = 0; j < jas_matrix_numcols(comp->data); ++j) {
+						*jas_matrix_getref(comp->data, i, j) -= adjust;
+					}
+				}
+			}
+		}
+
+		if (!tile->intmode) {
+				endcomps = &tile->tcmpts[tile->numtcmpts];
+				for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+					jas_matrix_asl(comp->data, JPC_FIX_FRACBITS);
+				}
+		}
+
+		switch (tile->mctid) {
+		case JPC_MCT_RCT:
+assert(jas_image_numcmpts(enc->image) == 3);
+			jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,
+			  tile->tcmpts[2].data);
+			break;
+		case JPC_MCT_ICT:
+assert(jas_image_numcmpts(enc->image) == 3);
+			jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,
+			  tile->tcmpts[2].data);
+			break;
+		default:
+			break;
+		}
+
+		for (unsigned  i = 0; i < jas_image_numcmpts(enc->image); ++i) {
+			comp = &tile->tcmpts[i];
+			jpc_tsfb_analyze(comp->tsfb, comp->data);
+
+		}
+
+
+		endcomps = &tile->tcmpts[tile->numtcmpts];
+		for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) {
+			mingbits = 0;
+			absbandno = 0;
+			/* All bands must have a corresponding quantizer step size,
+			  even if they contain no samples and are never coded. */
+			/* Some bands may not be hit by the loop below, so we must
+			  initialize all of the step sizes to a sane value. */
+			memset(comp->stepsizes, 0, sizeof(comp->stepsizes));
+			for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) {
+				if (!lvl->bands) {
+					absbandno += rlvlno ? 3 : 1;
+					continue;
+				}
+				endbands = &lvl->bands[lvl->numbands];
+				for (band = lvl->bands; band != endbands; ++band) {
+					if (!band->data) {
+						++absbandno;
+						continue;
+					}
+					mxmag = 0;
+					for (jas_matind_t y = 0; y < jas_matrix_numrows(band->data); ++y) {
+						for (jas_matind_t x = 0; x < jas_matrix_numcols(band->data); ++x) {
+							mag = JAS_ABS(jas_matrix_get(band->data, y, x));
+							if (mag > mxmag) {
+								mxmag = mag;
+							}
+						}
+					}
+					if (tile->intmode) {
+						actualnumbps = jpc_fix_firstone(mxmag) + 1;
+					} else {
+						actualnumbps = jpc_fix_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
+					}
+					numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +
+					  band->analgain);
+#if 0
+					jas_eprintf("%d %d mag=%d actual=%d numgbits=%d\n",
+					  cp->ccps[cmptno].prec, band->analgain, mxmag,
+					  actualnumbps, numgbits);
+#endif
+					if (numgbits > mingbits) {
+						mingbits = numgbits;
+					}
+					if (!tile->intmode) {
+						band->absstepsize = jpc_fix_div(jpc_inttofix(1
+						  << (band->analgain + 1)),
+						  band->synweight);
+					} else {
+						band->absstepsize = jpc_inttofix(1);
+					}
+					const uint_fast32_t stepsize = jpc_abstorelstepsize(
+					  band->absstepsize, cp->ccps[cmptno].prec +
+					  band->analgain);
+					if (stepsize == UINT_FAST32_MAX)
+						return -1;
+					band->stepsize = stepsize;
+					band->numbps = cp->tccp.numgbits +
+					  JPC_QCX_GETEXPN(band->stepsize) - 1;
+
+					if ((!tile->intmode) && band->data) {
+						jpc_quantize(band->data, band->absstepsize);
+					}
+
+					comp->stepsizes[absbandno] = band->stepsize;
+					++absbandno;
+				}
+			}
+
+			assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);
+			if (!tile->intmode) {
+				jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);
+			} else {
+				jas_matrix_asl(comp->data, JPC_NUMEXTRABITS);
+			}
+
+#if 0
+			jas_eprintf("numgbits %d mingbits %d\n", cp->tccp.numgbits,
+			  mingbits);
+#endif
+			if (mingbits > cp->tccp.numgbits) {
+				jas_logerrorf("error: too few guard bits (%d < %d)\n",
+				  cp->tccp.numgbits, mingbits);
+				return -1;
+			}
+		}
+
+		if (!(enc->tmpstream = jas_stream_memopen(0, 0))) {
+			jas_logerrorf("cannot open tmp file\n");
+			return -1;
+		}
+
+		/* Write the tile header. */
+		if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) {
+			return -1;
+		}
+		sot = &enc->mrk->parms.sot;
+		sot->len = 0;
+		sot->tileno = tileno;
+		sot->partno = 0;
+		sot->numparts = 1;
+		if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+			jas_logerrorf("cannot write SOT marker\n");
+			return -1;
+		}
+		jpc_ms_destroy(enc->mrk);
+		enc->mrk = 0;
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+		tccp = &cp->tccp;
+		for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
+			comp = &tile->tcmpts[cmptno];
+			if (comp->numrlvls != tccp->maxrlvls) {
+				if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
+					return -1;
+				}
+/* XXX = this is not really correct. we are using comp #0's precint sizes
+and other characteristics */
+				comp = &tile->tcmpts[0];
+				cod = &enc->mrk->parms.cod;
+				cod->compparms.csty = 0;
+				cod->compparms.numdlvls = comp->numrlvls - 1;
+				cod->prg = tile->prg;
+				cod->numlyrs = tile->numlyrs;
+				cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn);
+				cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn);
+				cod->compparms.cblksty = comp->cblksty;
+				cod->compparms.qmfbid = comp->qmfbid;
+				cod->mctrans = (tile->mctid != JPC_MCT_NONE);
+				for (unsigned i = 0; i < comp->numrlvls; ++i) {
+					cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn;
+					cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn;
+				}
+				if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+					return -1;
+				}
+				jpc_ms_destroy(enc->mrk);
+				enc->mrk = 0;
+			}
+		}
+
+		for (cmptno = 0, comp = tile->tcmpts; cmptno < cp->numcmpts; ++cmptno, ++comp) {
+			ccps = &cp->ccps[cmptno];
+			if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) {
+				samestepsizes = 1;
+				for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes);
+				  ++bandno) {
+					if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {
+						samestepsizes = 0;
+						break;
+					}
+				}
+			} else {
+				samestepsizes = 0;
+			}
+			if (!samestepsizes) {
+				if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
+					return -1;
+				}
+				qcc = &enc->mrk->parms.qcc;
+				qcc->compno = cmptno;
+				qcc->compparms.numguard = cp->tccp.numgbits;
+				qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?
+				  JPC_QCX_SEQNT : JPC_QCX_NOQNT;
+				qcc->compparms.numstepsizes = comp->numstepsizes;
+				qcc->compparms.stepsizes = comp->stepsizes;
+				if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+					return -1;
+				}
+				qcc->compparms.stepsizes = 0;
+				jpc_ms_destroy(enc->mrk);
+				enc->mrk = 0;
+			}
+		}
+
+		/* Write a SOD marker to indicate the end of the tile header. */
+		if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {
+			return -1;
+		}
+		if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+			jas_logerrorf("cannot write SOD marker\n");
+			return -1;
+		}
+		jpc_ms_destroy(enc->mrk);
+		enc->mrk = 0;
+		tilehdrlen = jas_stream_getrwcount(enc->tmpstream);
+		assert(tilehdrlen >= 0);
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+		if (jpc_enc_enccblks(enc)) {
+			return -1;
+		}
+
+		cp = enc->cp;
+		rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) /
+		  ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -
+		  cp->imgareatly));
+		tile->rawsize = cp->rawsize * rho;
+
+		for (unsigned lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) {
+			tile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl(
+			  cp->tcp.ilyrrates[lyrno]);
+		}
+
+		if (cp->totalsize != UINT_FAST32_MAX) {
+			tile->lyrsizes[tile->numlyrs - 1] = (rho * enc->mainbodysize);
+		} else {
+			tile->lyrsizes[tile->numlyrs - 1] = UINT_FAST32_MAX;
+		}
+
+#if 0
+		jas_eprintf("TESTING %ld %ld\n", cp->totalsize != UINT_FAST32_MAX,
+		  tile->lyrsizes[0]);
+#endif
+		for (unsigned lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
+			if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) {
+				if (JAS_CAST(uint_fast32_t, tilehdrlen) <= tile->lyrsizes[lyrno]) {
+					tile->lyrsizes[lyrno] -= tilehdrlen;
+				} else {
+					tile->lyrsizes[lyrno] = 0;
+				}
+			}
+		}
+
+		if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) {
+			return -1;
+		}
+
+#if 0
+		jas_eprintf("ENCODE TILE DATA\n");
+#endif
+		if (jpc_enc_encodetiledata(enc)) {
+			jas_logerrorf("dotile failed\n");
+			return -1;
+		}
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+		tilelen = jas_stream_tell(enc->tmpstream);
+
+		if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {
+			return -1;
+		}
+		jpc_putuint32(enc->tmpstream, tilelen);
+
+		if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {
+			return -1;
+		}
+		if (jpc_putdata(enc->out, enc->tmpstream, -1)) {
+			return -1;
+		}
+		enc->len += tilelen;
+
+		jas_stream_close(enc->tmpstream);
+		enc->tmpstream = 0;
+
+		jpc_enc_tile_destroy(enc->curtile);
+		enc->curtile = 0;
+
+	}
+
+	return 0;
+}
+
+int jpc_enc_encodetiledata(jpc_enc_t *enc)
+{
+assert(enc->tmpstream);
+	if (jpc_enc_encpkts(enc, enc->tmpstream)) {
+		return -1;
+	}
+	return 0;
+}
+
+void jpc_quantize(jas_matrix_t *data, jpc_fix_t stepsize)
+{
+	jpc_fix_t t;
+
+	if (stepsize == jpc_inttofix(1)) {
+		return;
+	}
+
+	for (jas_matind_t i = 0; i < jas_matrix_numrows(data); ++i) {
+		for (jas_matind_t j = 0; j < jas_matrix_numcols(data); ++j) {
+			t = jas_matrix_get(data, i, j);
+
+{
+	if (t < 0) {
+		t = jpc_fix_neg(jpc_fix_div(jpc_fix_neg(t), stepsize));
+	} else {
+		t = jpc_fix_div(t, stepsize);
+	}
+}
+
+			jas_matrix_set(data, i, j, t);
+		}
+	}
+}
+
+void calcrdslopes(jpc_enc_cblk_t *cblk)
+{
+	jpc_enc_pass_t *endpasses;
+	jpc_enc_pass_t *pass0;
+	jpc_enc_pass_t *pass1;
+	jpc_enc_pass_t *pass2;
+	jpc_flt_t slope0;
+	jpc_flt_t slope;
+	jpc_flt_t dd;
+	long dr;
+
+	endpasses = &cblk->passes[cblk->numpasses];
+	pass2 = cblk->passes;
+	slope0 = 0;
+	while (pass2 != endpasses) {
+		pass0 = 0;
+		for (pass1 = cblk->passes; pass1 != endpasses; ++pass1) {
+			dd = pass1->cumwmsedec;
+			dr = pass1->end;
+			if (pass0) {
+				dd -= pass0->cumwmsedec;
+				dr -= pass0->end;
+			}
+			if (dd <= 0) {
+				pass1->rdslope = JPC_BADRDSLOPE;
+				if (pass1 >= pass2) {
+					pass2 = &pass1[1];
+				}
+				continue;
+			}
+			if (pass1 < pass2 && pass1->rdslope <= 0) {
+				continue;
+			}
+			if (!dr) {
+				assert(pass0);
+				pass0->rdslope = 0;
+				break;
+			}
+			slope = dd / dr;
+			if (pass0 && slope >= slope0) {
+				pass0->rdslope = 0;
+				break;
+			}
+			pass1->rdslope = slope;
+			if (pass1 >= pass2) {
+				pass2 = &pass1[1];
+			}
+			pass0 = pass1;
+			slope0 = slope;
+		}
+	}
+
+#if 0
+	for (pass0 = cblk->passes; pass0 != endpasses; ++pass0) {
+if (pass0->rdslope > 0.0) {
+		jas_eprintf("pass %02d nmsedec=%lf dec=%lf end=%d %lf\n", pass0 - cblk->passes,
+		  fixtodbl(pass0->nmsedec), pass0->wmsedec, pass0->end, pass0->rdslope);
+}
+	}
+#endif
+}
+
+void dump_layeringinfo(jpc_enc_t *enc)
+{
+
+	jpc_enc_tcmpt_t *tcmpt;
+	unsigned tcmptno;
+	jpc_enc_rlvl_t *rlvl;
+	unsigned rlvlno;
+	jpc_enc_band_t *band;
+	unsigned bandno;
+	jpc_enc_prc_t *prc;
+	unsigned prcno;
+	jpc_enc_cblk_t *cblk;
+	unsigned cblkno;
+	jpc_enc_pass_t *pass;
+	unsigned passno;
+	jpc_enc_tile_t *tile;
+
+	tile = enc->curtile;
+
+	for (unsigned lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
+		jas_loginfof("lyrno = %02u\n", lyrno);
+		for (tcmptno = 0, tcmpt = tile->tcmpts; tcmptno < tile->numtcmpts;
+		  ++tcmptno, ++tcmpt) {
+			for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+			  ++rlvlno, ++rlvl) {
+				if (!rlvl->bands) {
+					continue;
+				}
+				for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+				  ++bandno, ++band) {
+					if (!band->data) {
+						continue;
+					}
+					for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
+					  ++prcno, ++prc) {
+						if (!prc->cblks) {
+							continue;
+						}
+						for (cblkno = 0, cblk = prc->cblks; cblkno <
+						  prc->numcblks; ++cblkno, ++cblk) {
+							for (passno = 0, pass = cblk->passes; passno <
+							  cblk->numpasses && pass->lyrno == lyrno;
+							  ++passno, ++pass) {
+								jas_loginfof("lyrno=%02d cmptno=%02d rlvlno=%02d bandno=%02d prcno=%02d cblkno=%03d passno=%03d\n",
+								  lyrno, tcmptno, rlvlno, bandno, prcno,
+								  cblkno, passno);
+							}
+						}
+					}
+				}
+			}
+		}
+	}
+}
+
+int rateallocate(jpc_enc_t *enc, unsigned numlyrs, uint_fast32_t *cumlens)
+{
+	int ret = 0;
+	jpc_flt_t lo;
+	jpc_flt_t hi;
+	jas_stream_t *out;
+	uint_fast32_t cumlen;
+	jpc_flt_t thresh;
+	jpc_flt_t goodthresh;
+	int success;
+	long pos;
+	long oldpos;
+	int numiters;
+
+	jpc_enc_tcmpt_t *comp;
+	jpc_enc_tcmpt_t *endcomps;
+	jpc_enc_rlvl_t *lvl;
+	jpc_enc_rlvl_t *endlvls;
+	jpc_enc_band_t *band;
+	jpc_enc_band_t *endbands;
+	jpc_enc_cblk_t *cblk;
+	jpc_enc_cblk_t *endcblks;
+	jpc_enc_pass_t *pass;
+	jpc_enc_pass_t *endpasses;
+	jpc_enc_pass_t *pass1;
+	jpc_flt_t mxrdslope;
+	jpc_flt_t mnrdslope;
+	jpc_enc_tile_t *tile;
+	jpc_enc_prc_t *prc;
+	unsigned prcno;
+
+	JAS_LOGDEBUGF(10, "starting rate allocation\n");
+
+	tile = enc->curtile;
+
+	for (unsigned lyrno = 1; lyrno < numlyrs - 1; ++lyrno) {
+		assert(cumlens[lyrno - 1] <= cumlens[lyrno]);
+	}
+
+	if (!(out = jas_stream_memopen(0, 0))) {
+		ret = -1;
+		goto done;
+	}
+
+	/* Find minimum and maximum R-D slope values. */
+	mnrdslope = DBL_MAX;
+	mxrdslope = 0;
+	endcomps = &tile->tcmpts[tile->numtcmpts];
+	for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+		endlvls = &comp->rlvls[comp->numrlvls];
+		for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+			if (!lvl->bands) {
+				continue;
+			}
+			endbands = &lvl->bands[lvl->numbands];
+			for (band = lvl->bands; band != endbands; ++band) {
+				if (!band->data) {
+					continue;
+				}
+				for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs;
+				  ++prcno, ++prc) {
+					if (!prc->cblks) {
+						continue;
+					}
+					endcblks = &prc->cblks[prc->numcblks];
+					for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+						calcrdslopes(cblk);
+						endpasses = &cblk->passes[cblk->numpasses];
+						for (pass = cblk->passes; pass != endpasses; ++pass) {
+							if (pass->rdslope > 0) {
+								if (pass->rdslope < mnrdslope) {
+									mnrdslope = pass->rdslope;
+								}
+								if (pass->rdslope > mxrdslope) {
+									mxrdslope = pass->rdslope;
+								}
+							}
+						}
+					}
+				}
+			}
+		}
+	}
+	JAS_LOGDEBUGF(10, "min rdslope = %f max rdslope = %f\n", mnrdslope,
+	  mxrdslope);
+
+	jpc_init_t2state(enc, true);
+
+	for (unsigned lyrno = 0; lyrno < numlyrs; ++lyrno) {
+
+		lo = mnrdslope;
+		hi = mxrdslope;
+
+		success = 0;
+		goodthresh = 0;
+		numiters = 0;
+
+		do {
+
+			cumlen = cumlens[lyrno];
+			if (cumlen == UINT_FAST32_MAX) {
+				/* Only the last layer can be free of a rate
+				  constraint (e.g., for lossless coding). */
+				assert(lyrno == numlyrs - 1);
+				goodthresh = -1;
+				success = 1;
+				break;
+			}
+
+			thresh = (lo + hi) / 2;
+
+			/* Save the tier 2 coding state. */
+			jpc_save_t2state(enc);
+			oldpos = jas_stream_tell(out);
+			assert(oldpos >= 0);
+
+			/* Assign all passes with R-D slopes greater than or
+			  equal to the current threshold to this layer. */
+			endcomps = &tile->tcmpts[tile->numtcmpts];
+			for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+				endlvls = &comp->rlvls[comp->numrlvls];
+				for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+					if (!lvl->bands) {
+						continue;
+					}
+					endbands = &lvl->bands[lvl->numbands];
+					for (band = lvl->bands; band != endbands; ++band) {
+						if (!band->data) {
+							continue;
+						}
+						for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs;
+						  ++prcno, ++prc) {
+							if (!prc->cblks) {
+								continue;
+							}
+							endcblks = &prc->cblks[prc->numcblks];
+							for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+								if (cblk->curpass) {
+									endpasses = &cblk->passes[cblk->numpasses];
+									pass1 = cblk->curpass;
+									for (pass = cblk->curpass; pass !=
+									  endpasses; ++pass) {
+										if (pass->rdslope >= thresh) {
+											pass1 = &pass[1];
+										}
+									}
+									for (pass = cblk->curpass; pass != pass1;
+									  ++pass) {
+										pass->lyrno = lyrno;
+									}
+									for (; pass != endpasses; ++pass) {
+										pass->lyrno = -1;
+									}
+								}
+							}
+						}
+					}
+				}
+			}
+
+			/* Perform tier 2 coding. */
+			endcomps = &tile->tcmpts[tile->numtcmpts];
+			for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+				endlvls = &comp->rlvls[comp->numrlvls];
+				for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+					if (!lvl->bands) {
+						continue;
+					}
+					for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
+						if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts,
+						  lvl - comp->rlvls, prcno, lyrno)) {
+							ret = -1;
+							goto done;
+						}
+					}
+				}
+			}
+
+			pos = jas_stream_tell(out);
+
+			/* Check the rate constraint. */
+			assert(pos >= 0);
+			if ((uint_fast32_t)pos > cumlen) {
+				/* The rate is too high. */
+				lo = thresh;
+			} else if ((uint_fast32_t)pos <= cumlen) {
+				/* The rate is low enough, so try higher. */
+				hi = thresh;
+				if (!success || thresh < goodthresh) {
+					goodthresh = thresh;
+					success = 1;
+				}
+			}
+
+			/* Save the tier 2 coding state. */
+			jpc_restore_t2state(enc);
+			if (jas_stream_seek(out, oldpos, SEEK_SET) < 0) {
+				ret = -1;
+				goto done;
+			}
+
+			JAS_LOGDEBUGF(10, "maxlen=%08ld actuallen=%08ld thresh=%f\n",
+			  cumlen, pos, thresh);
+
+			++numiters;
+		} while (lo < hi - 1e-3 && numiters < 32);
+
+		if (!success) {
+			jas_logwarnf("warning: empty layer generated\n");
+		}
+
+		JAS_LOGDEBUGF(10, "success %d goodthresh %f\n", success, goodthresh);
+
+		/* Assign all passes with R-D slopes greater than or
+		  equal to the selected threshold to this layer. */
+		endcomps = &tile->tcmpts[tile->numtcmpts];
+		for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+			endlvls = &comp->rlvls[comp->numrlvls];
+			for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+				if (!lvl->bands) {
+					continue;
+				}
+				endbands = &lvl->bands[lvl->numbands];
+				for (band = lvl->bands; band != endbands; ++band) {
+					if (!band->data) {
+						continue;
+					}
+					for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs;
+					  ++prcno, ++prc) {
+						if (!prc->cblks) {
+							continue;
+						}
+						endcblks = &prc->cblks[prc->numcblks];
+						for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+							if (cblk->curpass) {
+								endpasses = &cblk->passes[cblk->numpasses];
+								pass1 = cblk->curpass;
+								if (success) {
+									for (pass = cblk->curpass; pass !=
+									  endpasses; ++pass) {
+										if (pass->rdslope >= goodthresh) {
+											pass1 = &pass[1];
+										}
+									}
+								}
+								for (pass = cblk->curpass; pass != pass1;
+								  ++pass) {
+									pass->lyrno = lyrno;
+								}
+								for (; pass != endpasses; ++pass) {
+									pass->lyrno = -1;
+								}
+							}
+						}
+					}
+				}
+			}
+		}
+
+		/* Perform tier 2 coding. */
+		endcomps = &tile->tcmpts[tile->numtcmpts];
+		for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+			endlvls = &comp->rlvls[comp->numrlvls];
+			for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+				if (!lvl->bands) {
+					continue;
+				}
+				for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
+					if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts,
+					  lvl - comp->rlvls, prcno, lyrno)) {
+						ret = -1;
+						goto done;
+					}
+				}
+			}
+		}
+	}
+
+	if (jas_get_debug_level() >= 5) {
+		dump_layeringinfo(enc);
+	}
+
+	jas_stream_close(out);
+	out = 0;
+
+done:
+
+	if (out) {
+		jas_stream_close(out);
+	}
+
+	JAS_LOGDEBUGF(10, "finished rate allocation\n");
+
+	return ret;
+}
+
+/******************************************************************************\
+* Tile constructors and destructors.
+\******************************************************************************/
+
+static jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno)
+{
+	jpc_enc_tile_t *tile;
+	uint_fast32_t htileno;
+	uint_fast32_t vtileno;
+	uint_fast16_t lyrno;
+	uint_fast16_t cmptno;
+	jpc_enc_tcmpt_t *tcmpt;
+
+	if (!(tile = jas_malloc(sizeof(jpc_enc_tile_t)))) {
+		goto error;
+	}
+
+	/* Initialize a few members used in error recovery. */
+	tile->tcmpts = 0;
+	tile->lyrsizes = 0;
+	tile->numtcmpts = cp->numcmpts;
+	tile->pi = 0;
+
+	tile->tileno = tileno;
+	htileno = tileno % cp->numhtiles;
+	vtileno = tileno / cp->numhtiles;
+
+	/* Calculate the coordinates of the top-left and bottom-right
+	  corners of the tile. */
+	tile->tlx = JAS_MAX(cp->tilegrdoffx + htileno * cp->tilewidth,
+	  cp->imgareatlx);
+	tile->tly = JAS_MAX(cp->tilegrdoffy + vtileno * cp->tileheight,
+	  cp->imgareatly);
+	tile->brx = JAS_MIN(cp->tilegrdoffx + (htileno + 1) * cp->tilewidth,
+	  cp->refgrdwidth);
+	tile->bry = JAS_MIN(cp->tilegrdoffy + (vtileno + 1) * cp->tileheight,
+	  cp->refgrdheight);
+
+	/* Initialize some tile coding parameters. */
+	tile->intmode = cp->tcp.intmode;
+	tile->csty = cp->tcp.csty;
+	tile->prg = cp->tcp.prg;
+	tile->mctid = cp->tcp.mctid;
+
+	tile->numlyrs = cp->tcp.numlyrs;
+	if (!(tile->lyrsizes = jas_alloc2(tile->numlyrs,
+	  sizeof(uint_fast32_t)))) {
+		goto error;
+	}
+	for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
+		tile->lyrsizes[lyrno] = 0;
+	}
+
+	/* Allocate an array for the per-tile-component information. */
+	if (!(tile->tcmpts = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_tcmpt_t)))) {
+		goto error;
+	}
+	/* Initialize a few members critical for error recovery. */
+	for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
+	  ++cmptno, ++tcmpt) {
+		tcmpt->rlvls = 0;
+		tcmpt->tsfb = 0;
+		tcmpt->data = 0;
+	}
+	/* Initialize the per-tile-component information. */
+	for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
+	  ++cmptno, ++tcmpt) {
+		if (!tcmpt_create(tcmpt, cp, image, tile)) {
+			goto error;
+		}
+	}
+
+	/* Initialize the synthesis weights for the MCT. */
+	switch (tile->mctid) {
+	case JPC_MCT_RCT:
+		tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0));
+		tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(0.6875));
+		tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(0.6875));
+		break;
+	case JPC_MCT_ICT:
+		tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0000));
+		tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(3.2584));
+		tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(2.4755));
+		break;
+	default:
+	case JPC_MCT_NONE:
+		for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
+		  ++cmptno, ++tcmpt) {
+			tcmpt->synweight = JPC_FIX_ONE;
+		}
+		break;
+	}
+
+	if (!(tile->pi = jpc_enc_pi_create(cp, tile))) {
+		goto error;
+	}
+
+	return tile;
+
+error:
+
+	if (tile) {
+		jpc_enc_tile_destroy(tile);
+	}
+	return 0;
+}
+
+/* Note: I don't think that it is necessary to marked destroyed subobjects
+as such in this function. */
+static void jpc_enc_tile_destroy(jpc_enc_tile_t *tile)
+{
+	jpc_enc_tcmpt_t *tcmpt;
+	uint_fast16_t cmptno;
+
+	if (tile->tcmpts) {
+		for (cmptno = 0, tcmpt = tile->tcmpts; cmptno <
+		  tile->numtcmpts; ++cmptno, ++tcmpt) {
+			tcmpt_destroy(tcmpt);
+		}
+		jas_free(tile->tcmpts);
+		/* tile->tcmpts = NULL; */
+	}
+	if (tile->lyrsizes) {
+		jas_free(tile->lyrsizes);
+		/* tile->lyrsizes = NULL; */
+	}
+	if (tile->pi) {
+		jpc_pi_destroy(tile->pi);
+		/* tile->pi = NULL; */
+	}
+	jas_free(tile);
+	/* tile = NULL; */
+}
+
+/* Note: This constructor creates the object in place. */
+static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
+  jas_image_t *image, jpc_enc_tile_t *tile)
+{
+	uint_fast16_t cmptno;
+	uint_fast16_t rlvlno;
+	jpc_enc_rlvl_t *rlvl;
+	uint_fast32_t tlx;
+	uint_fast32_t tly;
+	uint_fast32_t brx;
+	uint_fast32_t bry;
+	uint_fast32_t cmpttlx;
+	uint_fast32_t cmpttly;
+	jpc_enc_ccp_t *ccp;
+	jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
+
+	tcmpt->tile = tile;
+	tcmpt->tsfb = 0;
+	tcmpt->data = 0;
+	tcmpt->rlvls = 0;
+
+	/* Deduce the component number. */
+	cmptno = tcmpt - tile->tcmpts;
+
+	ccp = &cp->ccps[cmptno];
+
+	/* Compute the coordinates of the top-left and bottom-right
+	  corners of this tile-component. */
+	tlx = JPC_CEILDIV(tile->tlx, ccp->sampgrdstepx);
+	tly = JPC_CEILDIV(tile->tly, ccp->sampgrdstepy);
+	brx = JPC_CEILDIV(tile->brx, ccp->sampgrdstepx);
+	bry = JPC_CEILDIV(tile->bry, ccp->sampgrdstepy);
+
+	/* Create a sequence to hold the tile-component sample data. */
+	if (!(tcmpt->data = jas_seq2d_create(tlx, tly, brx, bry))) {
+		goto error;
+	}
+
+	/* Get the image data associated with this tile-component. */
+	cmpttlx = JPC_CEILDIV(cp->imgareatlx, ccp->sampgrdstepx);
+	cmpttly = JPC_CEILDIV(cp->imgareatly, ccp->sampgrdstepy);
+	if (jas_image_readcmpt(image, cmptno, tlx - cmpttlx, tly - cmpttly,
+	  brx - tlx, bry - tly, tcmpt->data)) {
+		goto error;
+	}
+
+	tcmpt->synweight = 0;
+	tcmpt->qmfbid = cp->tccp.qmfbid;
+	tcmpt->numrlvls = cp->tccp.maxrlvls;
+	tcmpt->numbands = 3 * tcmpt->numrlvls - 2;
+	if (!(tcmpt->tsfb = jpc_cod_gettsfb(tcmpt->qmfbid, tcmpt->numrlvls - 1))) {
+		goto error;
+	}
+
+	for (rlvlno = 0; rlvlno < tcmpt->numrlvls; ++rlvlno) {
+		tcmpt->prcwidthexpns[rlvlno] = cp->tccp.prcwidthexpns[rlvlno];
+		tcmpt->prcheightexpns[rlvlno] = cp->tccp.prcheightexpns[rlvlno];
+	}
+	tcmpt->cblkwidthexpn = cp->tccp.cblkwidthexpn;
+	tcmpt->cblkheightexpn = cp->tccp.cblkheightexpn;
+	tcmpt->cblksty = cp->tccp.cblksty;
+	tcmpt->csty = cp->tccp.csty;
+
+	tcmpt->numstepsizes = tcmpt->numbands;
+	assert(tcmpt->numstepsizes <= JPC_MAXBANDS);
+	memset(tcmpt->stepsizes, 0, tcmpt->numstepsizes * sizeof(uint_fast16_t));
+
+	/* Retrieve information about the various bands. */
+	jpc_tsfb_getbands(tcmpt->tsfb, jas_seq2d_xstart(tcmpt->data),
+	  jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data),
+	  jas_seq2d_yend(tcmpt->data), bandinfos);
+
+	if (!(tcmpt->rlvls = jas_alloc2(tcmpt->numrlvls, sizeof(jpc_enc_rlvl_t)))) {
+		goto error;
+	}
+	for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+	  ++rlvlno, ++rlvl) {
+		rlvl->bands = 0;
+		rlvl->tcmpt = tcmpt;
+	}
+	for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+	  ++rlvlno, ++rlvl) {
+		if (!rlvl_create(rlvl, cp, tcmpt, bandinfos)) {
+			goto error;
+		}
+	}
+
+	return tcmpt;
+
+error:
+
+	tcmpt_destroy(tcmpt);
+	return 0;
+
+}
+
+/* Note: Since jpc_enc_tcmpt_t objects are created in-place, they might
+potentially be destroyed multiple times at different levels in the call
+chain.  So, destroyed subobjects must be marked as destroyed to prevent
+problems such as double frees. */
+static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt)
+{
+	jpc_enc_rlvl_t *rlvl;
+	uint_fast16_t rlvlno;
+
+	if (tcmpt->rlvls) {
+		for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+		  ++rlvlno, ++rlvl) {
+			rlvl_destroy(rlvl);
+		}
+		jas_free(tcmpt->rlvls);
+		tcmpt->rlvls = NULL;
+	}
+
+	if (tcmpt->data) {
+		jas_seq2d_destroy(tcmpt->data);
+		tcmpt->data = NULL;
+	}
+	if (tcmpt->tsfb) {
+		jpc_tsfb_destroy(tcmpt->tsfb);
+		tcmpt->tsfb = NULL;
+	}
+}
+
+/* Note: This constructor creates the object in place. */
+static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
+  jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos)
+{
+	uint_fast16_t rlvlno;
+	uint_fast32_t tlprctlx;
+	uint_fast32_t tlprctly;
+	uint_fast32_t brprcbrx;
+	uint_fast32_t brprcbry;
+	uint_fast16_t bandno;
+	jpc_enc_band_t *band;
+
+	/* Deduce the resolution level. */
+	rlvlno = rlvl - tcmpt->rlvls;
+
+	/* Initialize members required for error recovery. */
+	rlvl->bands = 0;
+	rlvl->tcmpt = tcmpt;
+
+	/* Compute the coordinates of the top-left and bottom-right
+	  corners of the tile-component at this resolution. */
+	rlvl->tlx = JPC_CEILDIVPOW2(JAS_CAST(uint_fast32_t,
+	  jas_seq2d_xstart(tcmpt->data)), tcmpt->numrlvls - 1 - rlvlno);
+	rlvl->tly = JPC_CEILDIVPOW2(JAS_CAST(uint_fast32_t,
+	  jas_seq2d_ystart(tcmpt->data)), tcmpt->numrlvls - 1 - rlvlno);
+	rlvl->brx = JPC_CEILDIVPOW2(JAS_CAST(uint_fast32_t,
+	  jas_seq2d_xend(tcmpt->data)), tcmpt->numrlvls - 1 - rlvlno);
+	rlvl->bry = JPC_CEILDIVPOW2(JAS_CAST(uint_fast32_t,
+	  jas_seq2d_yend(tcmpt->data)), tcmpt->numrlvls - 1 - rlvlno);
+
+	if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) {
+		rlvl->numhprcs = 0;
+		rlvl->numvprcs = 0;
+		rlvl->numprcs = 0;
+		return rlvl;
+	}
+
+	rlvl->numbands = (!rlvlno) ? 1 : 3;
+	rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno];
+	rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno];
+	if (!rlvlno) {
+		rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
+		rlvl->cbgheightexpn = rlvl->prcheightexpn;
+	} else {
+		rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
+		rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
+	}
+	rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn);
+	rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn);
+
+	/* Compute the number of precincts. */
+	tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
+	tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
+	brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn);
+	brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn);
+	rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn);
+	rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn);
+	rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
+
+	if (!(rlvl->bands = jas_alloc2(rlvl->numbands, sizeof(jpc_enc_band_t)))) {
+		goto error;
+	}
+	for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+	  ++bandno, ++band) {
+		band->prcs = 0;
+		band->data = 0;
+		band->rlvl = rlvl;
+	}
+	for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+	  ++bandno, ++band) {
+		if (!band_create(band, cp, rlvl, bandinfos)) {
+			goto error;
+		}
+	}
+
+	return rlvl;
+error:
+
+	rlvl_destroy(rlvl);
+	return 0;
+}
+
+/* Note: Since jpc_enc_rlvl_t objects are created in-place, they might
+potentially be destroyed multiple times at different levels in the call
+chain.  So, destroyed subobjects must be marked as destroyed to prevent
+problems such as double frees. */
+static void rlvl_destroy(jpc_enc_rlvl_t *rlvl)
+{
+	jpc_enc_band_t *band;
+	uint_fast16_t bandno;
+
+	if (rlvl->bands) {
+		for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+		  ++bandno, ++band) {
+			band_destroy(band);
+		}
+		jas_free(rlvl->bands);
+		rlvl->bands = NULL;
+	}
+}
+
+/* Note: This constructor creates the object in place. */
+static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
+  jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos)
+{
+	uint_fast16_t bandno;
+	uint_fast16_t gblbandno;
+	uint_fast16_t rlvlno;
+	jpc_tsfb_band_t *bandinfo;
+	jpc_enc_tcmpt_t *tcmpt;
+	uint_fast32_t prcno;
+	jpc_enc_prc_t *prc;
+
+	tcmpt = rlvl->tcmpt;
+	band->data = 0;
+	band->prcs = 0;
+	band->rlvl = rlvl;
+
+	/* Deduce the resolution level and band number. */
+	rlvlno = rlvl - rlvl->tcmpt->rlvls;
+	bandno = band - rlvl->bands;
+	gblbandno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1);
+
+	bandinfo = &bandinfos[gblbandno];
+
+if (bandinfo->xstart != bandinfo->xend && bandinfo->ystart != bandinfo->yend) {
+	if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
+		goto error;
+	}
+	if (jas_seq2d_bindsub(band->data, tcmpt->data, bandinfo->locxstart,
+			      bandinfo->locystart, bandinfo->locxend, bandinfo->locyend)) {
+		goto error;
+	}
+	jas_seq2d_setshift(band->data, bandinfo->xstart, bandinfo->ystart);
+}
+	band->orient = bandinfo->orient;
+	band->analgain = JPC_NOMINALGAIN(cp->tccp.qmfbid, tcmpt->numrlvls, rlvlno,
+	  band->orient);
+	band->numbps = 0;
+	band->absstepsize = 0;
+	band->stepsize = 0;
+	band->synweight = bandinfo->synenergywt;
+
+if (band->data) {
+	if (!(band->prcs = jas_alloc2(rlvl->numprcs, sizeof(jpc_enc_prc_t)))) {
+		goto error;
+	}
+	for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
+	  ++prc) {
+		prc->cblks = 0;
+		prc->incltree = 0;
+		prc->nlibtree = 0;
+		prc->savincltree = 0;
+		prc->savnlibtree = 0;
+		prc->band = band;
+	}
+	for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
+	  ++prc) {
+		if (!prc_create(prc, band)) {
+			goto error;
+		}
+	}
+}
+
+	return band;
+
+error:
+	band_destroy(band);
+	return 0;
+}
+
+/* Note: Since jpc_enc_band_t objects are created in-place, they might
+potentially be destroyed multiple times at different levels in the call
+chain.  So, destroyed subobjects must be marked as destroyed to prevent
+problems such as double frees. */
+static void band_destroy(jpc_enc_band_t *band)
+{
+	jpc_enc_prc_t *prc;
+	jpc_enc_rlvl_t *rlvl;
+	uint_fast32_t prcno;
+
+	if (band->prcs) {
+		rlvl = band->rlvl;
+		for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
+		  ++prcno, ++prc) {
+			prc_destroy(prc);
+		}
+		jas_free(band->prcs);
+		band->prcs = NULL;
+	}
+	if (band->data) {
+		jas_seq2d_destroy(band->data);
+		band->data = NULL;
+	}
+}
+
+/* Note: This constructor creates the object in place. */
+static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_band_t *band)
+{
+	uint_fast32_t prcno;
+	uint_fast32_t prcxind;
+	uint_fast32_t prcyind;
+	uint_fast32_t cbgtlx;
+	uint_fast32_t cbgtly;
+	uint_fast32_t tlprctlx;
+	uint_fast32_t tlprctly;
+	uint_fast32_t tlcbgtlx;
+	uint_fast32_t tlcbgtly;
+	uint_fast16_t rlvlno;
+	jpc_enc_rlvl_t *rlvl;
+	uint_fast32_t tlcblktlx;
+	uint_fast32_t tlcblktly;
+	uint_fast32_t brcblkbrx;
+	uint_fast32_t brcblkbry;
+	uint_fast32_t cblkno;
+	jpc_enc_cblk_t *cblk;
+	jpc_enc_tcmpt_t *tcmpt;
+
+	prc->cblks = 0;
+	prc->incltree = 0;
+	prc->savincltree = 0;
+	prc->nlibtree = 0;
+	prc->savnlibtree = 0;
+
+	rlvl = band->rlvl;
+	tcmpt = rlvl->tcmpt;
+	rlvlno = rlvl - tcmpt->rlvls;
+	prcno = prc - band->prcs;
+	prcxind = prcno % rlvl->numhprcs;
+	prcyind = prcno / rlvl->numhprcs;
+	prc->band = band;
+
+	tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
+	tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
+	if (!rlvlno) {
+		tlcbgtlx = tlprctlx;
+		tlcbgtly = tlprctly;
+	} else {
+		tlcbgtlx = JPC_CEILDIVPOW2(tlprctlx, 1);
+		tlcbgtly = JPC_CEILDIVPOW2(tlprctly, 1);
+	}
+
+	/* Compute the coordinates of the top-left and bottom-right
+	  corners of the precinct. */
+	cbgtlx = tlcbgtlx + (prcxind << rlvl->cbgwidthexpn);
+	cbgtly = tlcbgtly + (prcyind << rlvl->cbgheightexpn);
+	prc->tlx = JAS_MAX(jas_seq2d_xstart(band->data), (jas_matind_t)cbgtlx);
+	prc->tly = JAS_MAX(jas_seq2d_ystart(band->data), (jas_matind_t)cbgtly);
+	prc->brx = JAS_MIN(jas_seq2d_xend(band->data), (jas_matind_t)(cbgtlx +
+	  (1 << rlvl->cbgwidthexpn)));
+	prc->bry = JAS_MIN(jas_seq2d_yend(band->data), (jas_matind_t)(cbgtly +
+	  (1 << rlvl->cbgheightexpn)));
+
+	if (prc->tlx < prc->brx && prc->tly < prc->bry) {
+		/* The precinct contains at least one code block. */
+
+		tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
+		tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
+		brcblkbrx = JPC_CEILTOMULTPOW2(prc->brx, rlvl->cblkwidthexpn);
+		brcblkbry = JPC_CEILTOMULTPOW2(prc->bry, rlvl->cblkheightexpn);
+		prc->numhcblks = JPC_FLOORDIVPOW2(brcblkbrx - tlcblktlx,
+		  rlvl->cblkwidthexpn);
+		prc->numvcblks = JPC_FLOORDIVPOW2(brcblkbry - tlcblktly,
+		  rlvl->cblkheightexpn);
+		prc->numcblks = prc->numhcblks * prc->numvcblks;
+
+		if (!(prc->incltree = jpc_tagtree_create(prc->numhcblks,
+		  prc->numvcblks))) {
+			goto error;
+		}
+		if (!(prc->nlibtree = jpc_tagtree_create(prc->numhcblks,
+		  prc->numvcblks))) {
+			goto error;
+		}
+		if (!(prc->savincltree = jpc_tagtree_create(prc->numhcblks,
+		  prc->numvcblks))) {
+			goto error;
+		}
+		if (!(prc->savnlibtree = jpc_tagtree_create(prc->numhcblks,
+		  prc->numvcblks))) {
+			goto error;
+		}
+
+		if (!(prc->cblks = jas_alloc2(prc->numcblks, sizeof(jpc_enc_cblk_t)))) {
+			goto error;
+		}
+		for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+		  ++cblkno, ++cblk) {
+			cblk->passes = 0;
+			cblk->stream = 0;
+			cblk->mqenc = 0;
+			cblk->data = 0;
+			cblk->flags = 0;
+			cblk->prc = prc;
+		}
+		for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+		  ++cblkno, ++cblk) {
+			if (!cblk_create(cblk, prc)) {
+				goto error;
+			}
+		}
+	} else {
+		/* The precinct does not contain any code blocks. */
+		prc->tlx = prc->brx;
+		prc->tly = prc->bry;
+		prc->numcblks = 0;
+		prc->numhcblks = 0;
+		prc->numvcblks = 0;
+		prc->cblks = 0;
+		prc->incltree = 0;
+		prc->nlibtree = 0;
+		prc->savincltree = 0;
+		prc->savnlibtree = 0;
+	}
+
+	return prc;
+
+error:
+	prc_destroy(prc);
+	return 0;
+}
+
+/* Note: Since jpc_enc_prc_t objects are created in-place, they might
+potentially be destroyed multiple times at different levels in the call
+chain.  So, destroyed subobjects must be marked as destroyed to prevent
+problems such as double frees. */
+static void prc_destroy(jpc_enc_prc_t *prc)
+{
+	jpc_enc_cblk_t *cblk;
+	uint_fast32_t cblkno;
+
+	if (prc->cblks) {
+		for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+		  ++cblkno, ++cblk) {
+			cblk_destroy(cblk);
+		}
+		jas_free(prc->cblks);
+		prc->cblks = NULL;
+	}
+	if (prc->incltree) {
+		jpc_tagtree_destroy(prc->incltree);
+		prc->incltree = NULL;
+	}
+	if (prc->nlibtree) {
+		jpc_tagtree_destroy(prc->nlibtree);
+		prc->nlibtree = NULL;
+	}
+	if (prc->savincltree) {
+		jpc_tagtree_destroy(prc->savincltree);
+		prc->savincltree = NULL;
+	}
+	if (prc->savnlibtree) {
+		jpc_tagtree_destroy(prc->savnlibtree);
+		prc->savnlibtree = NULL;
+	}
+}
+
+/* Note: This constructor creates the object in place. */
+static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk,
+  jpc_enc_prc_t *prc)
+{
+	jpc_enc_band_t *band;
+	uint_fast32_t cblktlx;
+	uint_fast32_t cblktly;
+	uint_fast32_t cblkbrx;
+	uint_fast32_t cblkbry;
+	jpc_enc_rlvl_t *rlvl;
+	uint_fast32_t cblkxind;
+	uint_fast32_t cblkyind;
+	uint_fast32_t cblkno;
+	uint_fast32_t tlcblktlx;
+	uint_fast32_t tlcblktly;
+
+	cblkno = cblk - prc->cblks;
+	cblkxind = cblkno % prc->numhcblks;
+	cblkyind = cblkno / prc->numhcblks;
+	rlvl = prc->band->rlvl;
+	cblk->prc = prc;
+
+	cblk->numpasses = 0;
+	cblk->passes = 0;
+	cblk->numencpasses = 0;
+	cblk->numimsbs = 0;
+	cblk->numlenbits = 0;
+	cblk->stream = 0;
+	cblk->mqenc = 0;
+	cblk->flags = 0;
+	cblk->numbps = 0;
+	cblk->curpass = 0;
+	cblk->data = 0;
+	cblk->savedcurpass = 0;
+	cblk->savednumlenbits = 0;
+	cblk->savednumencpasses = 0;
+
+	band = prc->band;
+	tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
+	tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
+	cblktlx = JAS_MAX(tlcblktlx + (cblkxind << rlvl->cblkwidthexpn), prc->tlx);
+	cblktly = JAS_MAX(tlcblktly + (cblkyind << rlvl->cblkheightexpn), prc->tly);
+	cblkbrx = JAS_MIN(tlcblktlx + ((cblkxind + 1) << rlvl->cblkwidthexpn),
+	  prc->brx);
+	cblkbry = JAS_MIN(tlcblktly + ((cblkyind + 1) << rlvl->cblkheightexpn),
+	  prc->bry);
+
+	assert(cblktlx < cblkbrx && cblktly < cblkbry);
+	if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) {
+		goto error;
+	}
+	if (jas_seq2d_bindsub(cblk->data, band->data, cblktlx, cblktly, cblkbrx, cblkbry)) {
+		goto error;
+	}
+
+	return cblk;
+
+error:
+	cblk_destroy(cblk);
+	return 0;
+}
+
+/* Note: Since jpc_enc_cblk_t objects are created in-place, they might
+potentially be destroyed multiple times at different levels in the call
+chain.  So, destroyed subobjects must be marked as destroyed to prevent
+problems such as double frees. */
+static void cblk_destroy(jpc_enc_cblk_t *cblk)
+{
+	uint_fast16_t passno;
+	jpc_enc_pass_t *pass;
+	if (cblk->passes) {
+		for (passno = 0, pass = cblk->passes; passno < cblk->numpasses;
+		  ++passno, ++pass) {
+			pass_destroy(pass);
+		}
+		jas_free(cblk->passes);
+		cblk->passes = NULL;
+	}
+	if (cblk->stream) {
+		jas_stream_close(cblk->stream);
+		cblk->stream = NULL;
+	}
+	if (cblk->mqenc) {
+		jpc_mqenc_destroy(cblk->mqenc);
+		cblk->mqenc = NULL;
+	}
+	if (cblk->data) {
+		jas_seq2d_destroy(cblk->data);
+		cblk->data = NULL;
+	}
+	if (cblk->flags) {
+		jas_seq2d_destroy(cblk->flags);
+		cblk->flags = NULL;
+	}
+}
+
+static void pass_destroy(jpc_enc_pass_t *pass)
+{
+	/* XXX - need to free resources here */
+	JAS_UNUSED(pass);
+}
+
+void jpc_enc_dump(jpc_enc_t *enc)
+{
+	jpc_enc_tile_t *tile;
+	jpc_enc_tcmpt_t *tcmpt;
+	jpc_enc_rlvl_t *rlvl;
+	jpc_enc_band_t *band;
+	jpc_enc_prc_t *prc;
+	jpc_enc_cblk_t *cblk;
+	uint_fast16_t cmptno;
+	uint_fast16_t rlvlno;
+	uint_fast16_t bandno;
+	uint_fast32_t prcno;
+	uint_fast32_t cblkno;
+
+	tile = enc->curtile;
+
+	for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno,
+	  ++tcmpt) {
+		jas_loginfof("  tcmpt %5d %5d %5d %5d\n", jas_seq2d_xstart(tcmpt->data), jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data), jas_seq2d_yend(tcmpt->data));
+		for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+		  ++rlvlno, ++rlvl) {
+			jas_loginfof("    rlvl %5d %5d %5d %5d\n", rlvl->tlx, rlvl->tly, rlvl->brx, rlvl->bry);
+			for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+			  ++bandno, ++band) {
+				if (!band->data) {
+					continue;
+				}
+				jas_loginfof("      band %5d %5d %5d %5d\n", jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data), jas_seq2d_yend(band->data));
+				for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
+				  ++prcno, ++prc) {
+					jas_loginfof("        prc %5d %5d %5d %5d (%5d %5d)\n", prc->tlx, prc->tly, prc->brx, prc->bry, prc->brx - prc->tlx, prc->bry - prc->tly);
+					if (!prc->cblks) {
+						continue;
+					}
+					for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+					  ++cblkno, ++cblk) {
+						jas_loginfof("         cblk %5d %5d %5d %5d\n", jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data), jas_seq2d_yend(cblk->data));
+					}
+				}
+			}
+		}
+	}
+}
--- /dev/null
+++ b/jpc_enc.h
@@ -1,0 +1,650 @@
+/*
+ * 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_ENC_H
+#define JPC_ENC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_image.h"
+#include "jasper/jas_seq.h"
+#include "jasper/jas_stream.h"
+
+#include "jpc_cod.h"
+#include "jpc_t1cod.h"
+#include "jpc_t2cod.h"
+#include "jpc_mqenc.h"
+#include "jpc_tagtree.h"
+#include "jpc_cs.h"
+#include "jpc_fix.h"
+#include "jpc_flt.h"
+#include "jpc_tsfb.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* The number of bits used in various lookup tables. */
+#define	JPC_NUMEXTRABITS	JPC_NMSEDEC_FRACBITS
+
+/* An invalid R-D slope value. */
+#define	JPC_BADRDSLOPE	(-1)
+
+/******************************************************************************\
+* Coding parameters types.
+\******************************************************************************/
+
+/* Per-component coding paramters. */
+
+typedef struct {
+
+	/* The horizontal sampling period. */
+	uint_fast8_t sampgrdstepx;
+
+	/* The vertical sampling period. */
+	uint_fast8_t sampgrdstepy;
+
+	/* The sample alignment horizontal offset. */
+	uint_fast8_t sampgrdsubstepx;
+
+	/* The sample alignment vertical offset. */
+	uint_fast8_t sampgrdsubstepy;
+
+	/* The precision of the samples. */
+	uint_fast8_t prec;
+
+	/* The signedness of the samples. */
+	bool sgnd;
+
+	/* The number of step sizes. */
+	uint_fast16_t numstepsizes;
+
+	/* The quantizer step sizes. */
+	uint_fast16_t stepsizes[JPC_MAXBANDS];
+
+} jpc_enc_ccp_t;
+
+/* Per-tile coding parameters. */
+
+typedef struct {
+
+	/* The coding mode. */
+	bool intmode;
+
+	/* The coding style (i.e., SOP, EPH). */
+	uint_fast8_t csty;
+
+	/* The progression order. */
+	uint_fast8_t prg;
+
+	/* The multicomponent transform. */
+	uint_fast8_t mctid;
+
+	/* The number of layers. */
+	uint_fast16_t numlyrs;
+
+	/* The normalized bit rates associated with the various
+	  intermediate layers. */
+	jpc_fix_t *ilyrrates;
+
+} jpc_enc_tcp_t;
+
+/* Per tile-component coding parameters. */
+
+typedef struct {
+
+	/* The coding style (i.e., explicit precinct sizes). */
+	uint_fast8_t csty;
+
+	/* The maximum number of resolution levels allowed. */
+	uint_fast8_t maxrlvls;
+
+	/* The exponent for the nominal code block width. */
+	uint_fast16_t cblkwidthexpn;
+
+	/* The exponent for the nominal code block height. */
+	uint_fast16_t cblkheightexpn;
+
+	/* The code block style parameters (e.g., lazy, terminate all,
+	  segmentation symbols, causal, reset probability models). */
+	uint_fast8_t cblksty;
+
+	/* The QMFB. */
+	uint_fast8_t qmfbid;
+
+	/* The precinct width values. */
+	uint_fast16_t prcwidthexpns[JPC_MAXRLVLS];
+
+	/* The precinct height values. */
+	uint_fast16_t prcheightexpns[JPC_MAXRLVLS];
+
+	/* The number of guard bits. */
+	uint_fast8_t numgbits;
+
+} jpc_enc_tccp_t;
+
+/* Coding parameters. */
+
+typedef struct {
+
+	/* The debug level. */
+	int debug;
+
+	/* The horizontal offset from the origin of the reference grid to the
+	  left edge of the image area. */
+	uint_fast32_t imgareatlx;
+
+	/* The vertical offset from the origin of the reference grid to the
+	  top edge of the image area. */
+	uint_fast32_t imgareatly;
+
+	/* The horizontal offset from the origin of the reference grid to the
+	  right edge of the image area (plus one). */
+	uint_fast32_t refgrdwidth;
+
+	/* The vertical offset from the origin of the reference grid to the
+	  bottom edge of the image area (plus one). */
+	uint_fast32_t refgrdheight;
+
+	/* The horizontal offset from the origin of the tile grid to the
+	  origin of the reference grid. */
+	uint_fast32_t tilegrdoffx;
+
+	/* The vertical offset from the origin of the tile grid to the
+	  origin of the reference grid. */
+	uint_fast32_t tilegrdoffy;
+
+	/* 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 number of tiles spanning the image area in the horizontal
+	  direction. */
+	uint_fast32_t numhtiles;
+
+	/* The number of tiles spanning the image area in the vertical
+	  direction. */
+	uint_fast32_t numvtiles;
+
+	/* The number of tiles. */
+	uint_fast32_t numtiles;
+
+	/* The number of components. */
+	uint_fast16_t numcmpts;
+
+	/* The per-component coding parameters. */
+	jpc_enc_ccp_t *ccps;
+
+	/* The per-tile coding parameters. */
+	jpc_enc_tcp_t tcp;
+
+	/* The per-tile-component coding parameters. */
+	jpc_enc_tccp_t tccp;
+
+	/* The target code stream length in bytes. */
+	uint_fast32_t totalsize;
+
+	/* The raw (i.e., uncompressed) size of the image in bytes. */
+	uint_fast32_t rawsize;
+
+} jpc_enc_cp_t;
+
+/******************************************************************************\
+* Encoder class.
+\******************************************************************************/
+
+/* Encoder per-coding-pass state information. */
+
+typedef struct {
+
+	/* The starting offset for this pass. */
+	int start;
+
+	/* The ending offset for this pass. */
+	int end;
+
+	/* The type of data in this pass (i.e., MQ or raw). */
+	enum jpc_segtype type;
+
+	/* Flag indicating that this pass is terminated. */
+	int term;
+
+	/* The entropy coder state after coding this pass. */
+	jpc_mqencstate_t mqencstate;
+
+	/* The layer to which this pass has been assigned. */
+	unsigned lyrno;
+
+	/* The R-D slope for this pass. */
+	jpc_flt_t rdslope;
+
+	/* The weighted MSE reduction associated with this pass. */
+	jpc_flt_t wmsedec;
+
+	/* The cumulative weighted MSE reduction. */
+	jpc_flt_t cumwmsedec;
+
+	/* The normalized MSE reduction. */
+	long nmsedec;
+
+} jpc_enc_pass_t;
+
+/* Encoder per-code-block state information. */
+
+typedef struct {
+
+	/* The number of passes. */
+	unsigned numpasses;
+
+	/* The per-pass information. */
+	jpc_enc_pass_t *passes;
+
+	/* The number of passes encoded so far. */
+	int numencpasses;
+
+	/* The number of insignificant MSBs. */
+	int numimsbs;
+
+	/* The number of bits used to encode pass data lengths. */
+	int numlenbits;
+
+	/* The byte stream for this code block. */
+	jas_stream_t *stream;
+
+	/* The entropy encoder. */
+	jpc_mqenc_t *mqenc;
+
+	/* The data for this code block. */
+	jas_matrix_t *data;
+
+	/* The state for this code block. */
+	jas_matrix_t *flags;
+
+	/* The number of bit planes required for this code block. */
+	int numbps;
+
+	/* The next pass to be encoded. */
+	jpc_enc_pass_t *curpass;
+
+	/* The per-code-block-group state information. */
+	struct jpc_enc_prc_s *prc;
+
+	/* The saved current pass. */
+	/* This is used by the rate control code. */
+	jpc_enc_pass_t *savedcurpass;
+
+	/* The saved length indicator size. */
+	/* This is used by the rate control code. */
+	int savednumlenbits;
+
+	/* The saved number of encoded passes. */
+	/* This is used by the rate control code. */
+	int savednumencpasses;
+
+} jpc_enc_cblk_t;
+
+/* Encoder per-code-block-group state information. */
+
+typedef struct jpc_enc_prc_s {
+
+	/* The x-coordinate of the top-left corner of the precinct. */
+	uint_fast32_t tlx;
+
+	/* The y-coordinate of the top-left corner of the precinct. */
+	uint_fast32_t tly;
+
+	/* The x-coordinate of the bottom-right corner of the precinct
+	  (plus one). */
+	uint_fast32_t brx;
+
+	/* The y-coordinate of the bottom-right corner of the precinct
+	  (plus one). */
+	uint_fast32_t bry;
+
+	/* The number of code blocks spanning the precinct in the horizontal
+	direction. */
+	int numhcblks;
+
+	/* The number of code blocks spanning the precinct in the vertical
+	direction. */
+	int numvcblks;
+
+	/* The total number of code blocks. */
+	unsigned numcblks;
+
+	/* The per-code-block information. */
+	jpc_enc_cblk_t *cblks;
+
+	/* The inclusion tag tree. */
+	jpc_tagtree_t *incltree;
+
+	/* The insignifcant MSBs tag tree. */
+	jpc_tagtree_t *nlibtree;
+
+	/* The per-band information. */
+	struct jpc_enc_band_s *band;
+
+	/* The saved inclusion tag tree. */
+	/* This is used by rate control. */
+	jpc_tagtree_t *savincltree;
+
+	/* The saved leading-insignificant-bit-planes tag tree. */
+	/* This is used by rate control. */
+	jpc_tagtree_t *savnlibtree;
+
+} jpc_enc_prc_t;
+
+/* Encoder per-band state information. */
+
+typedef struct jpc_enc_band_s {
+
+	/* The per precinct information. */
+	jpc_enc_prc_t *prcs;
+
+	/* The coefficient data for this band. */
+	jas_matrix_t *data;
+
+	/* The orientation of this band (i.e., LL, LH, HL, or HH). */
+	enum jpc_tsfb_orient orient;
+
+	/* The number of bit planes associated with this band. */
+	int numbps;
+
+	/* The quantizer step size. */
+	jpc_fix_t absstepsize;
+
+	/* The encoded quantizer step size. */
+	int stepsize;
+
+	/* The L2 norm of the synthesis basis functions associated with
+	  this band.  (The MCT is not considered in this value.) */
+	jpc_fix_t synweight;
+
+	/* The analysis gain for this band. */
+	int analgain;
+
+	/* The per-resolution-level information. */
+	struct jpc_enc_rlvl_s *rlvl;
+
+} jpc_enc_band_t;
+
+/* Encoder per-resolution-level state information. */
+
+typedef struct jpc_enc_rlvl_s {
+
+	/* The x-coordinate of the top-left corner of the tile-component
+	  at this resolution. */
+	uint_fast32_t tlx;
+
+	/* The y-coordinate of the top-left corner of the tile-component
+	  at this resolution. */
+	uint_fast32_t tly;
+
+	/* The x-coordinate of the bottom-right corner of the tile-component
+	  at this resolution (plus one). */
+	uint_fast32_t brx;
+
+	/* The y-coordinate of the bottom-right corner of the tile-component
+	  at this resolution (plus one). */
+	uint_fast32_t bry;
+
+	/* The exponent value for the nominal precinct width measured
+	  relative to the associated LL band. */
+	int prcwidthexpn;
+
+	/* The exponent value for the nominal precinct height measured
+	  relative to the associated LL band. */
+	int prcheightexpn;
+
+	/* The number of precincts spanning the resolution level in the
+	  horizontal direction. */
+	int numhprcs;
+
+	/* The number of precincts spanning the resolution level in the
+	  vertical direction. */
+	int 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;
+
+	/* The number of bands associated with this resolution level. */
+	unsigned numbands;
+
+	/* The per-band information. */
+	jpc_enc_band_t *bands;
+
+	/* The parent tile-component. */
+	struct jpc_enc_tcmpt_s *tcmpt;
+
+} jpc_enc_rlvl_t;
+
+/* Encoder per-tile-component state information. */
+
+typedef struct jpc_enc_tcmpt_s {
+
+	/* The number of resolution levels. */
+	unsigned numrlvls;
+
+	/* The per-resolution-level information. */
+	jpc_enc_rlvl_t *rlvls;
+
+	/* The tile-component data. */
+	jas_matrix_t *data;
+
+	/* The QMFB. */
+	int qmfbid;
+
+	/* The number of bands. */
+	int numbands;
+
+	/* The TSFB. */
+	jpc_tsfb_t *tsfb;
+
+	/* The synthesis energy weight (for the MCT). */
+	jpc_fix_t synweight;
+
+	/* The precinct width exponents. */
+	int prcwidthexpns[JPC_MAXRLVLS];
+
+	/* The precinct height exponents. */
+	int prcheightexpns[JPC_MAXRLVLS];
+
+	/* The code block width exponent. */
+	int cblkwidthexpn;
+
+	/* The code block height exponent. */
+	int cblkheightexpn;
+
+	/* Coding style (i.e., explicit precinct sizes). */
+	int csty;
+
+	/* Code block style. */
+	int cblksty;
+
+	/* The number of quantizer step sizes. */
+	int numstepsizes;
+
+	/* The encoded quantizer step sizes. */
+	uint_fast16_t stepsizes[JPC_MAXBANDS];
+
+	/* The parent tile. */
+	struct jpc_enc_tile_s *tile;
+
+} jpc_enc_tcmpt_t;
+
+/* Encoder per-tile state information. */
+
+typedef struct jpc_enc_tile_s {
+
+	/* The tile number. */
+	uint_fast32_t tileno;
+
+	/* The x-coordinate of the top-left corner of the tile measured with
+	  respect to the reference grid. */
+	uint_fast32_t tlx;
+
+	/* The y-coordinate of the top-left corner of the tile measured with
+	  respect to the reference grid. */
+	uint_fast32_t tly;
+
+	/* The x-coordinate of the bottom-right corner of the tile measured
+	  with respect to the reference grid (plus one). */
+	uint_fast32_t brx;
+
+	/* The y-coordinate of the bottom-right corner of the tile measured
+	  with respect to the reference grid (plus one). */
+	uint_fast32_t bry;
+
+	/* The coding style. */
+	uint_fast8_t csty;
+
+	/* The progression order. */
+	uint_fast8_t prg;
+
+	/* The number of layers. */
+	unsigned numlyrs;
+
+	/* The MCT to employ (if any). */
+	uint_fast8_t mctid;
+
+	/* The packet iterator (used to determine the order of packet
+	  generation). */
+	jpc_pi_t *pi;
+
+	/* The coding mode (i.e., integer or real). */
+	bool intmode;
+
+	/* The number of bytes to allocate to the various layers. */
+	uint_fast32_t *lyrsizes;
+
+	/* The number of tile-components. */
+	unsigned numtcmpts;
+
+	/* The per tile-component information. */
+	jpc_enc_tcmpt_t *tcmpts;
+
+	/* The raw (i.e., uncompressed) size of this tile. */
+	uint_fast32_t rawsize;
+
+} jpc_enc_tile_t;
+
+/* Encoder class. */
+
+typedef struct jpc_enc_s {
+
+	/* The image being encoded. */
+	jas_image_t *image;
+
+	/* The output stream. */
+	jas_stream_t *out;
+
+	/* The coding parameters. */
+	jpc_enc_cp_t *cp;
+
+	/* The tile currently being processed. */
+	jpc_enc_tile_t *curtile;
+
+	/* The code stream state. */
+	jpc_cstate_t *cstate;
+
+	/* The number of bytes output so far. */
+	uint_fast32_t len;
+
+	/* The number of bytes available for the main body of the code stream. */
+	/* This is used for rate allocation purposes. */
+	uint_fast32_t mainbodysize;
+
+	/* The marker segment currently being processed. */
+	/* This member is a convenience for making cleanup easier. */
+	jpc_ms_t *mrk;
+
+	/* The stream used to temporarily hold tile-part data. */
+	jas_stream_t *tmpstream;
+
+} jpc_enc_t;
+
+#endif
--- a/jpc_fix.h
+++ b/jpc_fix.h
@@ -83,22 +83,29 @@
 * 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
+/*
+jpc_fix_t.
+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).
 
-/* 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;
+jpc_fix_big_t.
+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).
 
-/* The number of bits used for the fractional part of a fixed-point number. */
+JPC_FIX_FRACBITS.
+The number of bits used for the fractional part of a fixed-point number.
+*/
+
+typedef jas_fix_t jpc_fix_t;
+typedef jas_fix_big_t jpc_fix_big_t;
+
+#if defined(JAS_ENABLE_32BIT)
 #define JPC_FIX_FRACBITS	13
+#else
+#define JPC_FIX_FRACBITS	18
+#endif
 
 /******************************************************************************\
 * Instantiations of the generic fixed-point number macros for the
@@ -174,6 +181,7 @@
 //#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)
 
+#if 0
 #ifdef JAS_ENABLE_32BIT
 #define jpc_fix_asl jas_least32_asl
 #define jpc_fix_asr jas_least32_asr
@@ -181,9 +189,14 @@
 #define jpc_fix_asl jas_fast32_asl
 #define jpc_fix_asr jas_fast32_asr
 #endif
+#endif
+#define jpc_fix_asl jas_fix_asl
+#define jpc_fix_asr jas_fix_asr
 
-#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_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)
 
--- a/jpc_math.c
+++ b/jpc_math.c
@@ -93,3 +93,37 @@
 	}
 	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;
+}
--- a/jpc_math.h
+++ b/jpc_math.h
@@ -90,6 +90,14 @@
 * 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
--- a/jpc_mqdec.c
+++ b/jpc_mqdec.c
@@ -84,7 +84,7 @@
 
 #ifndef NDEBUG
 #define	MQDEC_CALL(n, x) \
-	((jas_getdbglevel() >= (n)) ? ((void)(x)) : ((void)0))
+	((jas_get_debug_level() >= (n)) ? ((void)(x)) : ((void)0))
 #else
 #define	MQDEC_CALL(n, x)
 #endif
@@ -207,10 +207,12 @@
 bool jpc_mqdec_getbit_func(register jpc_mqdec_t *mqdec)
 {
 	bool bit;
-	JAS_DBGLOG(100, ("jpc_mqdec_getbit_func(%p)\n", mqdec));
+	JAS_LOGDEBUGF(100, "jpc_mqdec_getbit_func(%p)\n", mqdec);
+	MQDEC_CALL(100, jpc_mqdec_dump(mqdec));
 	bit = jpc_mqdec_getbit_macro(mqdec);
-	JAS_DBGLOG(100, ("ctx = %d, decoded %d\n", mqdec->curctx -
-	  mqdec->ctxs, bit));
+	MQDEC_CALL(100, jpc_mqdec_dump(mqdec));
+	JAS_LOGDEBUGF(100, "ctx = %d, decoded %d\n", mqdec->curctx -
+	  mqdec->ctxs, bit);
 	return bit;
 }
 
@@ -277,4 +279,20 @@
 		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)
+{
+	jas_logprintf("MQDEC A = %08lx, C = %08lx, CT=%08lx, ",
+	  (unsigned long) mqdec->areg, (unsigned long) mqdec->creg,
+	  (unsigned long) mqdec->ctreg);
+	jas_logprintf("CTX = %" PRIdPTR ", ", mqdec->curctx - mqdec->ctxs);
+	jas_logprintf("IND %" PRIdPTR ", MPS %d, QEVAL %"PRIxLEAST16"\n", *mqdec->curctx -
+	  jpc_mqstates, (*mqdec->curctx)->mps, (*mqdec->curctx)->qeval);
 }
--- a/jpc_mqdec.h
+++ b/jpc_mqdec.h
@@ -172,6 +172,13 @@
 #endif
 
 /******************************************************************************\
+* Functions/macros for debugging.
+\******************************************************************************/
+
+/* Dump the MQ decoder state for debugging. */
+void jpc_mqdec_dump(const jpc_mqdec_t *dec);
+
+/******************************************************************************\
 * 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.
--- /dev/null
+++ b/jpc_mqenc.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__
+ */
+
+/*
+ * MQ Arithmetic Encoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_mqenc.h"
+
+#include "jasper/jas_stream.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Macros
+\******************************************************************************/
+
+#ifndef NDEBUG
+#define	JPC_MQENC_CALL(n, x) \
+	((jas_get_debug_level() >= (n)) ? ((void)(x)) : ((void)0))
+#else
+#define	JPC_MQENC_CALL(n, x)
+#endif
+
+#define	jpc_mqenc_codemps9(areg, creg, ctreg, curctx, enc) \
+{ \
+	const jpc_mqstate_t *state = *(curctx); \
+	(areg) -= state->qeval; \
+	if (!((areg) & 0x8000)) { \
+		if ((areg) < state->qeval) { \
+			(areg) = state->qeval; \
+		} else { \
+			(creg) += state->qeval; \
+		} \
+		*(curctx) = state->nmps; \
+		jpc_mqenc_renorme((areg), (creg), (ctreg), (enc)); \
+	} else { \
+		(creg) += state->qeval; \
+	} \
+}
+
+#define	jpc_mqenc_codelps2(areg, creg, ctreg, curctx, enc) \
+{ \
+	const jpc_mqstate_t *state = *(curctx); \
+	(areg) -= state->qeval; \
+	if ((areg) < state->qeval) { \
+		(creg) += state->qeval; \
+	} else { \
+		(areg) = state->qeval; \
+	} \
+	*(curctx) = state->nlps; \
+	jpc_mqenc_renorme((areg), (creg), (ctreg), (enc)); \
+}
+
+#define	jpc_mqenc_renorme(areg, creg, ctreg, enc) \
+{ \
+	do { \
+		(areg) <<= 1; \
+		(creg) <<= 1; \
+		if (!--(ctreg)) { \
+			jpc_mqenc_byteout((areg), (creg), (ctreg), (enc)); \
+		} \
+	} while (!((areg) & 0x8000)); \
+}
+
+#define	jpc_mqenc_byteout(areg, creg, ctreg, enc) \
+{ \
+	if ((enc)->outbuf != 0xff) { \
+		if ((creg) & 0x8000000) { \
+			if (++((enc)->outbuf) == 0xff) { \
+				(creg) &= 0x7ffffff; \
+				jpc_mqenc_byteout2(enc); \
+				enc->outbuf = ((creg) >> 20) & 0xff; \
+				(creg) &= 0xfffff; \
+				(ctreg) = 7; \
+			} else { \
+				jpc_mqenc_byteout2(enc); \
+				enc->outbuf = ((creg) >> 19) & 0xff; \
+				(creg) &= 0x7ffff; \
+				(ctreg) = 8; \
+			} \
+		} else { \
+			jpc_mqenc_byteout2(enc); \
+			(enc)->outbuf = ((creg) >> 19) & 0xff; \
+			(creg) &= 0x7ffff; \
+			(ctreg) = 8; \
+		} \
+	} else { \
+		jpc_mqenc_byteout2(enc); \
+		(enc)->outbuf = ((creg) >> 20) & 0xff; \
+		(creg) &= 0xfffff; \
+		(ctreg) = 7; \
+	} \
+}
+
+static void jpc_mqenc_byteout2(jpc_mqenc_t *enc)
+{
+	if (enc->outbuf >= 0) {
+		if (jas_stream_putc(enc->out, (unsigned char)enc->outbuf) == EOF) {
+			enc->err = true;
+		}
+	}
+	enc->lastbyte = enc->outbuf;
+}
+
+/******************************************************************************\
+* Local function protoypes.
+\******************************************************************************/
+
+static void jpc_mqenc_setbits(jpc_mqenc_t *mqenc);
+
+/******************************************************************************\
+* Code for creation and destruction of encoder.
+\******************************************************************************/
+
+/* Create a MQ encoder. */
+
+jpc_mqenc_t *jpc_mqenc_create(unsigned maxctxs, jas_stream_t *out)
+{
+	jpc_mqenc_t *mqenc;
+
+	/* Allocate memory for the MQ encoder. */
+	if (!(mqenc = jas_malloc(sizeof(jpc_mqenc_t)))) {
+		goto error;
+	}
+	mqenc->out = out;
+	mqenc->maxctxs = maxctxs;
+
+	/* Allocate memory for the per-context state information. */
+	if (!(mqenc->ctxs = jas_alloc2(mqenc->maxctxs, sizeof(jpc_mqstate_t *)))) {
+		goto error;
+	}
+
+	/* Set the current context to the first one. */
+	mqenc->curctx = mqenc->ctxs;
+
+	jpc_mqenc_init(mqenc);
+
+	/* Initialize the per-context state information to something sane. */
+	jpc_mqenc_setctxs(mqenc, 0, 0);
+
+	return mqenc;
+
+error:
+	if (mqenc) {
+		jpc_mqenc_destroy(mqenc);
+	}
+	return 0;
+}
+
+/* Destroy a MQ encoder. */
+
+void jpc_mqenc_destroy(jpc_mqenc_t *mqenc)
+{
+	jas_free(mqenc->ctxs);
+	jas_free(mqenc);
+}
+
+/******************************************************************************\
+* State initialization code.
+\******************************************************************************/
+
+/* Initialize the coding state of a MQ encoder. */
+
+void jpc_mqenc_init(jpc_mqenc_t *mqenc)
+{
+	mqenc->areg = 0x8000;
+	mqenc->outbuf = -1;
+	mqenc->creg = 0;
+	mqenc->ctreg = 12;
+	mqenc->lastbyte = -1;
+	mqenc->err = false;
+}
+
+/* Initialize one or more contexts. */
+
+void jpc_mqenc_setctxs(jpc_mqenc_t *mqenc, unsigned numctxs, const jpc_mqctx_t *ctxs)
+{
+	const jpc_mqstate_t **ctx;
+
+	ctx = mqenc->ctxs;
+	unsigned n = JAS_MIN(mqenc->maxctxs, numctxs);
+	while (n-- > 0) {
+		*ctx = &jpc_mqstates[2 * ctxs->ind + ctxs->mps];
+		++ctx;
+		++ctxs;
+	}
+	n = mqenc->maxctxs - numctxs;
+	while (n-- > 0) {
+		*ctx = &jpc_mqstates[0];
+		++ctx;
+	}
+
+}
+
+/* Get the coding state for a MQ encoder. */
+
+void jpc_mqenc_getstate(const jpc_mqenc_t *mqenc, jpc_mqencstate_t *state)
+{
+	state->areg = mqenc->areg;
+	state->creg = mqenc->creg;
+	state->ctreg = mqenc->ctreg;
+	state->lastbyte = mqenc->lastbyte;
+}
+
+/******************************************************************************\
+* Code for coding symbols.
+\******************************************************************************/
+
+/* Encode a bit. */
+
+int jpc_mqenc_putbit(jpc_mqenc_t *mqenc, bool bit)
+{
+	const jpc_mqstate_t *state;
+	JAS_LOGDEBUGF(100, "jpc_mqenc_putbit(%p, %d)\n", mqenc, bit);
+	JPC_MQENC_CALL(100, jpc_mqenc_dump(mqenc));
+
+	state = *(mqenc->curctx);
+
+	if (state->mps == bit) {
+		/* Apply the CODEMPS algorithm as defined in the standard. */
+		mqenc->areg -= state->qeval;
+		if (!(mqenc->areg & 0x8000)) {
+			jpc_mqenc_codemps2(mqenc);
+		} else {
+			mqenc->creg += state->qeval;
+		}
+	} else {
+		/* Apply the CODELPS algorithm as defined in the standard. */
+		jpc_mqenc_codelps2(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc->curctx, mqenc);
+	}
+
+	return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+int jpc_mqenc_codemps2(jpc_mqenc_t *mqenc)
+{
+	/* Note: This function only performs part of the work associated with
+	the CODEMPS algorithm from the standard.  Some of the work is also
+	performed by the caller. */
+
+	const jpc_mqstate_t *state = *(mqenc->curctx);
+	if (mqenc->areg < state->qeval) {
+		mqenc->areg = state->qeval;
+	} else {
+		mqenc->creg += state->qeval;
+	}
+	*mqenc->curctx = state->nmps;
+	jpc_mqenc_renorme(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+	return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+int jpc_mqenc_codelps(jpc_mqenc_t *mqenc)
+{
+	jpc_mqenc_codelps2(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc->curctx, mqenc);
+	return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+/******************************************************************************\
+* Miscellaneous code.
+\******************************************************************************/
+
+/* Terminate the code word. */
+
+int jpc_mqenc_flush(jpc_mqenc_t *mqenc, int termmode)
+{
+	int_fast16_t k;
+
+	switch (termmode) {
+	case JPC_MQENC_PTERM:
+		k = 11 - mqenc->ctreg + 1;
+		while (k > 0) {
+			mqenc->creg <<= mqenc->ctreg;
+			mqenc->ctreg = 0;
+			jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg,
+			  mqenc);
+			k -= mqenc->ctreg;
+		}
+		if (mqenc->outbuf != 0xff) {
+			jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+		}
+		break;
+	case JPC_MQENC_DEFTERM:
+		jpc_mqenc_setbits(mqenc);
+		mqenc->creg <<= mqenc->ctreg;
+		jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+		mqenc->creg <<= mqenc->ctreg;
+		jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+		if (mqenc->outbuf != 0xff) {
+			jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+		}
+		break;
+	default:
+		assert(false);
+		JAS_UNREACHABLE();
+	}
+	return 0;
+}
+
+static void jpc_mqenc_setbits(jpc_mqenc_t *mqenc)
+{
+	uint_least32_t tmp = mqenc->creg + mqenc->areg;
+	mqenc->creg |= 0xffff;
+	if (mqenc->creg >= tmp) {
+		mqenc->creg -= 0x8000;
+	}
+}
+
+/* Dump a MQ encoder to a stream for debugging. */
+
+int jpc_mqenc_dump(const jpc_mqenc_t *mqenc)
+{
+	jas_logprintf("AREG = %08"PRIxLEAST32", CREG = %08"PRIxLEAST32", CTREG = %"PRIuLEAST32"\n",
+	  mqenc->areg, mqenc->creg, mqenc->ctreg);
+	jas_logprintf("IND = %02"PRIdPTR", MPS = %d, QEVAL = %04"PRIxLEAST16"\n",
+	  *mqenc->curctx - jpc_mqstates, (*mqenc->curctx)->mps,
+	  (*mqenc->curctx)->qeval);
+	return 0;
+}
--- /dev/null
+++ b/jpc_mqenc.h
@@ -1,0 +1,217 @@
+/*
+ * 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 Encoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_MQENC_H
+#define JPC_MQENC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+
+#include "jpc_mqcod.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/*
+ * Termination modes.
+ */
+
+#define	JPC_MQENC_DEFTERM	0	/* default termination */
+#define	JPC_MQENC_PTERM		1	/* predictable termination */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* MQ arithmetic encoder class. */
+
+typedef struct {
+
+	/* The C register. */
+	uint_least32_t creg;
+
+	/* The A register. */
+	uint_least32_t areg;
+
+	/* The CT register. */
+	uint_least32_t ctreg;
+
+	/* The maximum number of contexts. */
+	unsigned maxctxs;
+
+	/* The per-context information. */
+	const jpc_mqstate_t **ctxs;
+
+	/* The current context. */
+	const jpc_mqstate_t **curctx;
+
+	/* The stream for encoder output. */
+	jas_stream_t *out;
+
+	/* The byte buffer (i.e., the B variable in the standard). */
+	int_least16_t outbuf;
+
+	/* The last byte output. */
+	int_least16_t lastbyte;
+
+	/* The error indicator. */
+	bool err;
+	
+} jpc_mqenc_t;
+
+/* MQ arithmetic encoder state information. */
+
+typedef struct {
+
+	/* The A register. */
+	unsigned areg;
+
+	/* The C register. */
+	unsigned creg;
+
+	/* The CT register. */
+	unsigned ctreg;
+
+	/* The last byte output by the encoder. */
+	int lastbyte;
+
+} jpc_mqencstate_t;
+
+/******************************************************************************\
+* Functions/macros for construction and destruction.
+\******************************************************************************/
+
+/* Create a MQ encoder. */
+jpc_mqenc_t *jpc_mqenc_create(unsigned maxctxs, jas_stream_t *out);
+
+/* Destroy a MQ encoder. */
+void jpc_mqenc_destroy(jpc_mqenc_t *enc);
+
+/******************************************************************************\
+* Functions/macros for initialization.
+\******************************************************************************/
+
+/* Initialize a MQ encoder. */
+void jpc_mqenc_init(jpc_mqenc_t *enc);
+
+/******************************************************************************\
+* Functions/macros for context manipulation.
+\******************************************************************************/
+
+/* Set the current context. */
+static inline void jpc_mqenc_setcurctx(jpc_mqenc_t *enc, unsigned ctxno) {
+	enc->curctx = &enc->ctxs[ctxno];
+}
+
+/* Set the state information for multiple contexts. */
+void jpc_mqenc_setctxs(jpc_mqenc_t *enc, unsigned numctxs, const jpc_mqctx_t *ctxs);
+
+/******************************************************************************\
+* Miscellaneous functions/macros.
+\******************************************************************************/
+
+/* Get the error state of a MQ encoder. */
+static inline bool jpc_mqenc_error(const jpc_mqenc_t *enc) {
+	return enc->err;
+}
+
+/* Get the current encoder state. */
+void jpc_mqenc_getstate(const jpc_mqenc_t *enc, jpc_mqencstate_t *state);
+
+/* Terminate the code. */
+int jpc_mqenc_flush(jpc_mqenc_t *enc, int termmode);
+
+/******************************************************************************\
+* Functions/macros for encoding bits.
+\******************************************************************************/
+
+/******************************************************************************\
+* Functions/macros for debugging.
+\******************************************************************************/
+
+int jpc_mqenc_dump(const jpc_mqenc_t *mqenc);
+
+/******************************************************************************\
+* Implementation-specific details.
+\******************************************************************************/
+
+/* Note: These function prototypes are included only to satisfy the
+  needs of the mqenc_putbit_macro macro.  Do not call any of these
+  functions directly. */
+int jpc_mqenc_codemps2(jpc_mqenc_t *enc);
+int jpc_mqenc_codelps(jpc_mqenc_t *enc);
+
+int jpc_mqenc_putbit(jpc_mqenc_t *enc, bool bit);
+
+#endif
--- a/jpc_qmfb.c
+++ b/jpc_qmfb.c
@@ -82,22 +82,22 @@
 #include "jpc_math.h"
 
 #include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
 
 /******************************************************************************\
 *
 \******************************************************************************/
 
-#define QMFB_SPLITBUFSIZE	4096
-#define	QMFB_JOINBUFSIZE	4096
+#define QMFB_SPLITJOINBUFSIZE 1024
 
-static int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+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 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 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 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);
@@ -121,16 +121,20 @@
 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_row(jpc_fix_t *a, unsigned numrows, bool parity, jpc_fix_t*, unsigned);
+static void jpc_qmfb_split_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride, bool parity, jpc_fix_t*, unsigned);
 static void jpc_qmfb_split_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols, unsigned stride,
-  bool parity);
+  bool parity, jpc_fix_t*, unsigned);
 
-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);
+void jpc_qmfb_join_row(jpc_fix_t *a, unsigned numcols, bool parity, jpc_fix_t*, unsigned);
+static void jpc_qmfb_join_colgrp(jpc_fix_t *a, unsigned numrows, unsigned stride, bool parity, jpc_fix_t*, unsigned);
 static void jpc_qmfb_join_colres(jpc_fix_t *a, unsigned numrows, unsigned numcols, unsigned stride,
-  bool parity);
+  bool parity, jpc_fix_t*, unsigned);
 
+/******************************************************************************\
+* Data.
+\******************************************************************************/
+
 static const double jpc_ft_lpenergywts[32] = {
 	1.2247448713915889,
 	1.6583123951776999,
@@ -292,21 +296,15 @@
 * generic
 \******************************************************************************/
 
-static void jpc_qmfb_split_row(jpc_fix_t *a, unsigned numcols, bool parity)
+static void jpc_qmfb_split_row(jpc_fix_t *a, unsigned numcols, bool parity,
+  jpc_fix_t *buffer, unsigned buffersize)
 {
-	jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
-	jpc_fix_t *buf = splitbuf;
+	jpc_fix_t *buf = buffer;
 	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();
-		}
-	}
+	assert(buffersize >= bufsize);
 
 	if (numcols >= 2) {
 		const unsigned hstartcol = (numcols + !parity) >> 1;
@@ -338,34 +336,20 @@
 			++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)
+  bool parity,
+  jpc_fix_t *buffer, unsigned buffersize)
 {
-
-	jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
-	jpc_fix_t *buf = splitbuf;
+	jpc_fix_t *buf = buffer;
 	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();
-		}
-	}
+	const size_t bufsize = JPC_QMFB_COLGRPSIZE * JPC_CEILDIVPOW2(numrows, 1);
+	assert(buffersize >= bufsize);
 
 	if (numrows >= 2) {
 		const unsigned hstartrow = (numrows + !parity) >> 1;
@@ -415,33 +399,20 @@
 			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)
+  unsigned stride, bool parity,
+  jpc_fix_t *buffer, unsigned buffersize)
 {
-
-	jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
-	jpc_fix_t *buf = splitbuf;
+	jpc_fix_t *buf = buffer;
 	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();
-		}
-	}
+	const size_t bufsize = numcols * JPC_CEILDIVPOW2(numrows, 1);
+	assert(buffersize >= bufsize);
 
 	if (numrows >= 2) {
 		const unsigned hstartcol = (numrows + !parity) >> 1;
@@ -491,30 +462,18 @@
 			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)
+void jpc_qmfb_join_row(jpc_fix_t *a, unsigned numcols, bool parity,
+  jpc_fix_t *buffer, unsigned buffersize)
 {
-
-	jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
-	jpc_fix_t *buf = joinbuf;
+	jpc_fix_t *buf = buffer;
 	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();
-		}
-	}
+	assert(buffersize >= bufsize);
 
 	const unsigned hstartcol = (numcols + !parity) >> 1;
 
@@ -542,34 +501,20 @@
 		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)
+  bool parity,
+  jpc_fix_t *buffer, unsigned buffersize)
 {
-
-	jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
-	jpc_fix_t *buf = joinbuf;
+	jpc_fix_t *buf = buffer;
 	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 size_t bufsize = JPC_QMFB_COLGRPSIZE * JPC_CEILDIVPOW2(numrows, 1);
+	assert(buffersize >= bufsize);
 
 	const unsigned hstartcol = (numrows + !parity) >> 1;
 
@@ -615,20 +560,13 @@
 		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)
+  unsigned stride, bool parity,
+  jpc_fix_t *buffer, unsigned buffersize)
 {
-
-	jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
-	jpc_fix_t *buf = joinbuf;
+	jpc_fix_t *buf = buffer;
 	jpc_fix_t *srcptr;
 	jpc_fix_t *dstptr;
 	register jpc_fix_t *srcptr2;
@@ -635,13 +573,8 @@
 	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 size_t bufsize = numcols * JPC_CEILDIVPOW2(numrows, 1);
+	assert(buffersize >= bufsize);
 
 	const unsigned hstartcol = (numrows + !parity) >> 1;
 
@@ -687,12 +620,6 @@
 		dstptr += 2 * stride;
 		srcptr += numcols;
 	}
-
-	/* If the join buffer was allocated on the heap, free this memory. */
-	if (buf != joinbuf) {
-		jas_free(buf);
-	}
-
 }
 
 /******************************************************************************\
@@ -1219,9 +1146,12 @@
 
 }
 
-static int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
   int stride)
 {
+	jpc_fix_t localbuf[QMFB_SPLITJOINBUFSIZE];
+	unsigned bufsize;
+	jpc_fix_t *buf;
 	const unsigned numrows = height;
 	const unsigned numcols = width;
 	const unsigned rowparity = ystart & 1;
@@ -1229,15 +1159,25 @@
 	jpc_fix_t *startptr;
 
 	const unsigned maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+	bufsize = JAS_MAX(width, JPC_QMFB_COLGRPSIZE * height);
+	if (bufsize > QMFB_SPLITJOINBUFSIZE) {
+		if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
+			return -1;
+		}
+	} else {
+		buf = localbuf;
+		bufsize = QMFB_SPLITJOINBUFSIZE;
+	}
+
 	startptr = &a[0];
 	for (unsigned i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
-		jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity);
+		jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity, buf, bufsize);
 		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);
+		  rowparity, buf, bufsize);
 		jpc_ft_fwdlift_colres(startptr, numrows, numcols - maxcols, stride,
 		  rowparity);
 	}
@@ -1244,37 +1184,53 @@
 
 	startptr = &a[0];
 	for (unsigned i = 0; i < numrows; ++i) {
-		jpc_qmfb_split_row(startptr, numcols, colparity);
+		jpc_qmfb_split_row(startptr, numcols, colparity, buf, bufsize);
 		jpc_ft_fwdlift_row(startptr, numcols, colparity);
 		startptr += stride;
 	}
 
+	if (buf != localbuf) {
+		jas_free(buf);
+	}
+
 	return 0;
 
 }
 
-static int jpc_ft_synthesize(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+int jpc_ft_synthesize(jpc_fix_t *a, int xstart, int ystart, int width, int height,
   int stride)
 {
+	jpc_fix_t localbuf[QMFB_SPLITJOINBUFSIZE];
+	unsigned bufsize;
+	jpc_fix_t *buf;
 	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;
+	bufsize = JAS_MAX(width, JPC_QMFB_COLGRPSIZE * height);
+	if (bufsize > QMFB_SPLITJOINBUFSIZE) {
+		if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
+			return -1;
+		}
+	} else {
+		buf = localbuf;
+		bufsize = QMFB_SPLITJOINBUFSIZE;
+	}
+
 	startptr = &a[0];
 	for (unsigned i = 0; i < numrows; ++i) {
 		jpc_ft_invlift_row(startptr, numcols, colparity);
-		jpc_qmfb_join_row(startptr, numcols, colparity);
+		jpc_qmfb_join_row(startptr, numcols, colparity, buf, bufsize);
 		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);
+		jpc_qmfb_join_colgrp(startptr, numrows, stride, rowparity, buf, bufsize);
 		startptr += JPC_QMFB_COLGRPSIZE;
 	}
 	if (maxcols < numcols) {
@@ -1281,11 +1237,14 @@
 		jpc_ft_invlift_colres(startptr, numrows, numcols - maxcols, stride,
 		  rowparity);
 		jpc_qmfb_join_colres(startptr, numrows, numcols - maxcols, stride,
-		  rowparity);
+		  rowparity, buf, bufsize);
 	}
 
-	return 0;
+	if (buf != localbuf) {
+		jas_free(buf);
+	}
 
+	return 0;
 }
 
 /******************************************************************************\
@@ -2135,9 +2094,12 @@
 
 }
 
-static int jpc_ns_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+int jpc_ns_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
   int stride)
 {
+	jpc_fix_t localbuf[QMFB_SPLITJOINBUFSIZE];
+	unsigned bufsize;
+	jpc_fix_t *buf;
 
 	const unsigned numrows = height;
 	const unsigned numcols = width;
@@ -2144,17 +2106,27 @@
 	const unsigned rowparity = ystart & 1;
 	const unsigned colparity = xstart & 1;
 	jpc_fix_t *startptr;
-
 	const unsigned maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+
+	bufsize = JAS_MAX(width, JPC_QMFB_COLGRPSIZE * height);
+	if (bufsize > QMFB_SPLITJOINBUFSIZE) {
+		if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
+			return -1;
+		}
+	} else {
+		buf = localbuf;
+		bufsize = QMFB_SPLITJOINBUFSIZE;
+	}
+
 	startptr = &a[0];
 	for (unsigned i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
-		jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity);
+		jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity, buf, bufsize);
 		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);
+		  rowparity, buf, bufsize);
 		jpc_ns_fwdlift_colres(startptr, numrows, numcols - maxcols, stride,
 		  rowparity);
 	}
@@ -2161,18 +2133,24 @@
 
 	startptr = &a[0];
 	for (unsigned i = 0; i < numrows; ++i) {
-		jpc_qmfb_split_row(startptr, numcols, colparity);
+		jpc_qmfb_split_row(startptr, numcols, colparity, buf, bufsize);
 		jpc_ns_fwdlift_row(startptr, numcols, colparity);
 		startptr += stride;
 	}
 
-	return 0;
+	if (buf != localbuf) {
+		jas_free(buf);
+	}
 
+	return 0;
 }
 
-static int jpc_ns_synthesize(jpc_fix_t *a, int xstart, int ystart, int width,
+int jpc_ns_synthesize(jpc_fix_t *a, int xstart, int ystart, int width,
   int height, int stride)
 {
+	jpc_fix_t localbuf[QMFB_SPLITJOINBUFSIZE];
+	unsigned bufsize;
+	jpc_fix_t *buf;
 
 	const unsigned numrows = height;
 	const unsigned numcols = width;
@@ -2180,18 +2158,28 @@
 	const unsigned colparity = xstart & 1;
 	jpc_fix_t *startptr;
 
+	const unsigned maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+	bufsize = JAS_MAX(width, JPC_QMFB_COLGRPSIZE * height);
+	if (bufsize > QMFB_SPLITJOINBUFSIZE) {
+		if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
+			return -1;
+		}
+	} else {
+		buf = localbuf;
+		bufsize = QMFB_SPLITJOINBUFSIZE;
+	}
+
 	startptr = &a[0];
 	for (unsigned i = 0; i < numrows; ++i) {
 		jpc_ns_invlift_row(startptr, numcols, colparity);
-		jpc_qmfb_join_row(startptr, numcols, colparity);
+		jpc_qmfb_join_row(startptr, numcols, colparity, buf, bufsize);
 		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);
+		jpc_qmfb_join_colgrp(startptr, numrows, stride, rowparity, buf, bufsize);
 		startptr += JPC_QMFB_COLGRPSIZE;
 	}
 	if (maxcols < numcols) {
@@ -2198,10 +2186,12 @@
 		jpc_ns_invlift_colres(startptr, numrows, numcols - maxcols, stride,
 		  rowparity);
 		jpc_qmfb_join_colres(startptr, numrows, numcols - maxcols, stride,
-		  rowparity);
+		  rowparity, buf, bufsize);
 	}
 
-	return 0;
+	if (buf != localbuf) {
+		jas_free(buf);
+	}
 
+	return 0;
 }
-
--- a/jpc_t1cod.c
+++ b/jpc_t1cod.c
@@ -112,8 +112,6 @@
 JAS_ATTRIBUTE_CONST
 static uint_least8_t jpc_getmagctxno(unsigned f);
 
-static void jpc_initmqctxs(void);
-
 /******************************************************************************\
 * Code.
 \******************************************************************************/
@@ -120,7 +118,7 @@
 
 enum jpc_passtype JPC_PASSTYPE(unsigned passno)
 {
-	unsigned passtype = -1;
+	unsigned passtype = 0;
 	switch (passno % 3) {
 	case 0:
 		passtype = JPC_CLNPASS;
@@ -140,8 +138,7 @@
 
 unsigned JPC_NOMINALGAIN(unsigned qmfbid, unsigned numlvls, unsigned lvlno, enum jpc_tsfb_orient orient)
 {
-	/* Avoid compiler warnings about unused parameters. */
-	(void)numlvls;
+	JAS_UNUSED(numlvls);
 
 	if (qmfbid == JPC_COX_INS) {
 		return 0;
@@ -162,6 +159,7 @@
 			JAS_UNREACHABLE();
 		}
 	}
+	JAS_UNREACHABLE();
 	return -1;
 }
 
@@ -184,7 +182,7 @@
 
 unsigned JPC_SEGPASSCNT(unsigned passno, unsigned firstpassno, unsigned numpasses, bool bypass, bool termall)
 {
-	unsigned ret = -1;
+	unsigned ret = 0;
 
 	if (termall) {
 		ret = 1;
@@ -236,9 +234,6 @@
 	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);
@@ -263,9 +258,13 @@
 		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));
+		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));
+		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;
@@ -272,9 +271,13 @@
 		} 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));
+		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));
+		jpc_refnmsedec0[i] = jpc_dbltofix(floor((u * u) *
+		  jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) /
+		  jpc_pow2i(JPC_NMSEDEC_FRACBITS));
 	}
 }
 
@@ -282,7 +285,7 @@
 {
 	assert(orient < 4);
 
-	unsigned n = -1;
+	unsigned n = 0;
 	unsigned t;
 	unsigned hv;
 
@@ -460,7 +463,7 @@
 	}
 }
 
-static void jpc_initmqctxs()
+void jpc_initmqctxs()
 {
 	jpc_initctxs(jpc_mqctxs);
 }
--- a/jpc_t1cod.h
+++ b/jpc_t1cod.h
@@ -294,6 +294,8 @@
 /* Initialize the lookup tables used by the codec. */
 void jpc_initluts(void);
 
+void jpc_initmqctxs(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);
--- a/jpc_t1dec.c
+++ b/jpc_t1dec.c
@@ -77,6 +77,7 @@
 #include "jpc_t1cod.h"
 #include "jpc_dec.h"
 
+#include "jasper/jas_thread.h"
 #include "jasper/jas_stream.h"
 #include "jasper/jas_math.h"
 #include "jasper/jas_debug.h"
@@ -98,8 +99,8 @@
 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;
+#if defined(JAS_ENABLE_NON_THREAD_SAFE_DEBUGGING)
+static size_t t1dec_cnt = 0;
 #endif
 
 JAS_FORCE_INLINE
@@ -106,14 +107,15 @@
 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);
+#if defined(JAS_ENABLE_NON_THREAD_SAFE_DEBUGGING)
+	if (jas_get_debug_level() >= 100) {
+		jas_logdebugf(100, "index = %zu; passtype = %s; symtype = %s; sym = %d\n",
+		  t1dec_cnt, passtypename, symtypename, v);
 		++t1dec_cnt;
 	}
 #else
-	(void)passtypename;
-	(void)symtypename;
+	JAS_UNUSED(passtypename);
+	JAS_UNUSED(symtypename);
 #endif
 	return v;
 }
@@ -128,14 +130,14 @@
 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);
+#if defined(JAS_ENABLE_NON_THREAD_SAFE_DEBUGGING)
+	if (jas_get_debug_level() >= 100) {
+		jas_logdebugf(100, "index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v);
 		++t1dec_cnt;
 	}
 #else
-	(void)passtypename;
-	(void)symtypename;
+	JAS_UNUSED(passtypename);
+	JAS_UNUSED(symtypename);
 #endif
 	return v;
 }
@@ -244,10 +246,10 @@
 		for (unsigned i = 0; i < seg->numpasses; ++i) {
 			if (cblk->numimsbs > band->numbps) {
 				if (ccp->roishift <= 0) {
-					jas_eprintf("warning: corrupt code stream\n");
+					jas_logwarnf("warning: corrupt code stream\n");
 				} else {
 					if (cblk->numimsbs < ccp->roishift - band->numbps) {
-						jas_eprintf("warning: corrupt code stream\n");
+						jas_logwarnf("warning: corrupt code stream\n");
 					}
 				}
 			}
@@ -292,7 +294,7 @@
 			}
 
 			if (ret) {
-				jas_eprintf("coding pass failed passtype=%d segtype=%d\n", passtype, seg->type);
+				jas_logerrorf("coding pass failed passtype=%d segtype=%d\n", passtype, seg->type);
 				goto error;
 			}
 
@@ -313,7 +315,7 @@
 			  filldata)) < 0) {
 				goto error;
 			} else if (ret > 0) {
-				jas_eprintf("warning: bad termination pattern detected\n");
+				jas_logwarnf("warning: bad termination pattern detected\n");
 			}
 			jpc_bitstream_close(nulldec);
 			nulldec = 0;
@@ -791,7 +793,7 @@
 		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");
+			jas_logwarnf("warning: bad segmentation symbol\n");
 		}
 	}
 
--- /dev/null
+++ b/jpc_t1enc.c
@@ -1,0 +1,895 @@
+/*
+ * 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 Encoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_t1enc.h"
+#include "jpc_t1cod.h"
+#include "jpc_enc.h"
+#include "jpc_math.h"
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+/* Encode a single code block. */
+static int jpc_enc_enccblk(const jpc_enc_tcmpt_t *comp,
+  const jpc_enc_band_t *band, jpc_enc_cblk_t *cblk);
+
+static int jpc_encsigpass(jpc_mqenc_t *mqenc, int bitpos, enum jpc_tsfb_orient orient, bool vcausalflag,
+  jas_matrix_t *flags, const jas_matrix_t *data, int term, long *nmsedec);
+
+static int jpc_encrefpass(jpc_mqenc_t *mqenc, int bitpos, jas_matrix_t *flags,
+  const jas_matrix_t *data, int term, long *nmsedec);
+
+static int jpc_encclnpass(jpc_mqenc_t *mqenc, int bitpos, enum jpc_tsfb_orient orient, bool vcausalflag,
+  bool segsym, jas_matrix_t *flags, const jas_matrix_t *data, int term, long *nmsedec);
+
+static int jpc_encrawsigpass(jpc_bitstream_t *out, int bitpos, bool vcausalflag,
+  jas_matrix_t *flags, const jas_matrix_t *data, int term, long *nmsedec);
+
+static int jpc_encrawrefpass(jpc_bitstream_t *out, int bitpos,
+  jas_matrix_t *flags, const jas_matrix_t *data, int term, long *nmsedec);
+
+/******************************************************************************\
+* Code for encoding code blocks.
+\******************************************************************************/
+
+/* Encode all of the code blocks associated with the current tile. */
+int jpc_enc_enccblks(jpc_enc_t *enc)
+{
+	jpc_enc_tcmpt_t *tcmpt;
+	jpc_enc_tcmpt_t *endcomps;
+	jpc_enc_rlvl_t *lvl;
+	jpc_enc_rlvl_t *endlvls;
+	jpc_enc_band_t *band;
+	jpc_enc_band_t *endbands;
+	jpc_enc_cblk_t *cblk;
+	jpc_enc_cblk_t *endcblks;
+	jpc_fix_t mx;
+	jpc_fix_t bmx;
+	jpc_fix_t v;
+	jpc_enc_tile_t *tile;
+	uint_fast32_t prcno;
+	jpc_enc_prc_t *prc;
+
+	tile = enc->curtile;
+
+	endcomps = &tile->tcmpts[tile->numtcmpts];
+	for (tcmpt = tile->tcmpts; tcmpt != endcomps; ++tcmpt) {
+		endlvls = &tcmpt->rlvls[tcmpt->numrlvls];
+		for (lvl = tcmpt->rlvls; lvl != endlvls; ++lvl) {
+			if (!lvl->bands) {
+				continue;
+			}
+			endbands = &lvl->bands[lvl->numbands];
+			for (band = lvl->bands; band != endbands; ++band) {
+				if (!band->data) {
+					continue;
+				}
+				for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
+					if (!prc->cblks) {
+						continue;
+					}
+					bmx = 0;
+					endcblks = &prc->cblks[prc->numcblks];
+					for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+						mx = 0;
+						for (jas_matind_t i = 0; i < jas_matrix_numrows(cblk->data); ++i) {
+							for (jas_matind_t j = 0; j < jas_matrix_numcols(cblk->data); ++j) {
+								v = JAS_ABS(jas_matrix_get(cblk->data, i, j));
+								if (v > mx) {
+									mx = v;
+								}
+							}
+						}
+						if (mx > bmx) {
+							bmx = mx;
+						}
+						cblk->numbps = JAS_MAX(jpc_fix_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0);
+					}
+
+					for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+						cblk->numimsbs = band->numbps - cblk->numbps;
+						assert(cblk->numimsbs >= 0);
+					}
+
+					for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+						if (jpc_enc_enccblk(tcmpt, band, cblk)) {
+							return -1;
+						}
+					}
+				}
+			}
+		}
+	}
+	return 0;
+}
+
+static int getthebyte(jas_stream_t *in, long off)
+{
+	int c;
+	long oldpos;
+	oldpos = jas_stream_tell(in);
+	assert(oldpos >= 0);
+	jas_stream_seek(in, off, SEEK_SET);
+	c = jas_stream_peekc(in);
+	jas_stream_seek(in, oldpos, SEEK_SET);
+	return c;
+}
+
+/* Encode a single code block. */
+static int jpc_enc_enccblk(const jpc_enc_tcmpt_t *tcmpt, const jpc_enc_band_t *band, jpc_enc_cblk_t *cblk)
+{
+	jpc_enc_pass_t *pass;
+	jpc_enc_pass_t *endpasses;
+	int bitpos;
+	int n;
+	int ret = -1;
+	jpc_bitstream_t *bout;
+	int c;
+
+	bout = 0;
+
+	if (!(cblk->stream = jas_stream_memopen(0, 0))) {
+		goto error;
+	}
+	if (!(cblk->mqenc = jpc_mqenc_create(JPC_NUMCTXS, cblk->stream))) {
+		goto error;
+	}
+	jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs);
+
+	cblk->numpasses = (cblk->numbps > 0) ? (3 * cblk->numbps - 2) : 0;
+	if (cblk->numpasses > 0) {
+		if (!(cblk->passes = jas_alloc2(cblk->numpasses,
+		  sizeof(jpc_enc_pass_t)))) {
+			goto error;
+		};
+	} else {
+		cblk->passes = 0;
+	}
+	endpasses = (cblk->passes) ? &cblk->passes[cblk->numpasses] : 0;
+	for (pass = cblk->passes; pass != endpasses; ++pass) {
+		pass->start = 0;
+		pass->end = 0;
+		pass->term = JPC_ISTERMINATED(pass - cblk->passes, 0, cblk->numpasses,
+		  (tcmpt->cblksty & JPC_COX_TERMALL) != 0,
+		  (tcmpt->cblksty & JPC_COX_LAZY) != 0);
+		pass->type = JPC_SEGTYPE(pass - cblk->passes, 0,
+		  (tcmpt->cblksty & JPC_COX_LAZY) != 0);
+		pass->lyrno = -1;
+		if (pass == endpasses - 1) {
+			assert(pass->term == 1);
+			pass->term = 1;
+		}
+	}
+
+	if (!(cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + 2,
+	  jas_matrix_numcols(cblk->data) + 2))) {
+		jas_logerrorf("cannot create matrix\n");
+		goto error;
+	}
+
+	bitpos = cblk->numbps - 1;
+	pass = cblk->passes;
+	n = cblk->numpasses;
+	while (--n >= 0) {
+
+		if (pass->type == JPC_SEG_MQ) {
+			/* NOP */
+		} else {
+			assert(pass->type == JPC_SEG_RAW);
+			if (!bout) {
+				bout = jpc_bitstream_sopen(cblk->stream, "w");
+				if (!bout) {
+					goto error;
+				}
+			}
+		}
+
+		enum jpc_passtype passtype = JPC_PASSTYPE(pass - cblk->passes);
+		pass->start = jas_stream_tell(cblk->stream);
+#if 0
+assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream));
+#endif
+		assert(bitpos >= 0);
+		const bool vcausal = (tcmpt->cblksty & JPC_COX_VSC) != 0;
+		const bool segsym = (tcmpt->cblksty & JPC_COX_SEGSYM) != 0;
+		unsigned termmode;
+		if (pass->term) {
+			termmode = ((tcmpt->cblksty & JPC_COX_PTERM) ?
+			  JPC_MQENC_PTERM : JPC_MQENC_DEFTERM) + 1;
+		} else {
+			termmode = 0;
+		}
+		switch (passtype) {
+		case JPC_SIGPASS:
+			ret = (pass->type == JPC_SEG_MQ) ? jpc_encsigpass(cblk->mqenc,
+			  bitpos, band->orient, vcausal, cblk->flags,
+			  cblk->data, termmode, &pass->nmsedec) :
+			  jpc_encrawsigpass(bout, bitpos, vcausal, cblk->flags,
+			  cblk->data, termmode, &pass->nmsedec);
+			break;
+		case JPC_REFPASS:
+			ret = (pass->type == JPC_SEG_MQ) ? jpc_encrefpass(cblk->mqenc,
+			  bitpos, cblk->flags, cblk->data, termmode,
+			  &pass->nmsedec) : jpc_encrawrefpass(bout, bitpos,
+			  cblk->flags, cblk->data, termmode,
+			  &pass->nmsedec);
+			break;
+		case JPC_CLNPASS:
+			assert(pass->type == JPC_SEG_MQ);
+			ret = jpc_encclnpass(cblk->mqenc, bitpos, band->orient,
+			  vcausal, segsym, cblk->flags, cblk->data, termmode,
+			  &pass->nmsedec);
+			break;
+		default:
+			assert(0);
+			break;
+		}
+
+		if (ret) {
+			if (bout) {
+				jpc_bitstream_close(bout);
+			}
+			goto error;
+		}
+
+		if (pass->type == JPC_SEG_MQ) {
+			if (pass->term) {
+				jpc_mqenc_init(cblk->mqenc);
+			}
+			jpc_mqenc_getstate(cblk->mqenc, &pass->mqencstate);
+			pass->end = jas_stream_tell(cblk->stream);
+			if (tcmpt->cblksty & JPC_COX_RESET) {
+				jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs);
+			}
+		} else {
+			if (pass->term) {
+				if (jpc_bitstream_pending(bout)) {
+					jpc_bitstream_outalign(bout, 0x2a);
+				}
+				jpc_bitstream_close(bout);
+				bout = 0;
+				pass->end = jas_stream_tell(cblk->stream);
+			} else {
+				pass->end = jas_stream_tell(cblk->stream) +
+				  jpc_bitstream_pending(bout);
+/* NOTE - This will not work.  need to adjust by # of pending output bytes */
+			}
+		}
+#if 0
+/* XXX - This assertion fails sometimes when various coding modes are used.
+This seems to be harmless, but why does it happen at all? */
+assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream));
+#endif
+
+		pass->wmsedec = jpc_fixtodbl(band->rlvl->tcmpt->synweight) *
+		  jpc_fixtodbl(band->rlvl->tcmpt->synweight) *
+		  jpc_fixtodbl(band->synweight) *
+		  jpc_fixtodbl(band->synweight) *
+		  jpc_fixtodbl(band->absstepsize) * jpc_fixtodbl(band->absstepsize) *
+		  ((double) (1 << bitpos)) * ((double)(1 << bitpos)) *
+		  jpc_fixtodbl(pass->nmsedec);
+		pass->cumwmsedec = pass->wmsedec;
+		if (pass != cblk->passes) {
+			pass->cumwmsedec += pass[-1].cumwmsedec;
+		}
+		if (passtype == JPC_CLNPASS) {
+			--bitpos;
+		}
+		++pass;
+	}
+
+#if 0
+dump_passes(cblk->passes, cblk->numpasses, cblk);
+#endif
+
+	n = 0;
+	endpasses = (cblk->passes) ? &cblk->passes[cblk->numpasses] : 0;
+	for (pass = cblk->passes; pass != endpasses; ++pass) {
+		if (pass->start < n) {
+			pass->start = n;
+		}
+		if (pass->end < n) {
+			pass->end = n;
+		}
+		if (!pass->term) {
+			const jpc_enc_pass_t *termpass = pass;
+			while (termpass - pass < cblk->numpasses &&
+			  !termpass->term) {
+				++termpass;
+			}
+			if (pass->type == JPC_SEG_MQ) {
+				unsigned t = (pass->mqencstate.lastbyte == 0xff) ? 1 : 0;
+				unsigned adjust;
+				if (pass->mqencstate.ctreg >= 5) {
+					adjust = 4 + t;
+				} else {
+					adjust = 5 + t;
+				}
+				pass->end += adjust;
+			}
+			if (pass->end > termpass->end) {
+				pass->end = termpass->end;
+			}
+			if ((c = getthebyte(cblk->stream, pass->end - 1)) == EOF) {
+				if (bout) {
+					jpc_bitstream_close(bout);
+				}
+				return -1;
+			}
+			if (c == 0xff) {
+				++pass->end;
+			}
+			n = JAS_MAX(n, pass->end);
+		} else {
+			n = JAS_MAX(n, pass->end);
+		}
+	}
+
+#if 0
+dump_passes(cblk->passes, cblk->numpasses, cblk);
+#endif
+
+	if (bout) {
+		jpc_bitstream_close(bout);
+	}
+
+	return 0;
+
+error:
+	return -1;
+}
+
+/******************************************************************************\
+* Code for significance pass.
+\******************************************************************************/
+
+#define	sigpass_step(fp, frowstep, dp, bitpos, one, nmsedec, orient, mqenc, vcausalflag) \
+{ \
+	jpc_fix_t f; \
+	f = *(fp); \
+	if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
+		bool v = (JAS_ABS(*(dp)) & (one)) != 0; \
+		jpc_mqenc_setcurctx(mqenc, JPC_GETZCCTXNO(f, (orient))); \
+		jpc_mqenc_putbit(mqenc, v); \
+		if (v) { \
+			*(nmsedec) += JPC_GETSIGNMSEDEC(JAS_ABS(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \
+			v = ((*(dp) < 0) ? 1 : 0); \
+			jpc_mqenc_setcurctx(mqenc, JPC_GETSCCTXNO(f)); \
+			jpc_mqenc_putbit(mqenc, v ^ JPC_GETSPB(f)); \
+			JPC_UPDATEFLAGS4(fp, frowstep, v, vcausalflag); \
+			*(fp) |= JPC_SIG; \
+		} \
+		*(fp) |= JPC_VISIT; \
+	} \
+}
+
+static int jpc_encsigpass(jpc_mqenc_t *mqenc, int bitpos, enum jpc_tsfb_orient orient, bool vcausalflag,
+  jas_matrix_t *flags, const jas_matrix_t *data, int term, long *nmsedec)
+{
+	int i;
+	int one;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fp;
+	jpc_fix_t *fvscanstart;
+
+	*nmsedec = 0;
+	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;
+
+	one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	const jpc_fix_t *dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		const jpc_fix_t *dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			const jpc_fix_t *dp = dvscanstart;
+			unsigned k = vscanlen;
+
+			sigpass_step(fp, frowstep, dp, bitpos, one,
+			  nmsedec, orient, mqenc, vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			sigpass_step(fp, frowstep, dp, bitpos, one,
+			  nmsedec, orient, mqenc, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			sigpass_step(fp, frowstep, dp, bitpos, one,
+			  nmsedec, orient, mqenc, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			sigpass_step(fp, frowstep, dp, bitpos, one,
+			  nmsedec, orient, mqenc, 0);
+
+		}
+	}
+
+	if (term) {
+		jpc_mqenc_flush(mqenc, term - 1);
+	}
+
+	return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+#define	rawsigpass_step(fp, frowstep, dp, bitpos, one, nmsedec, out, vcausalflag) \
+{ \
+	jpc_fix_t f = *(fp); \
+	if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
+		bool v = (JAS_ABS(*(dp)) & (one)) != 0; \
+		if ((jpc_bitstream_putbit((out), v)) == EOF) { \
+			return -1; \
+		} \
+		if (v) { \
+			*(nmsedec) += JPC_GETSIGNMSEDEC(JAS_ABS(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \
+			v = *(dp) < 0; \
+			if (jpc_bitstream_putbit(out, v) == EOF) { \
+				return -1; \
+			} \
+			JPC_UPDATEFLAGS4(fp, frowstep, v, vcausalflag); \
+			*(fp) |= JPC_SIG; \
+		} \
+		*(fp) |= JPC_VISIT; \
+	} \
+}
+
+static int jpc_encrawsigpass(jpc_bitstream_t *out, int bitpos, bool vcausalflag, jas_matrix_t *flags,
+  const jas_matrix_t *data, int term, long *nmsedec)
+{
+	int i;
+	int one;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fp;
+	jpc_fix_t *fvscanstart;
+
+	*nmsedec = 0;
+	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;
+
+	one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	const jpc_fix_t *dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		const jpc_fix_t *dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			const jpc_fix_t *dp = dvscanstart;
+			unsigned k = vscanlen;
+
+			rawsigpass_step(fp, frowstep, dp, bitpos, one,
+			  nmsedec, out, vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			rawsigpass_step(fp, frowstep, dp, bitpos, one,
+			  nmsedec, out, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			rawsigpass_step(fp, frowstep, dp, bitpos, one,
+			  nmsedec, out, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+
+			rawsigpass_step(fp, frowstep, dp, bitpos, one,
+			  nmsedec, out, 0);
+			if (--k <= 0) {
+				continue;
+			}
+		}
+	}
+
+	if (term) {
+		jpc_bitstream_outalign(out, 0x2a);
+	}
+
+	return 0;
+}
+
+/******************************************************************************\
+* Code for refinement pass.
+\******************************************************************************/
+
+#define	refpass_step(fp, dp, bitpos, one, nmsedec, mqenc, vcausalflag) \
+{ \
+	if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+		(d) = *(dp); \
+		*(nmsedec) += JPC_GETREFNMSEDEC(JAS_ABS(d), (bitpos) + JPC_NUMEXTRABITS); \
+		jpc_mqenc_setcurctx((mqenc), JPC_GETMAGCTXNO(*(fp))); \
+		const bool v = (JAS_ABS(d) & (one)) != 0; \
+		jpc_mqenc_putbit((mqenc), v); \
+		*(fp) |= JPC_REFINE; \
+	} \
+}
+
+static int jpc_encrefpass(jpc_mqenc_t *mqenc, int bitpos, jas_matrix_t *flags, const jas_matrix_t *data,
+  int term, long *nmsedec)
+{
+	int i;
+	int one;
+	int d;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fvscanstart;
+	jpc_fix_t *fp;
+
+	*nmsedec = 0;
+	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;
+
+	one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	const jpc_fix_t *dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		const jpc_fix_t *dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			const jpc_fix_t *dp = dvscanstart;
+			unsigned k = vscanlen;
+
+			refpass_step(fp, dp, bitpos, one, nmsedec,
+			  mqenc, vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			refpass_step(fp, dp, bitpos, one, nmsedec,
+			  mqenc, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			refpass_step(fp, dp, bitpos, one, nmsedec,
+			  mqenc, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			refpass_step(fp, dp, bitpos, one, nmsedec,
+			  mqenc, 0);
+
+		}
+	}
+
+	if (term) {
+		jpc_mqenc_flush(mqenc, term - 1);
+	}
+
+	return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+#define	rawrefpass_step(fp, dp, bitpos, one, nmsedec, out, vcausalflag) \
+{ \
+	jpc_fix_t d; \
+	if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+		d = *(dp); \
+		*(nmsedec) += JPC_GETREFNMSEDEC(JAS_ABS(d), (bitpos) + JPC_NUMEXTRABITS); \
+		const bool v = (JAS_ABS(d) & (one)) != 0; \
+		if (jpc_bitstream_putbit((out), v) == EOF) { \
+			return -1; \
+		} \
+		*(fp) |= JPC_REFINE; \
+	} \
+}
+
+static int jpc_encrawrefpass(jpc_bitstream_t *out, int bitpos, jas_matrix_t *flags,
+  const jas_matrix_t *data, int term, long *nmsedec)
+{
+	int i;
+	int one;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fvscanstart;
+	jpc_fix_t *fp;
+
+	*nmsedec = 0;
+	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;
+
+	one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	const jpc_fix_t *dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		const jpc_fix_t *dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+			fp = fvscanstart;
+			const jpc_fix_t *dp = dvscanstart;
+			unsigned k = vscanlen;
+
+			rawrefpass_step(fp, dp, bitpos, one, nmsedec,
+			  out, vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			rawrefpass_step(fp, dp, bitpos, one, nmsedec,
+			  out, vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			rawrefpass_step(fp, dp, bitpos, one, nmsedec,
+			  out, vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			rawrefpass_step(fp, dp, bitpos, one, nmsedec,
+			  out, vcausalflag);
+
+		}
+	}
+
+	if (term) {
+		jpc_bitstream_outalign(out, 0x2a);
+	}
+
+	return 0;
+}
+
+/******************************************************************************\
+* Code for cleanup pass.
+\******************************************************************************/
+
+#define	clnpass_step(fp, frowstep, dp, bitpos, one, orient, nmsedec, mqenc, label1, label2, vcausalflag) \
+{ \
+	jpc_fix_t f; \
+label1 \
+	f = *(fp); \
+	if (!(f & (JPC_SIG | JPC_VISIT))) { \
+		jpc_mqenc_setcurctx(mqenc, JPC_GETZCCTXNO(f, (orient))); \
+		bool v = (JAS_ABS(*(dp)) & (one)) != 0; \
+		jpc_mqenc_putbit((mqenc), v); \
+		if (v) { \
+label2 \
+			f = *(fp); \
+			/* Coefficient is significant. */ \
+			*(nmsedec) += JPC_GETSIGNMSEDEC(JAS_ABS(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \
+			jpc_mqenc_setcurctx((mqenc), JPC_GETSCCTXNO(f)); \
+			v = ((*(dp) < 0) ? 1 : 0); \
+			jpc_mqenc_putbit((mqenc), v ^ JPC_GETSPB(f)); \
+			JPC_UPDATEFLAGS4((fp), (frowstep), v, vcausalflag); \
+			*(fp) |= JPC_SIG; \
+		} \
+	} \
+	*(fp) &= ~JPC_VISIT; \
+}
+
+static int jpc_encclnpass(jpc_mqenc_t *mqenc, int bitpos, enum jpc_tsfb_orient orient, bool vcausalflag, bool segsymflag, jas_matrix_t *flags,
+  const jas_matrix_t *data, int term, long *nmsedec)
+{
+	int i;
+	jpc_fix_t *fp;
+	int one;
+	jpc_fix_t *fstripestart;
+	jpc_fix_t *fvscanstart;
+
+	*nmsedec = 0;
+	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;
+
+	one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+	fstripestart = jas_matrix_getref(flags, 1, 1);
+	const jpc_fix_t *dstripestart = jas_matrix_getref(data, 0, 0);
+	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+	  dstripestart += dstripestep) {
+		fvscanstart = fstripestart;
+		const jpc_fix_t *dvscanstart = dstripestart;
+		const unsigned vscanlen = JAS_MIN(i, 4);
+		for (unsigned j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+
+			fp = fvscanstart;
+			const jpc_fix_t *dp;
+			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)))) {
+				dp = dvscanstart;
+				for (k = 0; k < vscanlen; ++k) {
+					const bool v = (JAS_ABS(*dp) & one) != 0;
+					if (v) {
+						break;
+					}
+					dp += drowstep;
+				}
+				unsigned runlen = k;
+				if (runlen >= 4) {
+					jpc_mqenc_setcurctx(mqenc, JPC_AGGCTXNO);
+					jpc_mqenc_putbit(mqenc, false);
+					continue;
+				}
+				jpc_mqenc_setcurctx(mqenc, JPC_AGGCTXNO);
+				jpc_mqenc_putbit(mqenc, true);
+				jpc_mqenc_setcurctx(mqenc, JPC_UCTXNO);
+				jpc_mqenc_putbit(mqenc, runlen >> 1);
+				jpc_mqenc_putbit(mqenc, runlen & 1);
+				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 {
+				fp = fvscanstart;
+				dp = dvscanstart;
+				k = vscanlen;
+				goto clnpass_full0;
+			}
+			clnpass_step(fp, frowstep, dp, bitpos, one,
+			  orient, nmsedec, mqenc, clnpass_full0:, clnpass_partial0:, vcausalflag);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			clnpass_step(fp, frowstep, dp, bitpos, one,
+				orient, nmsedec, mqenc, ;, clnpass_partial1:, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			clnpass_step(fp, frowstep, dp, bitpos, one,
+				orient, nmsedec, mqenc, ;, clnpass_partial2:, 0);
+			if (--k <= 0) {
+				continue;
+			}
+			fp += frowstep;
+			dp += drowstep;
+			clnpass_step(fp, frowstep, dp, bitpos, one,
+				orient, nmsedec, mqenc, ;, clnpass_partial3:, 0);
+		}
+	}
+
+	if (segsymflag) {
+		jpc_mqenc_setcurctx(mqenc, JPC_UCTXNO);
+		jpc_mqenc_putbit(mqenc, true);
+		jpc_mqenc_putbit(mqenc, false);
+		jpc_mqenc_putbit(mqenc, true);
+		jpc_mqenc_putbit(mqenc, false);
+	}
+
+	if (term) {
+		jpc_mqenc_flush(mqenc, term - 1);
+	}
+
+	return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
--- /dev/null
+++ b/jpc_t1enc.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 Encoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T1ENC_H
+#define JPC_T1ENC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_enc.h"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Encode all of the code blocks. */
+int jpc_enc_enccblks(jpc_enc_t *enc);
+
+#endif
--- a/jpc_t2cod.c
+++ b/jpc_t2cod.c
@@ -67,6 +67,10 @@
  * $Id$
  */
 
+/******************************************************************************\
+*
+\******************************************************************************/
+
 #include "jpc_t2cod.h"
 #include "jpc_cs.h"
 #include "jpc_math.h"
@@ -73,7 +77,12 @@
 
 #include "jasper/jas_math.h"
 #include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.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);
@@ -80,6 +89,34 @@
 static int jpc_pi_nextpcrl(jpc_pi_t *pi);
 static int jpc_pi_nextcprl(jpc_pi_t *pi);
 
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jpc_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) {
+			jpc_pirlvl_destroy(pirlvl);
+		}
+		jas_free(picomp->pirlvls);
+	}
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
 int jpc_pi_next(jpc_pi_t *pi)
 {
 	int ret;
@@ -95,11 +132,14 @@
 			pi->prcno = 0;
 			pi->lyrno = 0;
 			pi->prgvolfirst = true;
-			if ((unsigned)pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) {
+			if (JAS_CAST(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)) {
+			} else if (JAS_CAST(unsigned, pi->pchgno) ==
+			  jpc_pchglist_numpchgs(pi->pchglist)) {
 				pi->pchg = &pi->defaultpchg;
 			} else {
+				JAS_LOGDEBUGF(10, "jpc_pi_next returning 1\n");
 				return 1;
 			}
 		}
@@ -138,6 +178,8 @@
 {
 	unsigned *prclyrno;
 
+	JAS_LOGDEBUGF(10, "jpc_pi_nextlrcp\n");
+
 	const jpc_pchg_t *pchg = pi->pchg;
 	if (!pi->prgvolfirst) {
 		prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
@@ -179,6 +221,7 @@
 static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
 {
 	unsigned *prclyrno;
+	JAS_LOGDEBUGF(10, "jpc_pi_nextrlcp\n");
 
 	const jpc_pchg_t *pchg = pi->pchg;
 	if (!pi->prgvolfirst) {
@@ -230,6 +273,8 @@
 	uint_fast32_t trx0;
 	uint_fast32_t try0;
 
+	JAS_LOGDEBUGF(10, "jpc_pi_nextrpcl\n");
+
 	const jpc_pchg_t *pchg = pi->pchg;
 	if (!pi->prgvolfirst) {
 		goto skip;
@@ -260,9 +305,11 @@
 		pi->prgvolfirst = 0;
 	}
 
-	if (pi->xstep == 0 || pi->ystep == 0)
+	if (pi->xstep == 0 || pi->ystep == 0) {
 		/* avoid division by zero */
+		jas_logerrorf("xstep and ystep must be nonzero\n");
 		return -1;
+	}
 
 	for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
 	  pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
@@ -334,6 +381,8 @@
 	uint_fast32_t rpx;
 	uint_fast32_t rpy;
 
+	JAS_LOGDEBUGF(10, "jpc_pi_nextpcrl\n");
+
 	const jpc_pchg_t *pchg = pi->pchg;
 	if (!pi->prgvolfirst) {
 		goto skip;
@@ -364,9 +413,11 @@
 		pi->prgvolfirst = 0;
 	}
 
-	if (pi->xstep == 0 || pi->ystep == 0)
+	if (pi->xstep == 0 || pi->ystep == 0) {
 		/* avoid division by zero */
+		jas_logerrorf("xstep and ystep must be nonzero\n");
 		return -1;
+	}
 
 	for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep -
 	  (pi->y % pi->ystep)) {
@@ -432,6 +483,8 @@
 	uint_fast32_t rpx;
 	uint_fast32_t rpy;
 
+	JAS_LOGDEBUGF(10, "jpc_pi_nextcprl\n");
+
 	const jpc_pchg_t *pchg = pi->pchg;
 	if (!pi->prgvolfirst) {
 		goto skip;
@@ -439,9 +492,17 @@
 		pi->prgvolfirst = 0;
 	}
 
-	if (pi->xstep == 0 || pi->ystep == 0)
-		/* avoid division by zero */
+#if 0
+	/*
+	This disabled code is wrong.  xstep and ystep need not be set yet.
+	This will cause some valid code streams to fail to be decoded.
+	*/
+	if (pi->xstep == 0 || pi->ystep == 0) {
+		/* avoid later division by zero */
+		jas_logerrorf("xstep and ystep must be nonzero\n");
 		return -1;
+	}
+#endif
 
 	for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno];
 	  pi->compno < pchg->compnoend && pi->compno < pi->numcomps;
@@ -452,6 +513,7 @@
 		  JAS_UINTFAST32_NUMBITS - 2 ||
 		  pirlvl->prcheightexpn + pi->picomp->numrlvls >
 		  JAS_UINTFAST32_NUMBITS - 2) {
+			jas_logerrorf("overflow detected\n");
 			return -1;
 		}
 		pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
@@ -460,12 +522,37 @@
 		  (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
 		for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
 		  rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
+			/* Perform the following calculation in an overflow-safe manner,
+			setting the result to zero upon overflow:
 			pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
 			  (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
 			  pi->picomp->numrlvls - rlvlno - 1)));
+			*/
+			pi->xstep = JAS_MIN(pi->xstep, jas_safeui64_to_int(
+			  jas_safeui64_mul(
+			    jas_safeui64_from_intmax(pi->picomp->hsamp),
+			    jas_safeui64_pow2_intmax(pirlvl->prcwidthexpn +
+			      pi->picomp->numrlvls - rlvlno - 1)), 0));
+			if (!pi->xstep) {
+				jas_logerrorf("overflow in x-step calculation\n");
+				return -1;
+			}
+
+			/* Perform the following calculation in an overflow-safe manner,
+			setting the result to zero upon overflow:
 			pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
 			  (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
 			  pi->picomp->numrlvls - rlvlno - 1)));
+			*/
+			pi->ystep = JAS_MIN(pi->ystep, jas_safeui64_to_int(
+			  jas_safeui64_mul(
+			    jas_safeui64_from_intmax(pi->picomp->vsamp),
+			    jas_safeui64_pow2_intmax(pirlvl->prcheightexpn +
+			      pi->picomp->numrlvls - rlvlno - 1)), 0));
+			if (!pi->ystep) {
+				jas_logerrorf("overflow in y-step calculation\n");
+				return -1;
+			}
 		}
 		for (pi->y = pi->ystart; pi->y < pi->yend;
 		  pi->y += pi->ystep - (pi->y % pi->ystep)) {
@@ -516,26 +603,10 @@
 	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;
@@ -568,11 +639,68 @@
 	return pi;
 }
 
+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;
+}
+
 int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg)
 {
 	return jpc_pchglist_insert(pi->pchglist, -1, pchg);
 }
 
+/* For debugging only. */
+void jpc_pi_dump(const jpc_pi_t *pi)
+{
+	jas_eprintf("numlyrs=%d\n", pi->numlyrs);
+	jas_eprintf("maxrlvls=%d\n", pi->maxrlvls);
+	jas_eprintf("numcomps=%d\n", pi->numcomps);
+	jas_eprintf("compno=%d\n", pi->compno);
+	jas_eprintf("rlvlno=%d\n", pi->rlvlno);
+	jas_eprintf("prcno=%d\n", pi->prcno);
+	jas_eprintf("lyrno=%d\n", pi->lyrno);
+	jas_eprintf("x=%d\n", pi->x);
+	jas_eprintf("y=%d\n", pi->y);
+	jas_eprintf("xstep=%d\n", pi->xstep);
+	jas_eprintf("ystep=%d\n", pi->ystep);
+	jas_eprintf("xstart=%d\n", pi->xstart);
+	jas_eprintf("ystart=%d\n", pi->ystart);
+	jas_eprintf("xend=%d\n", pi->xend);
+	jas_eprintf("yend=%d\n", pi->yend);
+	jas_eprintf("defaultpchg=%d\n", pi->defaultpchg);
+	jas_eprintf("pchgno=%d\n", pi->pchgno);
+	jas_eprintf("prgvolfirst=%d\n", pi->prgvolfirst);
+	jas_eprintf("valid=%d\n", pi->valid);
+	jas_eprintf("pktno=%d\n", pi->pktno);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
 jpc_pchglist_t *jpc_pchglist_create()
 {
 	jpc_pchglist_t *pchglist;
@@ -671,32 +799,4 @@
 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;
 }
--- a/jpc_t2cod.h
+++ b/jpc_t2cod.h
@@ -298,4 +298,10 @@
 /* Copy a progression change. */
 jpc_pchg_t *jpc_pchg_copy(const jpc_pchg_t *pchg);
 
+/******************************************************************************\
+* Functions/macros for debugging.
+\******************************************************************************/
+
+void jpc_pi_dump(const jpc_pi_t *pi);
+
 #endif
--- a/jpc_t2dec.c
+++ b/jpc_t2dec.c
@@ -189,17 +189,18 @@
 	if (cp->csty & JPC_COD_SOP) {
 		if (jpc_dec_lookahead(in) == JPC_MS_SOP) {
 			if (!(ms = jpc_getms(in, dec->cstate))) {
+				jas_logerrorf("cannot get marker segment\n");
 				return -1;
 			}
 			if (jpc_ms_gettype(ms) != JPC_MS_SOP) {
 				jpc_ms_destroy(ms);
-				jas_eprintf("cannot get (SOP) marker segment\n");
+				jas_logerrorf("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",
+				jas_logerrorf("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;
@@ -211,15 +212,17 @@
 	const uint_least64_t hdroffstart = jas_stream_getrwcount(pkthdrstream);
 
 	if (!(inb = jpc_bitstream_sopen(pkthdrstream, "r"))) {
+		jas_logerrorf("cannot open bitstream\n");
 		return -1;
 	}
 
 	if ((present = jpc_bitstream_getbit(inb)) < 0) {
+		jas_logerrorf("cannot get bit\n");
 		jpc_bitstream_close(inb);
 		return 1;
 	}
-	JAS_DBGLOG(10, ("\n", present));
-	JAS_DBGLOG(10, ("present=%d ", present));
+	JAS_LOGDEBUGF(10, "\n", present);
+	JAS_LOGDEBUGF(10, "present=%d ", present);
 
 	/* Is the packet non-empty? */
 	if (present) {
@@ -245,17 +248,19 @@
 				if (!cblk->numpasses) {
 					leaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);
 					if ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {
+						jas_logerrorf("cannot decode tagtree\n");
 						jpc_bitstream_close(inb);
 						return -1;
 					}
 				} else {
 					if ((included = jpc_bitstream_getbit(inb)) < 0) {
+						jas_logerrorf("cannot get bit\n");
 						jpc_bitstream_close(inb);
 						return -1;
 					}
 				}
-				JAS_DBGLOG(10, ("\n"));
-				JAS_DBGLOG(10, ("included=%d ", included));
+				JAS_LOGDEBUGF(10, "\n");
+				JAS_LOGDEBUGF(10, "included=%d ", included);
 				if (!included) {
 					continue;
 				}
@@ -264,6 +269,7 @@
 					leaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);
 					for (;;) {
 						if ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {
+							jas_logerrorf("cannot decode tagtree\n");
 							jpc_bitstream_close(inb);
 							return -1;
 						}
@@ -276,10 +282,11 @@
 					cblk->firstpassno = cblk->numimsbs * 3;
 				}
 				if ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {
+					jas_logerrorf("cannot get number of new passes\n");
 					jpc_bitstream_close(inb);
 					return -1;
 				}
-				JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses));
+				JAS_LOGDEBUGF(10, "numnewpasses=%d ", numnewpasses);
 				seg = cblk->curseg;
 				const unsigned savenumnewpasses = numnewpasses;
 				unsigned mycounter = 0;
@@ -295,15 +302,17 @@
 						   assertion failure
 						   in
 						   jpc_floorlog2() */
+						jas_logerrorf("first pass number unreasonably large\n");
 						jpc_bitstream_close(inb);
 						return -1;
 					}
 					if ((m = jpc_getcommacode(inb)) < 0) {
+						jas_logerrorf("cannot get comma code\n");
 						jpc_bitstream_close(inb);
 						return -1;
 					}
 					cblk->numlenbits += m;
-					JAS_DBGLOG(10, ("increment=%d ", m));
+					JAS_LOGDEBUGF(10, "increment=%d ", m);
 					while (numnewpasses > 0) {
 						const unsigned passno = cblk->firstpassno + cblk->numpasses + mycounter;
 						if (passno >= 10000) {
@@ -314,6 +323,7 @@
 							   value and would
 							   later crash in
 							   jpc_floorlog2() */
+							jas_logerrorf("pass number unreasonably large\n");
 							jpc_bitstream_close(inb);
 							return -1;
 						}
@@ -321,6 +331,7 @@
 						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())) {
+								jas_logerrorf("cannot allocate segment\n");
 								jpc_bitstream_close(inb);
 								return -1;
 							}
@@ -337,9 +348,10 @@
 						numnewpasses -= n;
 						if ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {
 							jpc_bitstream_close(inb);
+							jas_logerrorf("cannot get bits\n");
 							return -1;
 						}
-						JAS_DBGLOG(10, ("len=%d ", len));
+						JAS_LOGDEBUGF(10, "len=%d ", len);
 						if (!discard) {
 							seg->lyrno = lyrno;
 							seg->numpasses += n;
@@ -357,7 +369,7 @@
 
 	} else {
 		if (jpc_bitstream_inalign(inb, 0x7f, 0)) {
-			jas_eprintf("alignment failed\n");
+			jas_logerrorf("alignment failed\n");
 			jpc_bitstream_close(inb);
 			return -1;
 		}
@@ -364,21 +376,21 @@
 	}
 	jpc_bitstream_close(inb);
 
-	if (jas_getdbglevel() >= 5) {
+	if (jas_get_debug_level() >= 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,
+		jas_logdebugf(5, "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");
+			jas_logerrorf("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");
+			jas_logerrorf("missing EPH marker segment\n");
 			return -1;
 		}
 		jpc_ms_destroy(ms);
@@ -386,8 +398,8 @@
 
 	/* decode the packet body. */
 
-	if (jas_getdbglevel() >= 1) {
-		jas_eprintf("packet body offset=%06ld\n", (long) jas_stream_getrwcount(in));
+	if (jas_get_debug_level() >= 1) {
+		jas_logdebugf(1, "packet body offset=%06ld\n", (long) jas_stream_getrwcount(in));
 	}
 
 	if (!discard) {
@@ -410,14 +422,19 @@
 				while (seg) {
 					if (!seg->stream) {
 						if (!(seg->stream = jas_stream_memopen(0, 0))) {
+							jas_logerrorf("cannot open memory stream\n");
 							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);
+					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) {
+							jas_logerrorf("jas_getdata failed\n");
 							return -1;
 						}
 						seg->cnt = 0;
@@ -431,6 +448,7 @@
 		}
 	} else {
 		if (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {
+			jas_logerrorf("jas_stream_gobble failed\n");
 			return -1;
 		}
 	}
@@ -449,7 +467,8 @@
 	tile = dec->curtile;
 	pi = tile->pi;
 	for (;;) {
-		if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
+		if (!tile->pkthdrstream ||
+		  jas_stream_peekc(tile->pkthdrstream) == EOF) {
 			switch (jpc_dec_lookahead(in)) {
 			case JPC_MS_EOC:
 			case JPC_MS_SOT:
@@ -459,18 +478,24 @@
 			case 0:
 				break;
 			default:
+				jas_logerrorf("jpc_dec_lookahead failed\n");
 				return -1;
 			}
 		}
+		// jpc_pi_dump(pi);
 		if ((ret = jpc_pi_next(pi))) {
+			if (ret < 0) {
+				jas_logerrorf("jpc_pi_next failed\n");
+			}
+			//jas_logerrorf("jpc_pi_next failed (%d)\n", ret);
 			return ret;
 		}
 		if (dec->maxpkts >= 0 && dec->numpkts >= (unsigned)dec->maxpkts) {
-			jas_eprintf("warning: stopping decode prematurely as requested\n");
+			jas_logwarnf("warning: stopping decode prematurely as requested\n");
 			return 0;
 		}
-		if (jas_getdbglevel() >= 1) {
-			jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
+		if (jas_get_debug_level() >= 1) {
+			jas_logdebugf(1, "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));
@@ -477,6 +502,7 @@
 		}
 		if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi),
 		  jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
+			jas_logerrorf("jpc_dec_decodepkt failed\n");
 			return -1;
 		}
 		++dec->numpkts;
--- /dev/null
+++ b/jpc_t2enc.c
@@ -1,0 +1,656 @@
+/*
+ * 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 Encoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_t2enc.h"
+#include "jpc_t2cod.h"
+#include "jpc_tagtree.h"
+#include "jpc_enc.h"
+#include "jpc_math.h"
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+static int jpc_putcommacode(jpc_bitstream_t *out, int n)
+{
+	assert(n >= 0);
+
+	while (--n >= 0) {
+		if (jpc_bitstream_putbit(out, 1) == EOF) {
+			return -1;
+		}
+	}
+	if (jpc_bitstream_putbit(out, 0) == EOF) {
+		return -1;
+	}
+	return 0;
+}
+
+static int jpc_putnumnewpasses(jpc_bitstream_t *out, int n)
+{
+	int ret;
+
+	if (n <= 0) {
+		return -1;
+	} else if (n == 1) {
+		ret = jpc_bitstream_putbit(out, 0);
+	} else if (n == 2) {
+		ret = jpc_bitstream_putbits(out, 2, 2);
+	} else if (n <= 5) {
+		ret = jpc_bitstream_putbits(out, 4, 0xc | (n - 3));
+	} else if (n <= 36) {
+		ret = jpc_bitstream_putbits(out, 9, 0x1e0 | (n - 6));
+	} else if (n <= 164) {
+		ret = jpc_bitstream_putbits(out, 16, 0xff80 | (n - 37));
+	} else {
+		/* The standard has no provision for encoding a larger value.
+		In practice, however, it is highly unlikely that this
+		limitation will ever be encountered. */
+		return -1;
+	}
+
+	return (ret != EOF) ? 0 : (-1);
+}
+
+int jpc_enc_encpkts(jpc_enc_t *enc, jas_stream_t *out)
+{
+	jpc_enc_tile_t *tile;
+	jpc_pi_t *pi;
+
+	tile = enc->curtile;
+
+	jpc_init_t2state(enc, false);
+	pi = tile->pi;
+	jpc_pi_init(pi);
+
+	if (!jpc_pi_next(pi)) {
+		for (;;) {
+			if (jpc_enc_encpkt(enc, out, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),
+			  jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
+				return -1;
+			}
+			if (jpc_pi_next(pi)) {
+				break;
+			}
+		}
+	}
+	
+	return 0;
+}
+
+int jpc_enc_encpkt(jpc_enc_t *enc, jas_stream_t *out, unsigned compno, unsigned lvlno, unsigned prcno, unsigned lyrno)
+{
+	jpc_enc_tcmpt_t *comp;
+	jpc_enc_rlvl_t *lvl;
+	jpc_enc_band_t *band;
+	jpc_enc_band_t *endbands;
+	jpc_enc_cblk_t *cblk;
+	jpc_enc_cblk_t *endcblks;
+	jpc_bitstream_t *outb;
+	jpc_enc_pass_t *pass;
+	jpc_enc_pass_t *startpass;
+	jpc_enc_pass_t *lastpass;
+	jpc_enc_pass_t *endpass;
+	jpc_enc_pass_t *endpasses;
+	int i;
+	int ret;
+	jpc_tagtreenode_t *leaf;
+	int t1;
+	int t2;
+	jpc_enc_tile_t *tile;
+	jpc_enc_prc_t *prc;
+	jpc_enc_cp_t *cp;
+	jpc_ms_t *ms;
+
+	JAS_LOGDEBUGF(10, "encoding packet begin %d %d %d %d\n", compno, lvlno,
+	  prcno, lyrno);
+
+	tile = enc->curtile;
+	cp = enc->cp;
+
+	if (cp->tcp.csty & JPC_COD_SOP) {
+		if (!(ms = jpc_ms_create(JPC_MS_SOP))) {
+			return -1;
+		}
+		ms->parms.sop.seqno = jpc_pi_getind(tile->pi);
+		if (jpc_putms(out, enc->cstate, ms)) {
+			return -1;
+		}
+		jpc_ms_destroy(ms);
+	}
+
+	if (!(outb = jpc_bitstream_sopen(out, "w+"))) {
+		return -1;
+	}
+
+	if (jpc_bitstream_putbit(outb, 1) == EOF) {
+		goto error_close;
+	}
+	JAS_LOGDEBUGF(10, "present.\n");
+
+	comp = &tile->tcmpts[compno];
+	lvl = &comp->rlvls[lvlno];
+	endbands = &lvl->bands[lvl->numbands];
+	for (band = lvl->bands; band != endbands; ++band) {
+		if (!band->data) {
+			continue;
+		}
+		prc = &band->prcs[prcno];
+		if (!prc->cblks) {
+			continue;
+		}
+
+		endcblks = &prc->cblks[prc->numcblks];
+		for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+			if (!lyrno) {
+				leaf = jpc_tagtree_getleaf(prc->nlibtree, cblk - prc->cblks);
+				jpc_tagtree_setvalue(prc->nlibtree, leaf, cblk->numimsbs);
+			}
+			pass = cblk->curpass;
+			const bool included = (pass && pass->lyrno == lyrno);
+			if (included && (!cblk->numencpasses)) {
+				assert(pass->lyrno == lyrno);
+				leaf = jpc_tagtree_getleaf(prc->incltree,
+				  cblk - prc->cblks);
+				jpc_tagtree_setvalue(prc->incltree, leaf, pass->lyrno);
+			}
+		}
+
+		endcblks = &prc->cblks[prc->numcblks];
+		for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+			pass = cblk->curpass;
+			const bool included = (pass && pass->lyrno == lyrno);
+			if (!cblk->numencpasses) {
+				leaf = jpc_tagtree_getleaf(prc->incltree,
+				  cblk - prc->cblks);
+				if (jpc_tagtree_encode(prc->incltree, leaf, lyrno + 1, outb) <
+				  0) {
+					goto error_close;
+				}
+			} else {
+				if (jpc_bitstream_putbit(outb, included) == EOF) {
+					goto error_close;
+				}
+			}
+			JAS_LOGDEBUGF(10, "included=%d ", included);
+			if (!included) {
+				continue;
+			}
+			if (!cblk->numencpasses) {
+				i = 1;
+				leaf = jpc_tagtree_getleaf(prc->nlibtree, cblk - prc->cblks);
+				for (;;) {
+					if ((ret = jpc_tagtree_encode(prc->nlibtree, leaf, i,
+					  outb)) < 0) {
+						goto error_close;
+					}
+					if (ret) {
+						break;
+					}
+					++i;
+				}
+				assert(leaf->known_ && i == leaf->value_ + 1);
+			}
+
+			endpasses = &cblk->passes[cblk->numpasses];
+			startpass = pass;
+			endpass = startpass;
+			while (endpass != endpasses && endpass->lyrno == lyrno){
+				++endpass;
+			}
+			const unsigned numnewpasses = endpass - startpass;
+			if (jpc_putnumnewpasses(outb, numnewpasses)) {
+				goto error_close;
+			}
+			JAS_LOGDEBUGF(10, "numnewpasses=%d ", numnewpasses);
+
+			lastpass = endpass - 1;
+			unsigned n = startpass->start;
+			unsigned passcount = 1;
+			unsigned maxadjust = 0;
+			for (pass = startpass; pass != endpass; ++pass) {
+				if (pass->term || pass == lastpass) {
+					unsigned datalen = pass->end - n;
+					t1 = jpc_int_firstone(datalen) + 1;
+					t2 = cblk->numlenbits + jpc_floorlog2(passcount);
+					const unsigned adjust = JAS_MAX(t1 - t2, 0);
+					maxadjust = JAS_MAX(adjust, maxadjust);
+					n += datalen;
+					passcount = 1;
+				} else {
+					++passcount;
+				}
+			}
+			if (jpc_putcommacode(outb, maxadjust)) {
+				goto error_close;
+			}
+			cblk->numlenbits += maxadjust;
+
+			lastpass = endpass - 1;
+			n = startpass->start;
+			passcount = 1;
+			for (pass = startpass; pass != endpass; ++pass) {
+				if (pass->term || pass == lastpass) {
+					unsigned datalen = pass->end - n;
+					assert(jpc_int_firstone(datalen) < cblk->numlenbits +
+					  (int)jpc_floorlog2(passcount));
+					if (jpc_bitstream_putbits(outb, cblk->numlenbits +
+					  jpc_floorlog2(passcount), datalen) == EOF) {
+						goto error_close;
+					}
+					n += datalen;
+					passcount = 1;
+				} else {
+					++passcount;
+				}
+			}
+		}
+	}
+
+	jpc_bitstream_outalign(outb, 0);
+	jpc_bitstream_close(outb);
+
+	if (cp->tcp.csty & JPC_COD_EPH) {
+		if (!(ms = jpc_ms_create(JPC_MS_EPH))) {
+			return -1;
+		}
+		if (jpc_putms(out, enc->cstate, ms)) {
+			return -1;
+		}
+		jpc_ms_destroy(ms);
+	}
+
+	comp = &tile->tcmpts[compno];
+	lvl = &comp->rlvls[lvlno];
+	endbands = &lvl->bands[lvl->numbands];
+	for (band = lvl->bands; band != endbands; ++band) {
+		if (!band->data) {
+			continue;
+		}
+		prc = &band->prcs[prcno];
+		if (!prc->cblks) {
+			continue;
+		}
+		endcblks = &prc->cblks[prc->numcblks];
+		for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+			pass = cblk->curpass;
+
+			if (!pass) {
+				continue;
+			}
+			if (pass->lyrno != lyrno) {
+				assert(pass->lyrno > lyrno);
+				continue;
+			}
+
+			endpasses = &cblk->passes[cblk->numpasses];
+			startpass = pass;
+			endpass = startpass;
+			while (endpass != endpasses && endpass->lyrno == lyrno){
+				++endpass;
+			}
+			lastpass = endpass - 1;
+			const unsigned numnewpasses = endpass - startpass;
+
+			jas_stream_seek(cblk->stream, startpass->start, SEEK_SET);
+			assert(jas_stream_tell(cblk->stream) == startpass->start);
+			if (jas_stream_copy(out, cblk->stream, lastpass->end -
+			  startpass->start)) {
+				return -1;
+			}
+			cblk->curpass = (endpass != endpasses) ? endpass : 0;
+			cblk->numencpasses += numnewpasses;
+
+		}
+	}
+
+	JAS_LOGDEBUGF(10, "encoding packet end\n");
+
+	return 0;
+
+error_close:
+	jpc_bitstream_close(outb);
+	return -1;
+}
+
+void jpc_save_t2state(jpc_enc_t *enc)
+{
+/* stream pos in embedded T1 stream may be wrong since not saved/restored! */
+
+	jpc_enc_tcmpt_t *comp;
+	jpc_enc_tcmpt_t *endcomps;
+	jpc_enc_rlvl_t *lvl;
+	jpc_enc_rlvl_t *endlvls;
+	jpc_enc_band_t *band;
+	jpc_enc_band_t *endbands;
+	jpc_enc_cblk_t *cblk;
+	jpc_enc_cblk_t *endcblks;
+	jpc_enc_tile_t *tile;
+	unsigned prcno;
+	jpc_enc_prc_t *prc;
+
+	tile = enc->curtile;
+
+	endcomps = &tile->tcmpts[tile->numtcmpts];
+	for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+		endlvls = &comp->rlvls[comp->numrlvls];
+		for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+			if (!lvl->bands) {
+				continue;
+			}
+			endbands = &lvl->bands[lvl->numbands];
+			for (band = lvl->bands; band != endbands; ++band) {
+				if (!band->data) {
+					continue;
+				}
+				for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
+					if (!prc->cblks) {
+						continue;
+					}
+					jpc_tagtree_copy(prc->savincltree, prc->incltree);
+					jpc_tagtree_copy(prc->savnlibtree, prc->nlibtree);
+					endcblks = &prc->cblks[prc->numcblks];
+					for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+						cblk->savedcurpass = cblk->curpass;
+						cblk->savednumencpasses = cblk->numencpasses;
+						cblk->savednumlenbits = cblk->numlenbits;
+					}
+				}
+			}
+		}
+	}
+
+}
+
+void jpc_restore_t2state(jpc_enc_t *enc)
+{
+
+	jpc_enc_tcmpt_t *comp;
+	jpc_enc_tcmpt_t *endcomps;
+	jpc_enc_rlvl_t *lvl;
+	jpc_enc_rlvl_t *endlvls;
+	jpc_enc_band_t *band;
+	jpc_enc_band_t *endbands;
+	jpc_enc_cblk_t *cblk;
+	jpc_enc_cblk_t *endcblks;
+	jpc_enc_tile_t *tile;
+	unsigned prcno;
+	jpc_enc_prc_t *prc;
+
+	tile = enc->curtile;
+
+	endcomps = &tile->tcmpts[tile->numtcmpts];
+	for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+		endlvls = &comp->rlvls[comp->numrlvls];
+		for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+			if (!lvl->bands) {
+				continue;
+			}
+			endbands = &lvl->bands[lvl->numbands];
+			for (band = lvl->bands; band != endbands; ++band) {
+				if (!band->data) {
+					continue;
+				}
+				for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
+					if (!prc->cblks) {
+						continue;
+					}
+					jpc_tagtree_copy(prc->incltree, prc->savincltree);
+					jpc_tagtree_copy(prc->nlibtree, prc->savnlibtree);
+					endcblks = &prc->cblks[prc->numcblks];
+					for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+						cblk->curpass = cblk->savedcurpass;
+						cblk->numencpasses = cblk->savednumencpasses;
+						cblk->numlenbits = cblk->savednumlenbits;
+					}
+				}
+			}
+		}
+	}
+}
+
+void jpc_init_t2state(jpc_enc_t *enc, bool raflag)
+{
+/* It is assumed that band->numbps and cblk->numbps precomputed */
+
+	jpc_enc_tcmpt_t *comp;
+	jpc_enc_tcmpt_t *endcomps;
+	jpc_enc_rlvl_t *lvl;
+	jpc_enc_rlvl_t *endlvls;
+	jpc_enc_band_t *band;
+	jpc_enc_band_t *endbands;
+	jpc_enc_cblk_t *cblk;
+	jpc_enc_cblk_t *endcblks;
+	jpc_enc_pass_t *pass;
+	jpc_enc_pass_t *endpasses;
+	jpc_tagtreenode_t *leaf;
+	jpc_enc_tile_t *tile;
+	unsigned prcno;
+	jpc_enc_prc_t *prc;
+
+	tile = enc->curtile;
+
+	endcomps = &tile->tcmpts[tile->numtcmpts];
+	for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+		endlvls = &comp->rlvls[comp->numrlvls];
+		for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+			if (!lvl->bands) {
+				continue;
+			}
+			endbands = &lvl->bands[lvl->numbands];
+			for (band = lvl->bands; band != endbands; ++band) {
+				if (!band->data) {
+					continue;
+				}
+				for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
+					if (!prc->cblks) {
+						continue;
+					}
+					jpc_tagtree_reset(prc->incltree);
+					jpc_tagtree_reset(prc->nlibtree);
+					endcblks = &prc->cblks[prc->numcblks];
+					for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+						if (jas_stream_rewind(cblk->stream)) {
+							assert(0);
+						}
+						cblk->curpass = (cblk->numpasses > 0) ? cblk->passes : 0;
+						cblk->numencpasses = 0;
+						cblk->numlenbits = 3;
+						cblk->numimsbs = band->numbps - cblk->numbps;
+						assert(cblk->numimsbs >= 0);
+						leaf = jpc_tagtree_getleaf(prc->nlibtree, cblk - prc->cblks);
+						jpc_tagtree_setvalue(prc->nlibtree, leaf, cblk->numimsbs);
+
+						if (raflag) {
+							endpasses = &cblk->passes[cblk->numpasses];
+							for (pass = cblk->passes; pass != endpasses; ++pass) {
+								pass->lyrno = 0;
+							}
+						}
+					}
+				}
+			}
+		}
+	}
+
+}
+
+jpc_pi_t *jpc_enc_pi_create(jpc_enc_cp_t *cp, jpc_enc_tile_t *tile)
+{
+	jpc_pi_t *pi;
+	unsigned compno;
+	jpc_picomp_t *picomp;
+	jpc_pirlvl_t *pirlvl;
+	jpc_enc_tcmpt_t *tcomp;
+	unsigned rlvlno;
+	jpc_enc_rlvl_t *rlvl;
+	unsigned prcno;
+	unsigned *prclyrno;
+
+	if (!(pi = jpc_pi_create0())) {
+		return 0;
+	}
+	pi->pktno = -1;
+	pi->numcomps = cp->numcmpts;
+	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->tcmpts, 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 (rlvl->numprcs) {
+				if (!(pirlvl->prclyrnos = jas_alloc2(pirlvl->numprcs,
+				  sizeof(long)))) {
+					jpc_pi_destroy(pi);
+					return 0;
+				}
+			} else {
+				pirlvl->prclyrnos = 0;
+			}
+		}
+	}
+
+	pi->maxrlvls = 0;
+	for (compno = 0, tcomp = tile->tcmpts, picomp = pi->picomps;
+	  compno < pi->numcomps; ++compno, ++tcomp, ++picomp) {
+		picomp->hsamp = cp->ccps[compno].sampgrdstepx;
+		picomp->vsamp = cp->ccps[compno].sampgrdstepy;
+		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->numlyrs;
+	pi->xstart = tile->tlx;
+	pi->ystart = tile->tly;
+	pi->xend = tile->brx;
+	pi->yend = tile->bry;
+
+	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->prg;
+	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;
+}
--- /dev/null
+++ b/jpc_t2enc.h
@@ -1,0 +1,105 @@
+/*
+ * 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 Encoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T2ENC_H
+#define JPC_T2ENC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_stream.h"
+
+#include "jpc_enc.h"
+#include "jpc_t2cod.h"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Encode the packets for a tile. */
+int jpc_enc_encpkts(jpc_enc_t *enc, jas_stream_t *out);
+
+/* Encode the specified packet. */
+int jpc_enc_encpkt(jpc_enc_t *enc, jas_stream_t *out, unsigned compno,
+  unsigned lvlno, unsigned prcno, unsigned lyrno);
+
+/* Save the tier-2 coding state. */
+void jpc_save_t2state(jpc_enc_t *enc);
+
+/* Restore the tier-2 coding state. */
+void jpc_restore_t2state(jpc_enc_t *enc);
+
+/* Initialize the tier-2 coding state. */
+void jpc_init_t2state(jpc_enc_t *enc, bool raflag);
+
+/* Create a packet iterator for the encoder. */
+jpc_pi_t *jpc_enc_pi_create(jpc_enc_cp_t *cp, jpc_enc_tile_t *tile);
+
+#endif
--- a/jpc_tagtree.c
+++ b/jpc_tagtree.c
@@ -237,8 +237,7 @@
 {
 	jpc_tagtreenode_t *node;
 
-	/* Avoid compiler warnings about unused parameters. */
-	USED(tree);
+	JAS_UNUSED(tree);
 
 	assert(value >= 0);
 
@@ -266,8 +265,7 @@
 	jpc_tagtreenode_t *node;
 	int low;
 
-	/* Avoid compiler warnings about unused parameters. */
-	USED(tree);
+	JAS_UNUSED(tree);
 
 	assert(leaf);
 	assert(threshold >= 0);
@@ -327,8 +325,7 @@
 	int low;
 	int ret;
 
-	/* Avoid compiler warnings about unused parameters. */
-	USED(tree);
+	JAS_UNUSED(tree);
 
 	assert(threshold >= 0);
 
@@ -365,4 +362,22 @@
 	}
 
 	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;
+	}
 }
--- a/jpc_tagtree.h
+++ b/jpc_tagtree.h
@@ -159,4 +159,7 @@
 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
--- a/jpc_tsfb.c
+++ b/jpc_tsfb.c
@@ -77,7 +77,12 @@
 #include "jpc_fix.h"
 
 #include "jasper/jas_seq.h"
+#include "jasper/jas_malloc.h"
 
+/******************************************************************************\
+* Function prototypes.
+\******************************************************************************/
+
 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);
 
@@ -84,7 +89,7 @@
 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,
+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);
 
@@ -96,7 +101,7 @@
 {
 	jpc_tsfb_t *tsfb;
 
-	if (!(tsfb = malloc(sizeof(jpc_tsfb_t))))
+	if (!(tsfb = jas_malloc(sizeof(jpc_tsfb_t))))
 		return 0;
 
 	if (numlvls > 0) {
@@ -118,7 +123,7 @@
 
 void jpc_tsfb_destroy(jpc_tsfb_t *tsfb)
 {
-	free(tsfb);
+	jas_free(tsfb);
 }
 
 int jpc_tsfb_analyze(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
@@ -212,7 +217,7 @@
 	return band - bands;
 }
 
-static void jpc_tsfb_getbands2(jpc_tsfb_t *tsfb, int locxstart, int locystart,
+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)
 {
--- /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
--- a/mklib
+++ b/mklib
@@ -9,25 +9,60 @@
 	jas_iccdata.$O\
 	jas_image.$O\
 	jas_init.$O\
+	jas_malloc.$O\
 	jas_seq.$O\
 	jas_stream.$O\
+	jas_string.$O\
+	jas_tvp.$O\
+	jas_version.$O\
 	jp2_cod.$O\
 	jp2_dec.$O\
+	jp2_enc.$O\
 	jpc_bs.$O\
+	jpc_cod.$O\
 	jpc_cs.$O\
 	jpc_dec.$O\
+	jpc_enc.$O\
 	jpc_math.$O\
 	jpc_mct.$O\
 	jpc_mqcod.$O\
 	jpc_mqdec.$O\
+	jpc_mqenc.$O\
 	jpc_qmfb.$O\
 	jpc_t1cod.$O\
 	jpc_t1dec.$O\
+	jpc_t1enc.$O\
 	jpc_t2cod.$O\
 	jpc_t2dec.$O\
+	jpc_t2enc.$O\
 	jpc_tagtree.$O\
 	jpc_tsfb.$O\
+	jpc_util.$O\
 
 HFILES=\
+	jp2_cod.h\
+	jp2_dec.h\
+	jpc_bs.h\
+	jpc_cod.h\
+	jpc_cs.h\
+	jpc_dec.h\
+	jpc_enc.h\
+	jpc_fix.h\
+	jpc_flt.h\
+	jpc_math.h\
+	jpc_mct.h\
+	jpc_mqcod.h\
+	jpc_mqdec.h\
+	jpc_mqenc.h\
+	jpc_qmfb.h\
+	jpc_t1cod.h\
+	jpc_t1dec.h\
+	jpc_t1enc.h\
+	jpc_t2cod.h\
+	jpc_t2dec.h\
+	jpc_t2enc.h\
+	jpc_tagtree.h\
+	jpc_tsfb.h\
+	jpc_util.h\
 
 </sys/src/cmd/mklib